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_in_dependent_base) << &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 // If we already know which single declaration is referenced, just annotate 1188 // that declaration directly. Defer resolving even non-overloaded class 1189 // member accesses, as we need to defer certain access checks until we know 1190 // the context. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Otherwise, this is an overload set that we will need to resolve later. 1196 Result.suppressDiagnostics(); 1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1200 Result.begin(), Result.end())); 1201 } 1202 1203 ExprResult 1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1205 SourceLocation NameLoc) { 1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1207 CXXScopeSpec SS; 1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1210 } 1211 1212 ExprResult 1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1214 IdentifierInfo *Name, 1215 SourceLocation NameLoc, 1216 bool IsAddressOfOperand) { 1217 DeclarationNameInfo NameInfo(Name, NameLoc); 1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1219 NameInfo, IsAddressOfOperand, 1220 /*TemplateArgs=*/nullptr); 1221 } 1222 1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1224 NamedDecl *Found, 1225 SourceLocation NameLoc, 1226 const Token &NextToken) { 1227 if (getCurMethodDecl() && SS.isEmpty()) 1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1229 return BuildIvarRefExpr(S, NameLoc, Ivar); 1230 1231 // Reconstruct the lookup result. 1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1233 Result.addDecl(Found); 1234 Result.resolveKind(); 1235 1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1237 return BuildDeclarationNameExpr(SS, Result, ADL); 1238 } 1239 1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1241 // For an implicit class member access, transform the result into a member 1242 // access expression if necessary. 1243 auto *ULE = cast<UnresolvedLookupExpr>(E); 1244 if ((*ULE->decls_begin())->isCXXClassMember()) { 1245 CXXScopeSpec SS; 1246 SS.Adopt(ULE->getQualifierLoc()); 1247 1248 // Reconstruct the lookup result. 1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1250 LookupOrdinaryName); 1251 Result.setNamingClass(ULE->getNamingClass()); 1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1253 Result.addDecl(*I, I.getAccess()); 1254 Result.resolveKind(); 1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1256 nullptr, S); 1257 } 1258 1259 // Otherwise, this is already in the form we needed, and no further checks 1260 // are necessary. 1261 return ULE; 1262 } 1263 1264 Sema::TemplateNameKindForDiagnostics 1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1266 auto *TD = Name.getAsTemplateDecl(); 1267 if (!TD) 1268 return TemplateNameKindForDiagnostics::DependentTemplate; 1269 if (isa<ClassTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::ClassTemplate; 1271 if (isa<FunctionTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::FunctionTemplate; 1273 if (isa<VarTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::VarTemplate; 1275 if (isa<TypeAliasTemplateDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::AliasTemplate; 1277 if (isa<TemplateTemplateParmDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1279 if (isa<ConceptDecl>(TD)) 1280 return TemplateNameKindForDiagnostics::Concept; 1281 return TemplateNameKindForDiagnostics::DependentTemplate; 1282 } 1283 1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1285 assert(DC->getLexicalParent() == CurContext && 1286 "The next DeclContext should be lexically contained in the current one."); 1287 CurContext = DC; 1288 S->setEntity(DC); 1289 } 1290 1291 void Sema::PopDeclContext() { 1292 assert(CurContext && "DeclContext imbalance!"); 1293 1294 CurContext = CurContext->getLexicalParent(); 1295 assert(CurContext && "Popped translation unit!"); 1296 } 1297 1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1299 Decl *D) { 1300 // Unlike PushDeclContext, the context to which we return is not necessarily 1301 // the containing DC of TD, because the new context will be some pre-existing 1302 // TagDecl definition instead of a fresh one. 1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1304 CurContext = cast<TagDecl>(D)->getDefinition(); 1305 assert(CurContext && "skipping definition of undefined tag"); 1306 // Start lookups from the parent of the current context; we don't want to look 1307 // into the pre-existing complete definition. 1308 S->setEntity(CurContext->getLookupParent()); 1309 return Result; 1310 } 1311 1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1313 CurContext = static_cast<decltype(CurContext)>(Context); 1314 } 1315 1316 /// EnterDeclaratorContext - Used when we must lookup names in the context 1317 /// of a declarator's nested name specifier. 1318 /// 1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1320 // C++0x [basic.lookup.unqual]p13: 1321 // A name used in the definition of a static data member of class 1322 // X (after the qualified-id of the static member) is looked up as 1323 // if the name was used in a member function of X. 1324 // C++0x [basic.lookup.unqual]p14: 1325 // If a variable member of a namespace is defined outside of the 1326 // scope of its namespace then any name used in the definition of 1327 // the variable member (after the declarator-id) is looked up as 1328 // if the definition of the variable member occurred in its 1329 // namespace. 1330 // Both of these imply that we should push a scope whose context 1331 // is the semantic context of the declaration. We can't use 1332 // PushDeclContext here because that context is not necessarily 1333 // lexically contained in the current context. Fortunately, 1334 // the containing scope should have the appropriate information. 1335 1336 assert(!S->getEntity() && "scope already has entity"); 1337 1338 #ifndef NDEBUG 1339 Scope *Ancestor = S->getParent(); 1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1341 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1342 #endif 1343 1344 CurContext = DC; 1345 S->setEntity(DC); 1346 1347 if (S->getParent()->isTemplateParamScope()) { 1348 // Also set the corresponding entities for all immediately-enclosing 1349 // template parameter scopes. 1350 EnterTemplatedContext(S->getParent(), DC); 1351 } 1352 } 1353 1354 void Sema::ExitDeclaratorContext(Scope *S) { 1355 assert(S->getEntity() == CurContext && "Context imbalance!"); 1356 1357 // Switch back to the lexical context. The safety of this is 1358 // enforced by an assert in EnterDeclaratorContext. 1359 Scope *Ancestor = S->getParent(); 1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1361 CurContext = Ancestor->getEntity(); 1362 1363 // We don't need to do anything with the scope, which is going to 1364 // disappear. 1365 } 1366 1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1368 assert(S->isTemplateParamScope() && 1369 "expected to be initializing a template parameter scope"); 1370 1371 // C++20 [temp.local]p7: 1372 // In the definition of a member of a class template that appears outside 1373 // of the class template definition, the name of a member of the class 1374 // template hides the name of a template-parameter of any enclosing class 1375 // templates (but not a template-parameter of the member if the member is a 1376 // class or function template). 1377 // C++20 [temp.local]p9: 1378 // In the definition of a class template or in the definition of a member 1379 // of such a template that appears outside of the template definition, for 1380 // each non-dependent base class (13.8.2.1), if the name of the base class 1381 // or the name of a member of the base class is the same as the name of a 1382 // template-parameter, the base class name or member name hides the 1383 // template-parameter name (6.4.10). 1384 // 1385 // This means that a template parameter scope should be searched immediately 1386 // after searching the DeclContext for which it is a template parameter 1387 // scope. For example, for 1388 // template<typename T> template<typename U> template<typename V> 1389 // void N::A<T>::B<U>::f(...) 1390 // we search V then B<U> (and base classes) then U then A<T> (and base 1391 // classes) then T then N then ::. 1392 unsigned ScopeDepth = getTemplateDepth(S); 1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1394 DeclContext *SearchDCAfterScope = DC; 1395 for (; DC; DC = DC->getLookupParent()) { 1396 if (const TemplateParameterList *TPL = 1397 cast<Decl>(DC)->getDescribedTemplateParams()) { 1398 unsigned DCDepth = TPL->getDepth() + 1; 1399 if (DCDepth > ScopeDepth) 1400 continue; 1401 if (ScopeDepth == DCDepth) 1402 SearchDCAfterScope = DC = DC->getLookupParent(); 1403 break; 1404 } 1405 } 1406 S->setLookupEntity(SearchDCAfterScope); 1407 } 1408 } 1409 1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1411 // We assume that the caller has already called 1412 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1413 FunctionDecl *FD = D->getAsFunction(); 1414 if (!FD) 1415 return; 1416 1417 // Same implementation as PushDeclContext, but enters the context 1418 // from the lexical parent, rather than the top-level class. 1419 assert(CurContext == FD->getLexicalParent() && 1420 "The next DeclContext should be lexically contained in the current one."); 1421 CurContext = FD; 1422 S->setEntity(CurContext); 1423 1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1425 ParmVarDecl *Param = FD->getParamDecl(P); 1426 // If the parameter has an identifier, then add it to the scope 1427 if (Param->getIdentifier()) { 1428 S->AddDecl(Param); 1429 IdResolver.AddDecl(Param); 1430 } 1431 } 1432 } 1433 1434 void Sema::ActOnExitFunctionContext() { 1435 // Same implementation as PopDeclContext, but returns to the lexical parent, 1436 // rather than the top-level class. 1437 assert(CurContext && "DeclContext imbalance!"); 1438 CurContext = CurContext->getLexicalParent(); 1439 assert(CurContext && "Popped translation unit!"); 1440 } 1441 1442 /// Determine whether we allow overloading of the function 1443 /// PrevDecl with another declaration. 1444 /// 1445 /// This routine determines whether overloading is possible, not 1446 /// whether some new function is actually an overload. It will return 1447 /// true in C++ (where we can always provide overloads) or, as an 1448 /// extension, in C when the previous function is already an 1449 /// overloaded function declaration or has the "overloadable" 1450 /// attribute. 1451 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1452 ASTContext &Context, 1453 const FunctionDecl *New) { 1454 if (Context.getLangOpts().CPlusPlus) 1455 return true; 1456 1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1458 return true; 1459 1460 return Previous.getResultKind() == LookupResult::Found && 1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1462 New->hasAttr<OverloadableAttr>()); 1463 } 1464 1465 /// Add this decl to the scope shadowed decl chains. 1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1467 // Move up the scope chain until we find the nearest enclosing 1468 // non-transparent context. The declaration will be introduced into this 1469 // scope. 1470 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1471 S = S->getParent(); 1472 1473 // Add scoped declarations into their context, so that they can be 1474 // found later. Declarations without a context won't be inserted 1475 // into any context. 1476 if (AddToContext) 1477 CurContext->addDecl(D); 1478 1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1480 // are function-local declarations. 1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1482 return; 1483 1484 // Template instantiations should also not be pushed into scope. 1485 if (isa<FunctionDecl>(D) && 1486 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1487 return; 1488 1489 // If this replaces anything in the current scope, 1490 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1491 IEnd = IdResolver.end(); 1492 for (; I != IEnd; ++I) { 1493 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1494 S->RemoveDecl(*I); 1495 IdResolver.RemoveDecl(*I); 1496 1497 // Should only need to replace one decl. 1498 break; 1499 } 1500 } 1501 1502 S->AddDecl(D); 1503 1504 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1505 // Implicitly-generated labels may end up getting generated in an order that 1506 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1507 // the label at the appropriate place in the identifier chain. 1508 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1509 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1510 if (IDC == CurContext) { 1511 if (!S->isDeclScope(*I)) 1512 continue; 1513 } else if (IDC->Encloses(CurContext)) 1514 break; 1515 } 1516 1517 IdResolver.InsertDeclAfter(I, D); 1518 } else { 1519 IdResolver.AddDecl(D); 1520 } 1521 } 1522 1523 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1524 bool AllowInlineNamespace) { 1525 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1526 } 1527 1528 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1529 DeclContext *TargetDC = DC->getPrimaryContext(); 1530 do { 1531 if (DeclContext *ScopeDC = S->getEntity()) 1532 if (ScopeDC->getPrimaryContext() == TargetDC) 1533 return S; 1534 } while ((S = S->getParent())); 1535 1536 return nullptr; 1537 } 1538 1539 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1540 DeclContext*, 1541 ASTContext&); 1542 1543 /// Filters out lookup results that don't fall within the given scope 1544 /// as determined by isDeclInScope. 1545 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1546 bool ConsiderLinkage, 1547 bool AllowInlineNamespace) { 1548 LookupResult::Filter F = R.makeFilter(); 1549 while (F.hasNext()) { 1550 NamedDecl *D = F.next(); 1551 1552 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1553 continue; 1554 1555 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1556 continue; 1557 1558 F.erase(); 1559 } 1560 1561 F.done(); 1562 } 1563 1564 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1565 /// have compatible owning modules. 1566 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1567 // FIXME: The Modules TS is not clear about how friend declarations are 1568 // to be treated. It's not meaningful to have different owning modules for 1569 // linkage in redeclarations of the same entity, so for now allow the 1570 // redeclaration and change the owning modules to match. 1571 if (New->getFriendObjectKind() && 1572 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1573 New->setLocalOwningModule(Old->getOwningModule()); 1574 makeMergedDefinitionVisible(New); 1575 return false; 1576 } 1577 1578 Module *NewM = New->getOwningModule(); 1579 Module *OldM = Old->getOwningModule(); 1580 1581 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1582 NewM = NewM->Parent; 1583 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1584 OldM = OldM->Parent; 1585 1586 if (NewM == OldM) 1587 return false; 1588 1589 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1590 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1591 if (NewIsModuleInterface || OldIsModuleInterface) { 1592 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1593 // if a declaration of D [...] appears in the purview of a module, all 1594 // other such declarations shall appear in the purview of the same module 1595 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1596 << New 1597 << NewIsModuleInterface 1598 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1599 << OldIsModuleInterface 1600 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1601 Diag(Old->getLocation(), diag::note_previous_declaration); 1602 New->setInvalidDecl(); 1603 return true; 1604 } 1605 1606 return false; 1607 } 1608 1609 static bool isUsingDecl(NamedDecl *D) { 1610 return isa<UsingShadowDecl>(D) || 1611 isa<UnresolvedUsingTypenameDecl>(D) || 1612 isa<UnresolvedUsingValueDecl>(D); 1613 } 1614 1615 /// Removes using shadow declarations from the lookup results. 1616 static void RemoveUsingDecls(LookupResult &R) { 1617 LookupResult::Filter F = R.makeFilter(); 1618 while (F.hasNext()) 1619 if (isUsingDecl(F.next())) 1620 F.erase(); 1621 1622 F.done(); 1623 } 1624 1625 /// Check for this common pattern: 1626 /// @code 1627 /// class S { 1628 /// S(const S&); // DO NOT IMPLEMENT 1629 /// void operator=(const S&); // DO NOT IMPLEMENT 1630 /// }; 1631 /// @endcode 1632 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1633 // FIXME: Should check for private access too but access is set after we get 1634 // the decl here. 1635 if (D->doesThisDeclarationHaveABody()) 1636 return false; 1637 1638 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1639 return CD->isCopyConstructor(); 1640 return D->isCopyAssignmentOperator(); 1641 } 1642 1643 // We need this to handle 1644 // 1645 // typedef struct { 1646 // void *foo() { return 0; } 1647 // } A; 1648 // 1649 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1650 // for example. If 'A', foo will have external linkage. If we have '*A', 1651 // foo will have no linkage. Since we can't know until we get to the end 1652 // of the typedef, this function finds out if D might have non-external linkage. 1653 // Callers should verify at the end of the TU if it D has external linkage or 1654 // not. 1655 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1656 const DeclContext *DC = D->getDeclContext(); 1657 while (!DC->isTranslationUnit()) { 1658 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1659 if (!RD->hasNameForLinkage()) 1660 return true; 1661 } 1662 DC = DC->getParent(); 1663 } 1664 1665 return !D->isExternallyVisible(); 1666 } 1667 1668 // FIXME: This needs to be refactored; some other isInMainFile users want 1669 // these semantics. 1670 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1671 if (S.TUKind != TU_Complete) 1672 return false; 1673 return S.SourceMgr.isInMainFile(Loc); 1674 } 1675 1676 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1677 assert(D); 1678 1679 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1680 return false; 1681 1682 // Ignore all entities declared within templates, and out-of-line definitions 1683 // of members of class templates. 1684 if (D->getDeclContext()->isDependentContext() || 1685 D->getLexicalDeclContext()->isDependentContext()) 1686 return false; 1687 1688 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1689 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1690 return false; 1691 // A non-out-of-line declaration of a member specialization was implicitly 1692 // instantiated; it's the out-of-line declaration that we're interested in. 1693 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1694 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1695 return false; 1696 1697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1698 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1699 return false; 1700 } else { 1701 // 'static inline' functions are defined in headers; don't warn. 1702 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1703 return false; 1704 } 1705 1706 if (FD->doesThisDeclarationHaveABody() && 1707 Context.DeclMustBeEmitted(FD)) 1708 return false; 1709 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1710 // Constants and utility variables are defined in headers with internal 1711 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1712 // like "inline".) 1713 if (!isMainFileLoc(*this, VD->getLocation())) 1714 return false; 1715 1716 if (Context.DeclMustBeEmitted(VD)) 1717 return false; 1718 1719 if (VD->isStaticDataMember() && 1720 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1721 return false; 1722 if (VD->isStaticDataMember() && 1723 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1724 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1725 return false; 1726 1727 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1728 return false; 1729 } else { 1730 return false; 1731 } 1732 1733 // Only warn for unused decls internal to the translation unit. 1734 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1735 // for inline functions defined in the main source file, for instance. 1736 return mightHaveNonExternalLinkage(D); 1737 } 1738 1739 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1740 if (!D) 1741 return; 1742 1743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1744 const FunctionDecl *First = FD->getFirstDecl(); 1745 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1746 return; // First should already be in the vector. 1747 } 1748 1749 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1750 const VarDecl *First = VD->getFirstDecl(); 1751 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1752 return; // First should already be in the vector. 1753 } 1754 1755 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1756 UnusedFileScopedDecls.push_back(D); 1757 } 1758 1759 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1760 if (D->isInvalidDecl()) 1761 return false; 1762 1763 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1764 // For a decomposition declaration, warn if none of the bindings are 1765 // referenced, instead of if the variable itself is referenced (which 1766 // it is, by the bindings' expressions). 1767 for (auto *BD : DD->bindings()) 1768 if (BD->isReferenced()) 1769 return false; 1770 } else if (!D->getDeclName()) { 1771 return false; 1772 } else if (D->isReferenced() || D->isUsed()) { 1773 return false; 1774 } 1775 1776 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1777 return false; 1778 1779 if (isa<LabelDecl>(D)) 1780 return true; 1781 1782 // Except for labels, we only care about unused decls that are local to 1783 // functions. 1784 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1785 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1786 // For dependent types, the diagnostic is deferred. 1787 WithinFunction = 1788 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1789 if (!WithinFunction) 1790 return false; 1791 1792 if (isa<TypedefNameDecl>(D)) 1793 return true; 1794 1795 // White-list anything that isn't a local variable. 1796 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1797 return false; 1798 1799 // Types of valid local variables should be complete, so this should succeed. 1800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1801 1802 // White-list anything with an __attribute__((unused)) type. 1803 const auto *Ty = VD->getType().getTypePtr(); 1804 1805 // Only look at the outermost level of typedef. 1806 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1807 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1808 return false; 1809 } 1810 1811 // If we failed to complete the type for some reason, or if the type is 1812 // dependent, don't diagnose the variable. 1813 if (Ty->isIncompleteType() || Ty->isDependentType()) 1814 return false; 1815 1816 // Look at the element type to ensure that the warning behaviour is 1817 // consistent for both scalars and arrays. 1818 Ty = Ty->getBaseElementTypeUnsafe(); 1819 1820 if (const TagType *TT = Ty->getAs<TagType>()) { 1821 const TagDecl *Tag = TT->getDecl(); 1822 if (Tag->hasAttr<UnusedAttr>()) 1823 return false; 1824 1825 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1826 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1827 return false; 1828 1829 if (const Expr *Init = VD->getInit()) { 1830 if (const ExprWithCleanups *Cleanups = 1831 dyn_cast<ExprWithCleanups>(Init)) 1832 Init = Cleanups->getSubExpr(); 1833 const CXXConstructExpr *Construct = 1834 dyn_cast<CXXConstructExpr>(Init); 1835 if (Construct && !Construct->isElidable()) { 1836 CXXConstructorDecl *CD = Construct->getConstructor(); 1837 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1838 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1839 return false; 1840 } 1841 1842 // Suppress the warning if we don't know how this is constructed, and 1843 // it could possibly be non-trivial constructor. 1844 if (Init->isTypeDependent()) 1845 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1846 if (!Ctor->isTrivial()) 1847 return false; 1848 } 1849 } 1850 } 1851 1852 // TODO: __attribute__((unused)) templates? 1853 } 1854 1855 return true; 1856 } 1857 1858 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1859 FixItHint &Hint) { 1860 if (isa<LabelDecl>(D)) { 1861 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1862 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1863 true); 1864 if (AfterColon.isInvalid()) 1865 return; 1866 Hint = FixItHint::CreateRemoval( 1867 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1868 } 1869 } 1870 1871 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1872 if (D->getTypeForDecl()->isDependentType()) 1873 return; 1874 1875 for (auto *TmpD : D->decls()) { 1876 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1877 DiagnoseUnusedDecl(T); 1878 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1879 DiagnoseUnusedNestedTypedefs(R); 1880 } 1881 } 1882 1883 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1884 /// unless they are marked attr(unused). 1885 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1886 if (!ShouldDiagnoseUnusedDecl(D)) 1887 return; 1888 1889 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1890 // typedefs can be referenced later on, so the diagnostics are emitted 1891 // at end-of-translation-unit. 1892 UnusedLocalTypedefNameCandidates.insert(TD); 1893 return; 1894 } 1895 1896 FixItHint Hint; 1897 GenerateFixForUnusedDecl(D, Context, Hint); 1898 1899 unsigned DiagID; 1900 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1901 DiagID = diag::warn_unused_exception_param; 1902 else if (isa<LabelDecl>(D)) 1903 DiagID = diag::warn_unused_label; 1904 else 1905 DiagID = diag::warn_unused_variable; 1906 1907 Diag(D->getLocation(), DiagID) << D << Hint; 1908 } 1909 1910 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1911 // Verify that we have no forward references left. If so, there was a goto 1912 // or address of a label taken, but no definition of it. Label fwd 1913 // definitions are indicated with a null substmt which is also not a resolved 1914 // MS inline assembly label name. 1915 bool Diagnose = false; 1916 if (L->isMSAsmLabel()) 1917 Diagnose = !L->isResolvedMSAsmLabel(); 1918 else 1919 Diagnose = L->getStmt() == nullptr; 1920 if (Diagnose) 1921 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1922 } 1923 1924 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1925 S->mergeNRVOIntoParent(); 1926 1927 if (S->decl_empty()) return; 1928 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1929 "Scope shouldn't contain decls!"); 1930 1931 for (auto *TmpD : S->decls()) { 1932 assert(TmpD && "This decl didn't get pushed??"); 1933 1934 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1935 NamedDecl *D = cast<NamedDecl>(TmpD); 1936 1937 // Diagnose unused variables in this scope. 1938 if (!S->hasUnrecoverableErrorOccurred()) { 1939 DiagnoseUnusedDecl(D); 1940 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1941 DiagnoseUnusedNestedTypedefs(RD); 1942 } 1943 1944 if (!D->getDeclName()) continue; 1945 1946 // If this was a forward reference to a label, verify it was defined. 1947 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1948 CheckPoppedLabel(LD, *this); 1949 1950 // Remove this name from our lexical scope, and warn on it if we haven't 1951 // already. 1952 IdResolver.RemoveDecl(D); 1953 auto ShadowI = ShadowingDecls.find(D); 1954 if (ShadowI != ShadowingDecls.end()) { 1955 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1956 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1957 << D << FD << FD->getParent(); 1958 Diag(FD->getLocation(), diag::note_previous_declaration); 1959 } 1960 ShadowingDecls.erase(ShadowI); 1961 } 1962 } 1963 } 1964 1965 /// Look for an Objective-C class in the translation unit. 1966 /// 1967 /// \param Id The name of the Objective-C class we're looking for. If 1968 /// typo-correction fixes this name, the Id will be updated 1969 /// to the fixed name. 1970 /// 1971 /// \param IdLoc The location of the name in the translation unit. 1972 /// 1973 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1974 /// if there is no class with the given name. 1975 /// 1976 /// \returns The declaration of the named Objective-C class, or NULL if the 1977 /// class could not be found. 1978 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1979 SourceLocation IdLoc, 1980 bool DoTypoCorrection) { 1981 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1982 // creation from this context. 1983 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1984 1985 if (!IDecl && DoTypoCorrection) { 1986 // Perform typo correction at the given location, but only if we 1987 // find an Objective-C class name. 1988 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1989 if (TypoCorrection C = 1990 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1991 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1992 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1993 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1994 Id = IDecl->getIdentifier(); 1995 } 1996 } 1997 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1998 // This routine must always return a class definition, if any. 1999 if (Def && Def->getDefinition()) 2000 Def = Def->getDefinition(); 2001 return Def; 2002 } 2003 2004 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2005 /// from S, where a non-field would be declared. This routine copes 2006 /// with the difference between C and C++ scoping rules in structs and 2007 /// unions. For example, the following code is well-formed in C but 2008 /// ill-formed in C++: 2009 /// @code 2010 /// struct S6 { 2011 /// enum { BAR } e; 2012 /// }; 2013 /// 2014 /// void test_S6() { 2015 /// struct S6 a; 2016 /// a.e = BAR; 2017 /// } 2018 /// @endcode 2019 /// For the declaration of BAR, this routine will return a different 2020 /// scope. The scope S will be the scope of the unnamed enumeration 2021 /// within S6. In C++, this routine will return the scope associated 2022 /// with S6, because the enumeration's scope is a transparent 2023 /// context but structures can contain non-field names. In C, this 2024 /// routine will return the translation unit scope, since the 2025 /// enumeration's scope is a transparent context and structures cannot 2026 /// contain non-field names. 2027 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2028 while (((S->getFlags() & Scope::DeclScope) == 0) || 2029 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2030 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2031 S = S->getParent(); 2032 return S; 2033 } 2034 2035 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2036 ASTContext::GetBuiltinTypeError Error) { 2037 switch (Error) { 2038 case ASTContext::GE_None: 2039 return ""; 2040 case ASTContext::GE_Missing_type: 2041 return BuiltinInfo.getHeaderName(ID); 2042 case ASTContext::GE_Missing_stdio: 2043 return "stdio.h"; 2044 case ASTContext::GE_Missing_setjmp: 2045 return "setjmp.h"; 2046 case ASTContext::GE_Missing_ucontext: 2047 return "ucontext.h"; 2048 } 2049 llvm_unreachable("unhandled error kind"); 2050 } 2051 2052 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2053 unsigned ID, SourceLocation Loc) { 2054 DeclContext *Parent = Context.getTranslationUnitDecl(); 2055 2056 if (getLangOpts().CPlusPlus) { 2057 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2058 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2059 CLinkageDecl->setImplicit(); 2060 Parent->addDecl(CLinkageDecl); 2061 Parent = CLinkageDecl; 2062 } 2063 2064 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2065 /*TInfo=*/nullptr, SC_Extern, false, 2066 Type->isFunctionProtoType()); 2067 New->setImplicit(); 2068 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2069 2070 // Create Decl objects for each parameter, adding them to the 2071 // FunctionDecl. 2072 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2073 SmallVector<ParmVarDecl *, 16> Params; 2074 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2075 ParmVarDecl *parm = ParmVarDecl::Create( 2076 Context, New, SourceLocation(), SourceLocation(), nullptr, 2077 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2078 parm->setScopeInfo(0, i); 2079 Params.push_back(parm); 2080 } 2081 New->setParams(Params); 2082 } 2083 2084 AddKnownFunctionAttributes(New); 2085 return New; 2086 } 2087 2088 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2089 /// file scope. lazily create a decl for it. ForRedeclaration is true 2090 /// if we're creating this built-in in anticipation of redeclaring the 2091 /// built-in. 2092 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2093 Scope *S, bool ForRedeclaration, 2094 SourceLocation Loc) { 2095 LookupNecessaryTypesForBuiltin(S, ID); 2096 2097 ASTContext::GetBuiltinTypeError Error; 2098 QualType R = Context.GetBuiltinType(ID, Error); 2099 if (Error) { 2100 if (!ForRedeclaration) 2101 return nullptr; 2102 2103 // If we have a builtin without an associated type we should not emit a 2104 // warning when we were not able to find a type for it. 2105 if (Error == ASTContext::GE_Missing_type || 2106 Context.BuiltinInfo.allowTypeMismatch(ID)) 2107 return nullptr; 2108 2109 // If we could not find a type for setjmp it is because the jmp_buf type was 2110 // not defined prior to the setjmp declaration. 2111 if (Error == ASTContext::GE_Missing_setjmp) { 2112 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2113 << Context.BuiltinInfo.getName(ID); 2114 return nullptr; 2115 } 2116 2117 // Generally, we emit a warning that the declaration requires the 2118 // appropriate header. 2119 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2120 << getHeaderName(Context.BuiltinInfo, ID, Error) 2121 << Context.BuiltinInfo.getName(ID); 2122 return nullptr; 2123 } 2124 2125 if (!ForRedeclaration && 2126 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2127 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2128 Diag(Loc, diag::ext_implicit_lib_function_decl) 2129 << Context.BuiltinInfo.getName(ID) << R; 2130 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2131 Diag(Loc, diag::note_include_header_or_declare) 2132 << Header << Context.BuiltinInfo.getName(ID); 2133 } 2134 2135 if (R.isNull()) 2136 return nullptr; 2137 2138 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2139 RegisterLocallyScopedExternCDecl(New, S); 2140 2141 // TUScope is the translation-unit scope to insert this function into. 2142 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2143 // relate Scopes to DeclContexts, and probably eliminate CurContext 2144 // entirely, but we're not there yet. 2145 DeclContext *SavedContext = CurContext; 2146 CurContext = New->getDeclContext(); 2147 PushOnScopeChains(New, TUScope); 2148 CurContext = SavedContext; 2149 return New; 2150 } 2151 2152 /// Typedef declarations don't have linkage, but they still denote the same 2153 /// entity if their types are the same. 2154 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2155 /// isSameEntity. 2156 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2157 TypedefNameDecl *Decl, 2158 LookupResult &Previous) { 2159 // This is only interesting when modules are enabled. 2160 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2161 return; 2162 2163 // Empty sets are uninteresting. 2164 if (Previous.empty()) 2165 return; 2166 2167 LookupResult::Filter Filter = Previous.makeFilter(); 2168 while (Filter.hasNext()) { 2169 NamedDecl *Old = Filter.next(); 2170 2171 // Non-hidden declarations are never ignored. 2172 if (S.isVisible(Old)) 2173 continue; 2174 2175 // Declarations of the same entity are not ignored, even if they have 2176 // different linkages. 2177 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2178 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2179 Decl->getUnderlyingType())) 2180 continue; 2181 2182 // If both declarations give a tag declaration a typedef name for linkage 2183 // purposes, then they declare the same entity. 2184 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2185 Decl->getAnonDeclWithTypedefName()) 2186 continue; 2187 } 2188 2189 Filter.erase(); 2190 } 2191 2192 Filter.done(); 2193 } 2194 2195 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2196 QualType OldType; 2197 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2198 OldType = OldTypedef->getUnderlyingType(); 2199 else 2200 OldType = Context.getTypeDeclType(Old); 2201 QualType NewType = New->getUnderlyingType(); 2202 2203 if (NewType->isVariablyModifiedType()) { 2204 // Must not redefine a typedef with a variably-modified type. 2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2206 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2207 << Kind << NewType; 2208 if (Old->getLocation().isValid()) 2209 notePreviousDefinition(Old, New->getLocation()); 2210 New->setInvalidDecl(); 2211 return true; 2212 } 2213 2214 if (OldType != NewType && 2215 !OldType->isDependentType() && 2216 !NewType->isDependentType() && 2217 !Context.hasSameType(OldType, NewType)) { 2218 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2219 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2220 << Kind << NewType << OldType; 2221 if (Old->getLocation().isValid()) 2222 notePreviousDefinition(Old, New->getLocation()); 2223 New->setInvalidDecl(); 2224 return true; 2225 } 2226 return false; 2227 } 2228 2229 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2230 /// same name and scope as a previous declaration 'Old'. Figure out 2231 /// how to resolve this situation, merging decls or emitting 2232 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2233 /// 2234 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2235 LookupResult &OldDecls) { 2236 // If the new decl is known invalid already, don't bother doing any 2237 // merging checks. 2238 if (New->isInvalidDecl()) return; 2239 2240 // Allow multiple definitions for ObjC built-in typedefs. 2241 // FIXME: Verify the underlying types are equivalent! 2242 if (getLangOpts().ObjC) { 2243 const IdentifierInfo *TypeID = New->getIdentifier(); 2244 switch (TypeID->getLength()) { 2245 default: break; 2246 case 2: 2247 { 2248 if (!TypeID->isStr("id")) 2249 break; 2250 QualType T = New->getUnderlyingType(); 2251 if (!T->isPointerType()) 2252 break; 2253 if (!T->isVoidPointerType()) { 2254 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2255 if (!PT->isStructureType()) 2256 break; 2257 } 2258 Context.setObjCIdRedefinitionType(T); 2259 // Install the built-in type for 'id', ignoring the current definition. 2260 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2261 return; 2262 } 2263 case 5: 2264 if (!TypeID->isStr("Class")) 2265 break; 2266 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2267 // Install the built-in type for 'Class', ignoring the current definition. 2268 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2269 return; 2270 case 3: 2271 if (!TypeID->isStr("SEL")) 2272 break; 2273 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2274 // Install the built-in type for 'SEL', ignoring the current definition. 2275 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2276 return; 2277 } 2278 // Fall through - the typedef name was not a builtin type. 2279 } 2280 2281 // Verify the old decl was also a type. 2282 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2283 if (!Old) { 2284 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2285 << New->getDeclName(); 2286 2287 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2288 if (OldD->getLocation().isValid()) 2289 notePreviousDefinition(OldD, New->getLocation()); 2290 2291 return New->setInvalidDecl(); 2292 } 2293 2294 // If the old declaration is invalid, just give up here. 2295 if (Old->isInvalidDecl()) 2296 return New->setInvalidDecl(); 2297 2298 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2299 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2300 auto *NewTag = New->getAnonDeclWithTypedefName(); 2301 NamedDecl *Hidden = nullptr; 2302 if (OldTag && NewTag && 2303 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2304 !hasVisibleDefinition(OldTag, &Hidden)) { 2305 // There is a definition of this tag, but it is not visible. Use it 2306 // instead of our tag. 2307 New->setTypeForDecl(OldTD->getTypeForDecl()); 2308 if (OldTD->isModed()) 2309 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2310 OldTD->getUnderlyingType()); 2311 else 2312 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2313 2314 // Make the old tag definition visible. 2315 makeMergedDefinitionVisible(Hidden); 2316 2317 // If this was an unscoped enumeration, yank all of its enumerators 2318 // out of the scope. 2319 if (isa<EnumDecl>(NewTag)) { 2320 Scope *EnumScope = getNonFieldDeclScope(S); 2321 for (auto *D : NewTag->decls()) { 2322 auto *ED = cast<EnumConstantDecl>(D); 2323 assert(EnumScope->isDeclScope(ED)); 2324 EnumScope->RemoveDecl(ED); 2325 IdResolver.RemoveDecl(ED); 2326 ED->getLexicalDeclContext()->removeDecl(ED); 2327 } 2328 } 2329 } 2330 } 2331 2332 // If the typedef types are not identical, reject them in all languages and 2333 // with any extensions enabled. 2334 if (isIncompatibleTypedef(Old, New)) 2335 return; 2336 2337 // The types match. Link up the redeclaration chain and merge attributes if 2338 // the old declaration was a typedef. 2339 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2340 New->setPreviousDecl(Typedef); 2341 mergeDeclAttributes(New, Old); 2342 } 2343 2344 if (getLangOpts().MicrosoftExt) 2345 return; 2346 2347 if (getLangOpts().CPlusPlus) { 2348 // C++ [dcl.typedef]p2: 2349 // In a given non-class scope, a typedef specifier can be used to 2350 // redefine the name of any type declared in that scope to refer 2351 // to the type to which it already refers. 2352 if (!isa<CXXRecordDecl>(CurContext)) 2353 return; 2354 2355 // C++0x [dcl.typedef]p4: 2356 // In a given class scope, a typedef specifier can be used to redefine 2357 // any class-name declared in that scope that is not also a typedef-name 2358 // to refer to the type to which it already refers. 2359 // 2360 // This wording came in via DR424, which was a correction to the 2361 // wording in DR56, which accidentally banned code like: 2362 // 2363 // struct S { 2364 // typedef struct A { } A; 2365 // }; 2366 // 2367 // in the C++03 standard. We implement the C++0x semantics, which 2368 // allow the above but disallow 2369 // 2370 // struct S { 2371 // typedef int I; 2372 // typedef int I; 2373 // }; 2374 // 2375 // since that was the intent of DR56. 2376 if (!isa<TypedefNameDecl>(Old)) 2377 return; 2378 2379 Diag(New->getLocation(), diag::err_redefinition) 2380 << New->getDeclName(); 2381 notePreviousDefinition(Old, New->getLocation()); 2382 return New->setInvalidDecl(); 2383 } 2384 2385 // Modules always permit redefinition of typedefs, as does C11. 2386 if (getLangOpts().Modules || getLangOpts().C11) 2387 return; 2388 2389 // If we have a redefinition of a typedef in C, emit a warning. This warning 2390 // is normally mapped to an error, but can be controlled with 2391 // -Wtypedef-redefinition. If either the original or the redefinition is 2392 // in a system header, don't emit this for compatibility with GCC. 2393 if (getDiagnostics().getSuppressSystemWarnings() && 2394 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2395 (Old->isImplicit() || 2396 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2397 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2398 return; 2399 2400 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2401 << New->getDeclName(); 2402 notePreviousDefinition(Old, New->getLocation()); 2403 } 2404 2405 /// DeclhasAttr - returns true if decl Declaration already has the target 2406 /// attribute. 2407 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2408 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2409 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2410 for (const auto *i : D->attrs()) 2411 if (i->getKind() == A->getKind()) { 2412 if (Ann) { 2413 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2414 return true; 2415 continue; 2416 } 2417 // FIXME: Don't hardcode this check 2418 if (OA && isa<OwnershipAttr>(i)) 2419 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2420 return true; 2421 } 2422 2423 return false; 2424 } 2425 2426 static bool isAttributeTargetADefinition(Decl *D) { 2427 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2428 return VD->isThisDeclarationADefinition(); 2429 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2430 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2431 return true; 2432 } 2433 2434 /// Merge alignment attributes from \p Old to \p New, taking into account the 2435 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2436 /// 2437 /// \return \c true if any attributes were added to \p New. 2438 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2439 // Look for alignas attributes on Old, and pick out whichever attribute 2440 // specifies the strictest alignment requirement. 2441 AlignedAttr *OldAlignasAttr = nullptr; 2442 AlignedAttr *OldStrictestAlignAttr = nullptr; 2443 unsigned OldAlign = 0; 2444 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2445 // FIXME: We have no way of representing inherited dependent alignments 2446 // in a case like: 2447 // template<int A, int B> struct alignas(A) X; 2448 // template<int A, int B> struct alignas(B) X {}; 2449 // For now, we just ignore any alignas attributes which are not on the 2450 // definition in such a case. 2451 if (I->isAlignmentDependent()) 2452 return false; 2453 2454 if (I->isAlignas()) 2455 OldAlignasAttr = I; 2456 2457 unsigned Align = I->getAlignment(S.Context); 2458 if (Align > OldAlign) { 2459 OldAlign = Align; 2460 OldStrictestAlignAttr = I; 2461 } 2462 } 2463 2464 // Look for alignas attributes on New. 2465 AlignedAttr *NewAlignasAttr = nullptr; 2466 unsigned NewAlign = 0; 2467 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2468 if (I->isAlignmentDependent()) 2469 return false; 2470 2471 if (I->isAlignas()) 2472 NewAlignasAttr = I; 2473 2474 unsigned Align = I->getAlignment(S.Context); 2475 if (Align > NewAlign) 2476 NewAlign = Align; 2477 } 2478 2479 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2480 // Both declarations have 'alignas' attributes. We require them to match. 2481 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2482 // fall short. (If two declarations both have alignas, they must both match 2483 // every definition, and so must match each other if there is a definition.) 2484 2485 // If either declaration only contains 'alignas(0)' specifiers, then it 2486 // specifies the natural alignment for the type. 2487 if (OldAlign == 0 || NewAlign == 0) { 2488 QualType Ty; 2489 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2490 Ty = VD->getType(); 2491 else 2492 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2493 2494 if (OldAlign == 0) 2495 OldAlign = S.Context.getTypeAlign(Ty); 2496 if (NewAlign == 0) 2497 NewAlign = S.Context.getTypeAlign(Ty); 2498 } 2499 2500 if (OldAlign != NewAlign) { 2501 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2502 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2503 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2504 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2505 } 2506 } 2507 2508 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2509 // C++11 [dcl.align]p6: 2510 // if any declaration of an entity has an alignment-specifier, 2511 // every defining declaration of that entity shall specify an 2512 // equivalent alignment. 2513 // C11 6.7.5/7: 2514 // If the definition of an object does not have an alignment 2515 // specifier, any other declaration of that object shall also 2516 // have no alignment specifier. 2517 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2518 << OldAlignasAttr; 2519 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2520 << OldAlignasAttr; 2521 } 2522 2523 bool AnyAdded = false; 2524 2525 // Ensure we have an attribute representing the strictest alignment. 2526 if (OldAlign > NewAlign) { 2527 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2528 Clone->setInherited(true); 2529 New->addAttr(Clone); 2530 AnyAdded = true; 2531 } 2532 2533 // Ensure we have an alignas attribute if the old declaration had one. 2534 if (OldAlignasAttr && !NewAlignasAttr && 2535 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2536 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2537 Clone->setInherited(true); 2538 New->addAttr(Clone); 2539 AnyAdded = true; 2540 } 2541 2542 return AnyAdded; 2543 } 2544 2545 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2546 const InheritableAttr *Attr, 2547 Sema::AvailabilityMergeKind AMK) { 2548 // This function copies an attribute Attr from a previous declaration to the 2549 // new declaration D if the new declaration doesn't itself have that attribute 2550 // yet or if that attribute allows duplicates. 2551 // If you're adding a new attribute that requires logic different from 2552 // "use explicit attribute on decl if present, else use attribute from 2553 // previous decl", for example if the attribute needs to be consistent 2554 // between redeclarations, you need to call a custom merge function here. 2555 InheritableAttr *NewAttr = nullptr; 2556 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2557 NewAttr = S.mergeAvailabilityAttr( 2558 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2559 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2560 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2561 AA->getPriority()); 2562 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2563 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2565 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2566 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2567 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2568 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2569 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2570 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2571 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2572 FA->getFirstArg()); 2573 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2574 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2575 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2576 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2577 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2578 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2579 IA->getInheritanceModel()); 2580 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2581 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2582 &S.Context.Idents.get(AA->getSpelling())); 2583 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2584 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2585 isa<CUDAGlobalAttr>(Attr))) { 2586 // CUDA target attributes are part of function signature for 2587 // overloading purposes and must not be merged. 2588 return false; 2589 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2590 NewAttr = S.mergeMinSizeAttr(D, *MA); 2591 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2592 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2593 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2594 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2595 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2596 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2597 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2598 NewAttr = S.mergeCommonAttr(D, *CommonA); 2599 else if (isa<AlignedAttr>(Attr)) 2600 // AlignedAttrs are handled separately, because we need to handle all 2601 // such attributes on a declaration at the same time. 2602 NewAttr = nullptr; 2603 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2604 (AMK == Sema::AMK_Override || 2605 AMK == Sema::AMK_ProtocolImplementation)) 2606 NewAttr = nullptr; 2607 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2608 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2609 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2612 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2613 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2614 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2615 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2616 NewAttr = S.mergeImportNameAttr(D, *INA); 2617 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2618 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2619 2620 if (NewAttr) { 2621 NewAttr->setInherited(true); 2622 D->addAttr(NewAttr); 2623 if (isa<MSInheritanceAttr>(NewAttr)) 2624 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2625 return true; 2626 } 2627 2628 return false; 2629 } 2630 2631 static const NamedDecl *getDefinition(const Decl *D) { 2632 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2633 return TD->getDefinition(); 2634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2635 const VarDecl *Def = VD->getDefinition(); 2636 if (Def) 2637 return Def; 2638 return VD->getActingDefinition(); 2639 } 2640 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2641 const FunctionDecl *Def = nullptr; 2642 if (FD->isDefined(Def, true)) 2643 return Def; 2644 } 2645 return nullptr; 2646 } 2647 2648 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2649 for (const auto *Attribute : D->attrs()) 2650 if (Attribute->getKind() == Kind) 2651 return true; 2652 return false; 2653 } 2654 2655 /// checkNewAttributesAfterDef - If we already have a definition, check that 2656 /// there are no new attributes in this declaration. 2657 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2658 if (!New->hasAttrs()) 2659 return; 2660 2661 const NamedDecl *Def = getDefinition(Old); 2662 if (!Def || Def == New) 2663 return; 2664 2665 AttrVec &NewAttributes = New->getAttrs(); 2666 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2667 const Attr *NewAttribute = NewAttributes[I]; 2668 2669 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2671 Sema::SkipBodyInfo SkipBody; 2672 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2673 2674 // If we're skipping this definition, drop the "alias" attribute. 2675 if (SkipBody.ShouldSkip) { 2676 NewAttributes.erase(NewAttributes.begin() + I); 2677 --E; 2678 continue; 2679 } 2680 } else { 2681 VarDecl *VD = cast<VarDecl>(New); 2682 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2683 VarDecl::TentativeDefinition 2684 ? diag::err_alias_after_tentative 2685 : diag::err_redefinition; 2686 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2687 if (Diag == diag::err_redefinition) 2688 S.notePreviousDefinition(Def, VD->getLocation()); 2689 else 2690 S.Diag(Def->getLocation(), diag::note_previous_definition); 2691 VD->setInvalidDecl(); 2692 } 2693 ++I; 2694 continue; 2695 } 2696 2697 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2698 // Tentative definitions are only interesting for the alias check above. 2699 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2700 ++I; 2701 continue; 2702 } 2703 } 2704 2705 if (hasAttribute(Def, NewAttribute->getKind())) { 2706 ++I; 2707 continue; // regular attr merging will take care of validating this. 2708 } 2709 2710 if (isa<C11NoReturnAttr>(NewAttribute)) { 2711 // C's _Noreturn is allowed to be added to a function after it is defined. 2712 ++I; 2713 continue; 2714 } else if (isa<UuidAttr>(NewAttribute)) { 2715 // msvc will allow a subsequent definition to add an uuid to a class 2716 ++I; 2717 continue; 2718 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2719 if (AA->isAlignas()) { 2720 // C++11 [dcl.align]p6: 2721 // if any declaration of an entity has an alignment-specifier, 2722 // every defining declaration of that entity shall specify an 2723 // equivalent alignment. 2724 // C11 6.7.5/7: 2725 // If the definition of an object does not have an alignment 2726 // specifier, any other declaration of that object shall also 2727 // have no alignment specifier. 2728 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2729 << AA; 2730 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2731 << AA; 2732 NewAttributes.erase(NewAttributes.begin() + I); 2733 --E; 2734 continue; 2735 } 2736 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2737 // If there is a C definition followed by a redeclaration with this 2738 // attribute then there are two different definitions. In C++, prefer the 2739 // standard diagnostics. 2740 if (!S.getLangOpts().CPlusPlus) { 2741 S.Diag(NewAttribute->getLocation(), 2742 diag::err_loader_uninitialized_redeclaration); 2743 S.Diag(Def->getLocation(), diag::note_previous_definition); 2744 NewAttributes.erase(NewAttributes.begin() + I); 2745 --E; 2746 continue; 2747 } 2748 } else if (isa<SelectAnyAttr>(NewAttribute) && 2749 cast<VarDecl>(New)->isInline() && 2750 !cast<VarDecl>(New)->isInlineSpecified()) { 2751 // Don't warn about applying selectany to implicitly inline variables. 2752 // Older compilers and language modes would require the use of selectany 2753 // to make such variables inline, and it would have no effect if we 2754 // honored it. 2755 ++I; 2756 continue; 2757 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2758 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2759 // declarations after defintions. 2760 ++I; 2761 continue; 2762 } 2763 2764 S.Diag(NewAttribute->getLocation(), 2765 diag::warn_attribute_precede_definition); 2766 S.Diag(Def->getLocation(), diag::note_previous_definition); 2767 NewAttributes.erase(NewAttributes.begin() + I); 2768 --E; 2769 } 2770 } 2771 2772 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2773 const ConstInitAttr *CIAttr, 2774 bool AttrBeforeInit) { 2775 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2776 2777 // Figure out a good way to write this specifier on the old declaration. 2778 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2779 // enough of the attribute list spelling information to extract that without 2780 // heroics. 2781 std::string SuitableSpelling; 2782 if (S.getLangOpts().CPlusPlus20) 2783 SuitableSpelling = std::string( 2784 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2785 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2786 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2787 InsertLoc, {tok::l_square, tok::l_square, 2788 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2789 S.PP.getIdentifierInfo("require_constant_initialization"), 2790 tok::r_square, tok::r_square})); 2791 if (SuitableSpelling.empty()) 2792 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2793 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2794 S.PP.getIdentifierInfo("require_constant_initialization"), 2795 tok::r_paren, tok::r_paren})); 2796 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2797 SuitableSpelling = "constinit"; 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2799 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2800 if (SuitableSpelling.empty()) 2801 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2802 SuitableSpelling += " "; 2803 2804 if (AttrBeforeInit) { 2805 // extern constinit int a; 2806 // int a = 0; // error (missing 'constinit'), accepted as extension 2807 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2808 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2809 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2810 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2811 } else { 2812 // int a = 0; 2813 // constinit extern int a; // error (missing 'constinit') 2814 S.Diag(CIAttr->getLocation(), 2815 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2816 : diag::warn_require_const_init_added_too_late) 2817 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2818 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2819 << CIAttr->isConstinit() 2820 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2821 } 2822 } 2823 2824 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2825 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2826 AvailabilityMergeKind AMK) { 2827 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2828 UsedAttr *NewAttr = OldAttr->clone(Context); 2829 NewAttr->setInherited(true); 2830 New->addAttr(NewAttr); 2831 } 2832 2833 if (!Old->hasAttrs() && !New->hasAttrs()) 2834 return; 2835 2836 // [dcl.constinit]p1: 2837 // If the [constinit] specifier is applied to any declaration of a 2838 // variable, it shall be applied to the initializing declaration. 2839 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2840 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2841 if (bool(OldConstInit) != bool(NewConstInit)) { 2842 const auto *OldVD = cast<VarDecl>(Old); 2843 auto *NewVD = cast<VarDecl>(New); 2844 2845 // Find the initializing declaration. Note that we might not have linked 2846 // the new declaration into the redeclaration chain yet. 2847 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2848 if (!InitDecl && 2849 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2850 InitDecl = NewVD; 2851 2852 if (InitDecl == NewVD) { 2853 // This is the initializing declaration. If it would inherit 'constinit', 2854 // that's ill-formed. (Note that we do not apply this to the attribute 2855 // form). 2856 if (OldConstInit && OldConstInit->isConstinit()) 2857 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2858 /*AttrBeforeInit=*/true); 2859 } else if (NewConstInit) { 2860 // This is the first time we've been told that this declaration should 2861 // have a constant initializer. If we already saw the initializing 2862 // declaration, this is too late. 2863 if (InitDecl && InitDecl != NewVD) { 2864 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2865 /*AttrBeforeInit=*/false); 2866 NewVD->dropAttr<ConstInitAttr>(); 2867 } 2868 } 2869 } 2870 2871 // Attributes declared post-definition are currently ignored. 2872 checkNewAttributesAfterDef(*this, New, Old); 2873 2874 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2875 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2876 if (!OldA->isEquivalent(NewA)) { 2877 // This redeclaration changes __asm__ label. 2878 Diag(New->getLocation(), diag::err_different_asm_label); 2879 Diag(OldA->getLocation(), diag::note_previous_declaration); 2880 } 2881 } else if (Old->isUsed()) { 2882 // This redeclaration adds an __asm__ label to a declaration that has 2883 // already been ODR-used. 2884 Diag(New->getLocation(), diag::err_late_asm_label_name) 2885 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2886 } 2887 } 2888 2889 // Re-declaration cannot add abi_tag's. 2890 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2891 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2892 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2893 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2894 NewTag) == OldAbiTagAttr->tags_end()) { 2895 Diag(NewAbiTagAttr->getLocation(), 2896 diag::err_new_abi_tag_on_redeclaration) 2897 << NewTag; 2898 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2899 } 2900 } 2901 } else { 2902 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2903 Diag(Old->getLocation(), diag::note_previous_declaration); 2904 } 2905 } 2906 2907 // This redeclaration adds a section attribute. 2908 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2909 if (auto *VD = dyn_cast<VarDecl>(New)) { 2910 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2911 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2912 Diag(Old->getLocation(), diag::note_previous_declaration); 2913 } 2914 } 2915 } 2916 2917 // Redeclaration adds code-seg attribute. 2918 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2919 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2920 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2921 Diag(New->getLocation(), diag::warn_mismatched_section) 2922 << 0 /*codeseg*/; 2923 Diag(Old->getLocation(), diag::note_previous_declaration); 2924 } 2925 2926 if (!Old->hasAttrs()) 2927 return; 2928 2929 bool foundAny = New->hasAttrs(); 2930 2931 // Ensure that any moving of objects within the allocated map is done before 2932 // we process them. 2933 if (!foundAny) New->setAttrs(AttrVec()); 2934 2935 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2936 // Ignore deprecated/unavailable/availability attributes if requested. 2937 AvailabilityMergeKind LocalAMK = AMK_None; 2938 if (isa<DeprecatedAttr>(I) || 2939 isa<UnavailableAttr>(I) || 2940 isa<AvailabilityAttr>(I)) { 2941 switch (AMK) { 2942 case AMK_None: 2943 continue; 2944 2945 case AMK_Redeclaration: 2946 case AMK_Override: 2947 case AMK_ProtocolImplementation: 2948 LocalAMK = AMK; 2949 break; 2950 } 2951 } 2952 2953 // Already handled. 2954 if (isa<UsedAttr>(I)) 2955 continue; 2956 2957 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2958 foundAny = true; 2959 } 2960 2961 if (mergeAlignedAttrs(*this, New, Old)) 2962 foundAny = true; 2963 2964 if (!foundAny) New->dropAttrs(); 2965 } 2966 2967 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2968 /// to the new one. 2969 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2970 const ParmVarDecl *oldDecl, 2971 Sema &S) { 2972 // C++11 [dcl.attr.depend]p2: 2973 // The first declaration of a function shall specify the 2974 // carries_dependency attribute for its declarator-id if any declaration 2975 // of the function specifies the carries_dependency attribute. 2976 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2977 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2978 S.Diag(CDA->getLocation(), 2979 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2980 // Find the first declaration of the parameter. 2981 // FIXME: Should we build redeclaration chains for function parameters? 2982 const FunctionDecl *FirstFD = 2983 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2984 const ParmVarDecl *FirstVD = 2985 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2986 S.Diag(FirstVD->getLocation(), 2987 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2988 } 2989 2990 if (!oldDecl->hasAttrs()) 2991 return; 2992 2993 bool foundAny = newDecl->hasAttrs(); 2994 2995 // Ensure that any moving of objects within the allocated map is 2996 // done before we process them. 2997 if (!foundAny) newDecl->setAttrs(AttrVec()); 2998 2999 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3000 if (!DeclHasAttr(newDecl, I)) { 3001 InheritableAttr *newAttr = 3002 cast<InheritableParamAttr>(I->clone(S.Context)); 3003 newAttr->setInherited(true); 3004 newDecl->addAttr(newAttr); 3005 foundAny = true; 3006 } 3007 } 3008 3009 if (!foundAny) newDecl->dropAttrs(); 3010 } 3011 3012 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3013 const ParmVarDecl *OldParam, 3014 Sema &S) { 3015 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3016 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3017 if (*Oldnullability != *Newnullability) { 3018 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3019 << DiagNullabilityKind( 3020 *Newnullability, 3021 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3022 != 0)) 3023 << DiagNullabilityKind( 3024 *Oldnullability, 3025 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3026 != 0)); 3027 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3028 } 3029 } else { 3030 QualType NewT = NewParam->getType(); 3031 NewT = S.Context.getAttributedType( 3032 AttributedType::getNullabilityAttrKind(*Oldnullability), 3033 NewT, NewT); 3034 NewParam->setType(NewT); 3035 } 3036 } 3037 } 3038 3039 namespace { 3040 3041 /// Used in MergeFunctionDecl to keep track of function parameters in 3042 /// C. 3043 struct GNUCompatibleParamWarning { 3044 ParmVarDecl *OldParm; 3045 ParmVarDecl *NewParm; 3046 QualType PromotedType; 3047 }; 3048 3049 } // end anonymous namespace 3050 3051 // Determine whether the previous declaration was a definition, implicit 3052 // declaration, or a declaration. 3053 template <typename T> 3054 static std::pair<diag::kind, SourceLocation> 3055 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3056 diag::kind PrevDiag; 3057 SourceLocation OldLocation = Old->getLocation(); 3058 if (Old->isThisDeclarationADefinition()) 3059 PrevDiag = diag::note_previous_definition; 3060 else if (Old->isImplicit()) { 3061 PrevDiag = diag::note_previous_implicit_declaration; 3062 if (OldLocation.isInvalid()) 3063 OldLocation = New->getLocation(); 3064 } else 3065 PrevDiag = diag::note_previous_declaration; 3066 return std::make_pair(PrevDiag, OldLocation); 3067 } 3068 3069 /// canRedefineFunction - checks if a function can be redefined. Currently, 3070 /// only extern inline functions can be redefined, and even then only in 3071 /// GNU89 mode. 3072 static bool canRedefineFunction(const FunctionDecl *FD, 3073 const LangOptions& LangOpts) { 3074 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3075 !LangOpts.CPlusPlus && 3076 FD->isInlineSpecified() && 3077 FD->getStorageClass() == SC_Extern); 3078 } 3079 3080 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3081 const AttributedType *AT = T->getAs<AttributedType>(); 3082 while (AT && !AT->isCallingConv()) 3083 AT = AT->getModifiedType()->getAs<AttributedType>(); 3084 return AT; 3085 } 3086 3087 template <typename T> 3088 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3089 const DeclContext *DC = Old->getDeclContext(); 3090 if (DC->isRecord()) 3091 return false; 3092 3093 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3094 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3095 return true; 3096 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3097 return true; 3098 return false; 3099 } 3100 3101 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3102 static bool isExternC(VarTemplateDecl *) { return false; } 3103 3104 /// Check whether a redeclaration of an entity introduced by a 3105 /// using-declaration is valid, given that we know it's not an overload 3106 /// (nor a hidden tag declaration). 3107 template<typename ExpectedDecl> 3108 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3109 ExpectedDecl *New) { 3110 // C++11 [basic.scope.declarative]p4: 3111 // Given a set of declarations in a single declarative region, each of 3112 // which specifies the same unqualified name, 3113 // -- they shall all refer to the same entity, or all refer to functions 3114 // and function templates; or 3115 // -- exactly one declaration shall declare a class name or enumeration 3116 // name that is not a typedef name and the other declarations shall all 3117 // refer to the same variable or enumerator, or all refer to functions 3118 // and function templates; in this case the class name or enumeration 3119 // name is hidden (3.3.10). 3120 3121 // C++11 [namespace.udecl]p14: 3122 // If a function declaration in namespace scope or block scope has the 3123 // same name and the same parameter-type-list as a function introduced 3124 // by a using-declaration, and the declarations do not declare the same 3125 // function, the program is ill-formed. 3126 3127 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3128 if (Old && 3129 !Old->getDeclContext()->getRedeclContext()->Equals( 3130 New->getDeclContext()->getRedeclContext()) && 3131 !(isExternC(Old) && isExternC(New))) 3132 Old = nullptr; 3133 3134 if (!Old) { 3135 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3136 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3137 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3138 return true; 3139 } 3140 return false; 3141 } 3142 3143 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3144 const FunctionDecl *B) { 3145 assert(A->getNumParams() == B->getNumParams()); 3146 3147 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3148 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3149 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3150 if (AttrA == AttrB) 3151 return true; 3152 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3153 AttrA->isDynamic() == AttrB->isDynamic(); 3154 }; 3155 3156 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3157 } 3158 3159 /// If necessary, adjust the semantic declaration context for a qualified 3160 /// declaration to name the correct inline namespace within the qualifier. 3161 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3162 DeclaratorDecl *OldD) { 3163 // The only case where we need to update the DeclContext is when 3164 // redeclaration lookup for a qualified name finds a declaration 3165 // in an inline namespace within the context named by the qualifier: 3166 // 3167 // inline namespace N { int f(); } 3168 // int ::f(); // Sema DC needs adjusting from :: to N::. 3169 // 3170 // For unqualified declarations, the semantic context *can* change 3171 // along the redeclaration chain (for local extern declarations, 3172 // extern "C" declarations, and friend declarations in particular). 3173 if (!NewD->getQualifier()) 3174 return; 3175 3176 // NewD is probably already in the right context. 3177 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3178 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3179 if (NamedDC->Equals(SemaDC)) 3180 return; 3181 3182 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3183 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3184 "unexpected context for redeclaration"); 3185 3186 auto *LexDC = NewD->getLexicalDeclContext(); 3187 auto FixSemaDC = [=](NamedDecl *D) { 3188 if (!D) 3189 return; 3190 D->setDeclContext(SemaDC); 3191 D->setLexicalDeclContext(LexDC); 3192 }; 3193 3194 FixSemaDC(NewD); 3195 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3196 FixSemaDC(FD->getDescribedFunctionTemplate()); 3197 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3198 FixSemaDC(VD->getDescribedVarTemplate()); 3199 } 3200 3201 /// MergeFunctionDecl - We just parsed a function 'New' from 3202 /// declarator D which has the same name and scope as a previous 3203 /// declaration 'Old'. Figure out how to resolve this situation, 3204 /// merging decls or emitting diagnostics as appropriate. 3205 /// 3206 /// In C++, New and Old must be declarations that are not 3207 /// overloaded. Use IsOverload to determine whether New and Old are 3208 /// overloaded, and to select the Old declaration that New should be 3209 /// merged with. 3210 /// 3211 /// Returns true if there was an error, false otherwise. 3212 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3213 Scope *S, bool MergeTypeWithOld) { 3214 // Verify the old decl was also a function. 3215 FunctionDecl *Old = OldD->getAsFunction(); 3216 if (!Old) { 3217 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3218 if (New->getFriendObjectKind()) { 3219 Diag(New->getLocation(), diag::err_using_decl_friend); 3220 Diag(Shadow->getTargetDecl()->getLocation(), 3221 diag::note_using_decl_target); 3222 Diag(Shadow->getUsingDecl()->getLocation(), 3223 diag::note_using_decl) << 0; 3224 return true; 3225 } 3226 3227 // Check whether the two declarations might declare the same function. 3228 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3229 return true; 3230 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3231 } else { 3232 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3233 << New->getDeclName(); 3234 notePreviousDefinition(OldD, New->getLocation()); 3235 return true; 3236 } 3237 } 3238 3239 // If the old declaration is invalid, just give up here. 3240 if (Old->isInvalidDecl()) 3241 return true; 3242 3243 // Disallow redeclaration of some builtins. 3244 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3245 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3246 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3247 << Old << Old->getType(); 3248 return true; 3249 } 3250 3251 diag::kind PrevDiag; 3252 SourceLocation OldLocation; 3253 std::tie(PrevDiag, OldLocation) = 3254 getNoteDiagForInvalidRedeclaration(Old, New); 3255 3256 // Don't complain about this if we're in GNU89 mode and the old function 3257 // is an extern inline function. 3258 // Don't complain about specializations. They are not supposed to have 3259 // storage classes. 3260 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3261 New->getStorageClass() == SC_Static && 3262 Old->hasExternalFormalLinkage() && 3263 !New->getTemplateSpecializationInfo() && 3264 !canRedefineFunction(Old, getLangOpts())) { 3265 if (getLangOpts().MicrosoftExt) { 3266 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3267 Diag(OldLocation, PrevDiag); 3268 } else { 3269 Diag(New->getLocation(), diag::err_static_non_static) << New; 3270 Diag(OldLocation, PrevDiag); 3271 return true; 3272 } 3273 } 3274 3275 if (New->hasAttr<InternalLinkageAttr>() && 3276 !Old->hasAttr<InternalLinkageAttr>()) { 3277 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3278 << New->getDeclName(); 3279 notePreviousDefinition(Old, New->getLocation()); 3280 New->dropAttr<InternalLinkageAttr>(); 3281 } 3282 3283 if (CheckRedeclarationModuleOwnership(New, Old)) 3284 return true; 3285 3286 if (!getLangOpts().CPlusPlus) { 3287 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3288 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3289 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3290 << New << OldOvl; 3291 3292 // Try our best to find a decl that actually has the overloadable 3293 // attribute for the note. In most cases (e.g. programs with only one 3294 // broken declaration/definition), this won't matter. 3295 // 3296 // FIXME: We could do this if we juggled some extra state in 3297 // OverloadableAttr, rather than just removing it. 3298 const Decl *DiagOld = Old; 3299 if (OldOvl) { 3300 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3301 const auto *A = D->getAttr<OverloadableAttr>(); 3302 return A && !A->isImplicit(); 3303 }); 3304 // If we've implicitly added *all* of the overloadable attrs to this 3305 // chain, emitting a "previous redecl" note is pointless. 3306 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3307 } 3308 3309 if (DiagOld) 3310 Diag(DiagOld->getLocation(), 3311 diag::note_attribute_overloadable_prev_overload) 3312 << OldOvl; 3313 3314 if (OldOvl) 3315 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3316 else 3317 New->dropAttr<OverloadableAttr>(); 3318 } 3319 } 3320 3321 // If a function is first declared with a calling convention, but is later 3322 // declared or defined without one, all following decls assume the calling 3323 // convention of the first. 3324 // 3325 // It's OK if a function is first declared without a calling convention, 3326 // but is later declared or defined with the default calling convention. 3327 // 3328 // To test if either decl has an explicit calling convention, we look for 3329 // AttributedType sugar nodes on the type as written. If they are missing or 3330 // were canonicalized away, we assume the calling convention was implicit. 3331 // 3332 // Note also that we DO NOT return at this point, because we still have 3333 // other tests to run. 3334 QualType OldQType = Context.getCanonicalType(Old->getType()); 3335 QualType NewQType = Context.getCanonicalType(New->getType()); 3336 const FunctionType *OldType = cast<FunctionType>(OldQType); 3337 const FunctionType *NewType = cast<FunctionType>(NewQType); 3338 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3339 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3340 bool RequiresAdjustment = false; 3341 3342 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3343 FunctionDecl *First = Old->getFirstDecl(); 3344 const FunctionType *FT = 3345 First->getType().getCanonicalType()->castAs<FunctionType>(); 3346 FunctionType::ExtInfo FI = FT->getExtInfo(); 3347 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3348 if (!NewCCExplicit) { 3349 // Inherit the CC from the previous declaration if it was specified 3350 // there but not here. 3351 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3352 RequiresAdjustment = true; 3353 } else if (Old->getBuiltinID()) { 3354 // Builtin attribute isn't propagated to the new one yet at this point, 3355 // so we check if the old one is a builtin. 3356 3357 // Calling Conventions on a Builtin aren't really useful and setting a 3358 // default calling convention and cdecl'ing some builtin redeclarations is 3359 // common, so warn and ignore the calling convention on the redeclaration. 3360 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3361 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3362 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3363 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3364 RequiresAdjustment = true; 3365 } else { 3366 // Calling conventions aren't compatible, so complain. 3367 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3368 Diag(New->getLocation(), diag::err_cconv_change) 3369 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3370 << !FirstCCExplicit 3371 << (!FirstCCExplicit ? "" : 3372 FunctionType::getNameForCallConv(FI.getCC())); 3373 3374 // Put the note on the first decl, since it is the one that matters. 3375 Diag(First->getLocation(), diag::note_previous_declaration); 3376 return true; 3377 } 3378 } 3379 3380 // FIXME: diagnose the other way around? 3381 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3382 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3383 RequiresAdjustment = true; 3384 } 3385 3386 // Merge regparm attribute. 3387 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3388 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3389 if (NewTypeInfo.getHasRegParm()) { 3390 Diag(New->getLocation(), diag::err_regparm_mismatch) 3391 << NewType->getRegParmType() 3392 << OldType->getRegParmType(); 3393 Diag(OldLocation, diag::note_previous_declaration); 3394 return true; 3395 } 3396 3397 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3398 RequiresAdjustment = true; 3399 } 3400 3401 // Merge ns_returns_retained attribute. 3402 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3403 if (NewTypeInfo.getProducesResult()) { 3404 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3405 << "'ns_returns_retained'"; 3406 Diag(OldLocation, diag::note_previous_declaration); 3407 return true; 3408 } 3409 3410 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3411 RequiresAdjustment = true; 3412 } 3413 3414 if (OldTypeInfo.getNoCallerSavedRegs() != 3415 NewTypeInfo.getNoCallerSavedRegs()) { 3416 if (NewTypeInfo.getNoCallerSavedRegs()) { 3417 AnyX86NoCallerSavedRegistersAttr *Attr = 3418 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3419 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3420 Diag(OldLocation, diag::note_previous_declaration); 3421 return true; 3422 } 3423 3424 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3425 RequiresAdjustment = true; 3426 } 3427 3428 if (RequiresAdjustment) { 3429 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3430 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3431 New->setType(QualType(AdjustedType, 0)); 3432 NewQType = Context.getCanonicalType(New->getType()); 3433 } 3434 3435 // If this redeclaration makes the function inline, we may need to add it to 3436 // UndefinedButUsed. 3437 if (!Old->isInlined() && New->isInlined() && 3438 !New->hasAttr<GNUInlineAttr>() && 3439 !getLangOpts().GNUInline && 3440 Old->isUsed(false) && 3441 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3442 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3443 SourceLocation())); 3444 3445 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3446 // about it. 3447 if (New->hasAttr<GNUInlineAttr>() && 3448 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3449 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3450 } 3451 3452 // If pass_object_size params don't match up perfectly, this isn't a valid 3453 // redeclaration. 3454 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3455 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3456 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3457 << New->getDeclName(); 3458 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3459 return true; 3460 } 3461 3462 if (getLangOpts().CPlusPlus) { 3463 // C++1z [over.load]p2 3464 // Certain function declarations cannot be overloaded: 3465 // -- Function declarations that differ only in the return type, 3466 // the exception specification, or both cannot be overloaded. 3467 3468 // Check the exception specifications match. This may recompute the type of 3469 // both Old and New if it resolved exception specifications, so grab the 3470 // types again after this. Because this updates the type, we do this before 3471 // any of the other checks below, which may update the "de facto" NewQType 3472 // but do not necessarily update the type of New. 3473 if (CheckEquivalentExceptionSpec(Old, New)) 3474 return true; 3475 OldQType = Context.getCanonicalType(Old->getType()); 3476 NewQType = Context.getCanonicalType(New->getType()); 3477 3478 // Go back to the type source info to compare the declared return types, 3479 // per C++1y [dcl.type.auto]p13: 3480 // Redeclarations or specializations of a function or function template 3481 // with a declared return type that uses a placeholder type shall also 3482 // use that placeholder, not a deduced type. 3483 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3484 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3485 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3486 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3487 OldDeclaredReturnType)) { 3488 QualType ResQT; 3489 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3490 OldDeclaredReturnType->isObjCObjectPointerType()) 3491 // FIXME: This does the wrong thing for a deduced return type. 3492 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3493 if (ResQT.isNull()) { 3494 if (New->isCXXClassMember() && New->isOutOfLine()) 3495 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3496 << New << New->getReturnTypeSourceRange(); 3497 else 3498 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3499 << New->getReturnTypeSourceRange(); 3500 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3501 << Old->getReturnTypeSourceRange(); 3502 return true; 3503 } 3504 else 3505 NewQType = ResQT; 3506 } 3507 3508 QualType OldReturnType = OldType->getReturnType(); 3509 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3510 if (OldReturnType != NewReturnType) { 3511 // If this function has a deduced return type and has already been 3512 // defined, copy the deduced value from the old declaration. 3513 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3514 if (OldAT && OldAT->isDeduced()) { 3515 New->setType( 3516 SubstAutoType(New->getType(), 3517 OldAT->isDependentType() ? Context.DependentTy 3518 : OldAT->getDeducedType())); 3519 NewQType = Context.getCanonicalType( 3520 SubstAutoType(NewQType, 3521 OldAT->isDependentType() ? Context.DependentTy 3522 : OldAT->getDeducedType())); 3523 } 3524 } 3525 3526 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3527 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3528 if (OldMethod && NewMethod) { 3529 // Preserve triviality. 3530 NewMethod->setTrivial(OldMethod->isTrivial()); 3531 3532 // MSVC allows explicit template specialization at class scope: 3533 // 2 CXXMethodDecls referring to the same function will be injected. 3534 // We don't want a redeclaration error. 3535 bool IsClassScopeExplicitSpecialization = 3536 OldMethod->isFunctionTemplateSpecialization() && 3537 NewMethod->isFunctionTemplateSpecialization(); 3538 bool isFriend = NewMethod->getFriendObjectKind(); 3539 3540 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3541 !IsClassScopeExplicitSpecialization) { 3542 // -- Member function declarations with the same name and the 3543 // same parameter types cannot be overloaded if any of them 3544 // is a static member function declaration. 3545 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3547 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3548 return true; 3549 } 3550 3551 // C++ [class.mem]p1: 3552 // [...] A member shall not be declared twice in the 3553 // member-specification, except that a nested class or member 3554 // class template can be declared and then later defined. 3555 if (!inTemplateInstantiation()) { 3556 unsigned NewDiag; 3557 if (isa<CXXConstructorDecl>(OldMethod)) 3558 NewDiag = diag::err_constructor_redeclared; 3559 else if (isa<CXXDestructorDecl>(NewMethod)) 3560 NewDiag = diag::err_destructor_redeclared; 3561 else if (isa<CXXConversionDecl>(NewMethod)) 3562 NewDiag = diag::err_conv_function_redeclared; 3563 else 3564 NewDiag = diag::err_member_redeclared; 3565 3566 Diag(New->getLocation(), NewDiag); 3567 } else { 3568 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3569 << New << New->getType(); 3570 } 3571 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3572 return true; 3573 3574 // Complain if this is an explicit declaration of a special 3575 // member that was initially declared implicitly. 3576 // 3577 // As an exception, it's okay to befriend such methods in order 3578 // to permit the implicit constructor/destructor/operator calls. 3579 } else if (OldMethod->isImplicit()) { 3580 if (isFriend) { 3581 NewMethod->setImplicit(); 3582 } else { 3583 Diag(NewMethod->getLocation(), 3584 diag::err_definition_of_implicitly_declared_member) 3585 << New << getSpecialMember(OldMethod); 3586 return true; 3587 } 3588 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3589 Diag(NewMethod->getLocation(), 3590 diag::err_definition_of_explicitly_defaulted_member) 3591 << getSpecialMember(OldMethod); 3592 return true; 3593 } 3594 } 3595 3596 // C++11 [dcl.attr.noreturn]p1: 3597 // The first declaration of a function shall specify the noreturn 3598 // attribute if any declaration of that function specifies the noreturn 3599 // attribute. 3600 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3601 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3602 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3603 Diag(Old->getFirstDecl()->getLocation(), 3604 diag::note_noreturn_missing_first_decl); 3605 } 3606 3607 // C++11 [dcl.attr.depend]p2: 3608 // The first declaration of a function shall specify the 3609 // carries_dependency attribute for its declarator-id if any declaration 3610 // of the function specifies the carries_dependency attribute. 3611 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3612 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3613 Diag(CDA->getLocation(), 3614 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3615 Diag(Old->getFirstDecl()->getLocation(), 3616 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3617 } 3618 3619 // (C++98 8.3.5p3): 3620 // All declarations for a function shall agree exactly in both the 3621 // return type and the parameter-type-list. 3622 // We also want to respect all the extended bits except noreturn. 3623 3624 // noreturn should now match unless the old type info didn't have it. 3625 QualType OldQTypeForComparison = OldQType; 3626 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3627 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3628 const FunctionType *OldTypeForComparison 3629 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3630 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3631 assert(OldQTypeForComparison.isCanonical()); 3632 } 3633 3634 if (haveIncompatibleLanguageLinkages(Old, New)) { 3635 // As a special case, retain the language linkage from previous 3636 // declarations of a friend function as an extension. 3637 // 3638 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3639 // and is useful because there's otherwise no way to specify language 3640 // linkage within class scope. 3641 // 3642 // Check cautiously as the friend object kind isn't yet complete. 3643 if (New->getFriendObjectKind() != Decl::FOK_None) { 3644 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3645 Diag(OldLocation, PrevDiag); 3646 } else { 3647 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3648 Diag(OldLocation, PrevDiag); 3649 return true; 3650 } 3651 } 3652 3653 // If the function types are compatible, merge the declarations. Ignore the 3654 // exception specifier because it was already checked above in 3655 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3656 // about incompatible types under -fms-compatibility. 3657 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3658 NewQType)) 3659 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3660 3661 // If the types are imprecise (due to dependent constructs in friends or 3662 // local extern declarations), it's OK if they differ. We'll check again 3663 // during instantiation. 3664 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3665 return false; 3666 3667 // Fall through for conflicting redeclarations and redefinitions. 3668 } 3669 3670 // C: Function types need to be compatible, not identical. This handles 3671 // duplicate function decls like "void f(int); void f(enum X);" properly. 3672 if (!getLangOpts().CPlusPlus && 3673 Context.typesAreCompatible(OldQType, NewQType)) { 3674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3676 const FunctionProtoType *OldProto = nullptr; 3677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3679 // The old declaration provided a function prototype, but the 3680 // new declaration does not. Merge in the prototype. 3681 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3682 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3683 NewQType = 3684 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3685 OldProto->getExtProtoInfo()); 3686 New->setType(NewQType); 3687 New->setHasInheritedPrototype(); 3688 3689 // Synthesize parameters with the same types. 3690 SmallVector<ParmVarDecl*, 16> Params; 3691 for (const auto &ParamType : OldProto->param_types()) { 3692 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3693 SourceLocation(), nullptr, 3694 ParamType, /*TInfo=*/nullptr, 3695 SC_None, nullptr); 3696 Param->setScopeInfo(0, Params.size()); 3697 Param->setImplicit(); 3698 Params.push_back(Param); 3699 } 3700 3701 New->setParams(Params); 3702 } 3703 3704 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3705 } 3706 3707 // Check if the function types are compatible when pointer size address 3708 // spaces are ignored. 3709 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3710 return false; 3711 3712 // GNU C permits a K&R definition to follow a prototype declaration 3713 // if the declared types of the parameters in the K&R definition 3714 // match the types in the prototype declaration, even when the 3715 // promoted types of the parameters from the K&R definition differ 3716 // from the types in the prototype. GCC then keeps the types from 3717 // the prototype. 3718 // 3719 // If a variadic prototype is followed by a non-variadic K&R definition, 3720 // the K&R definition becomes variadic. This is sort of an edge case, but 3721 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3722 // C99 6.9.1p8. 3723 if (!getLangOpts().CPlusPlus && 3724 Old->hasPrototype() && !New->hasPrototype() && 3725 New->getType()->getAs<FunctionProtoType>() && 3726 Old->getNumParams() == New->getNumParams()) { 3727 SmallVector<QualType, 16> ArgTypes; 3728 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3729 const FunctionProtoType *OldProto 3730 = Old->getType()->getAs<FunctionProtoType>(); 3731 const FunctionProtoType *NewProto 3732 = New->getType()->getAs<FunctionProtoType>(); 3733 3734 // Determine whether this is the GNU C extension. 3735 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3736 NewProto->getReturnType()); 3737 bool LooseCompatible = !MergedReturn.isNull(); 3738 for (unsigned Idx = 0, End = Old->getNumParams(); 3739 LooseCompatible && Idx != End; ++Idx) { 3740 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3741 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3742 if (Context.typesAreCompatible(OldParm->getType(), 3743 NewProto->getParamType(Idx))) { 3744 ArgTypes.push_back(NewParm->getType()); 3745 } else if (Context.typesAreCompatible(OldParm->getType(), 3746 NewParm->getType(), 3747 /*CompareUnqualified=*/true)) { 3748 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3749 NewProto->getParamType(Idx) }; 3750 Warnings.push_back(Warn); 3751 ArgTypes.push_back(NewParm->getType()); 3752 } else 3753 LooseCompatible = false; 3754 } 3755 3756 if (LooseCompatible) { 3757 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3758 Diag(Warnings[Warn].NewParm->getLocation(), 3759 diag::ext_param_promoted_not_compatible_with_prototype) 3760 << Warnings[Warn].PromotedType 3761 << Warnings[Warn].OldParm->getType(); 3762 if (Warnings[Warn].OldParm->getLocation().isValid()) 3763 Diag(Warnings[Warn].OldParm->getLocation(), 3764 diag::note_previous_declaration); 3765 } 3766 3767 if (MergeTypeWithOld) 3768 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3769 OldProto->getExtProtoInfo())); 3770 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3771 } 3772 3773 // Fall through to diagnose conflicting types. 3774 } 3775 3776 // A function that has already been declared has been redeclared or 3777 // defined with a different type; show an appropriate diagnostic. 3778 3779 // If the previous declaration was an implicitly-generated builtin 3780 // declaration, then at the very least we should use a specialized note. 3781 unsigned BuiltinID; 3782 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3783 // If it's actually a library-defined builtin function like 'malloc' 3784 // or 'printf', just warn about the incompatible redeclaration. 3785 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3786 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3787 Diag(OldLocation, diag::note_previous_builtin_declaration) 3788 << Old << Old->getType(); 3789 return false; 3790 } 3791 3792 PrevDiag = diag::note_previous_builtin_declaration; 3793 } 3794 3795 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3796 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3797 return true; 3798 } 3799 3800 /// Completes the merge of two function declarations that are 3801 /// known to be compatible. 3802 /// 3803 /// This routine handles the merging of attributes and other 3804 /// properties of function declarations from the old declaration to 3805 /// the new declaration, once we know that New is in fact a 3806 /// redeclaration of Old. 3807 /// 3808 /// \returns false 3809 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3810 Scope *S, bool MergeTypeWithOld) { 3811 // Merge the attributes 3812 mergeDeclAttributes(New, Old); 3813 3814 // Merge "pure" flag. 3815 if (Old->isPure()) 3816 New->setPure(); 3817 3818 // Merge "used" flag. 3819 if (Old->getMostRecentDecl()->isUsed(false)) 3820 New->setIsUsed(); 3821 3822 // Merge attributes from the parameters. These can mismatch with K&R 3823 // declarations. 3824 if (New->getNumParams() == Old->getNumParams()) 3825 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3826 ParmVarDecl *NewParam = New->getParamDecl(i); 3827 ParmVarDecl *OldParam = Old->getParamDecl(i); 3828 mergeParamDeclAttributes(NewParam, OldParam, *this); 3829 mergeParamDeclTypes(NewParam, OldParam, *this); 3830 } 3831 3832 if (getLangOpts().CPlusPlus) 3833 return MergeCXXFunctionDecl(New, Old, S); 3834 3835 // Merge the function types so the we get the composite types for the return 3836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3837 // was visible. 3838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3839 if (!Merged.isNull() && MergeTypeWithOld) 3840 New->setType(Merged); 3841 3842 return false; 3843 } 3844 3845 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3846 ObjCMethodDecl *oldMethod) { 3847 // Merge the attributes, including deprecated/unavailable 3848 AvailabilityMergeKind MergeKind = 3849 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3850 ? AMK_ProtocolImplementation 3851 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3852 : AMK_Override; 3853 3854 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3855 3856 // Merge attributes from the parameters. 3857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3858 oe = oldMethod->param_end(); 3859 for (ObjCMethodDecl::param_iterator 3860 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3861 ni != ne && oi != oe; ++ni, ++oi) 3862 mergeParamDeclAttributes(*ni, *oi, *this); 3863 3864 CheckObjCMethodOverride(newMethod, oldMethod); 3865 } 3866 3867 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3868 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3869 3870 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3871 ? diag::err_redefinition_different_type 3872 : diag::err_redeclaration_different_type) 3873 << New->getDeclName() << New->getType() << Old->getType(); 3874 3875 diag::kind PrevDiag; 3876 SourceLocation OldLocation; 3877 std::tie(PrevDiag, OldLocation) 3878 = getNoteDiagForInvalidRedeclaration(Old, New); 3879 S.Diag(OldLocation, PrevDiag); 3880 New->setInvalidDecl(); 3881 } 3882 3883 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3884 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3885 /// emitting diagnostics as appropriate. 3886 /// 3887 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3888 /// to here in AddInitializerToDecl. We can't check them before the initializer 3889 /// is attached. 3890 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3891 bool MergeTypeWithOld) { 3892 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3893 return; 3894 3895 QualType MergedT; 3896 if (getLangOpts().CPlusPlus) { 3897 if (New->getType()->isUndeducedType()) { 3898 // We don't know what the new type is until the initializer is attached. 3899 return; 3900 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3901 // These could still be something that needs exception specs checked. 3902 return MergeVarDeclExceptionSpecs(New, Old); 3903 } 3904 // C++ [basic.link]p10: 3905 // [...] the types specified by all declarations referring to a given 3906 // object or function shall be identical, except that declarations for an 3907 // array object can specify array types that differ by the presence or 3908 // absence of a major array bound (8.3.4). 3909 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3910 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3911 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3912 3913 // We are merging a variable declaration New into Old. If it has an array 3914 // bound, and that bound differs from Old's bound, we should diagnose the 3915 // mismatch. 3916 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3917 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3918 PrevVD = PrevVD->getPreviousDecl()) { 3919 QualType PrevVDTy = PrevVD->getType(); 3920 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3921 continue; 3922 3923 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3924 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3925 } 3926 } 3927 3928 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3929 if (Context.hasSameType(OldArray->getElementType(), 3930 NewArray->getElementType())) 3931 MergedT = New->getType(); 3932 } 3933 // FIXME: Check visibility. New is hidden but has a complete type. If New 3934 // has no array bound, it should not inherit one from Old, if Old is not 3935 // visible. 3936 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3937 if (Context.hasSameType(OldArray->getElementType(), 3938 NewArray->getElementType())) 3939 MergedT = Old->getType(); 3940 } 3941 } 3942 else if (New->getType()->isObjCObjectPointerType() && 3943 Old->getType()->isObjCObjectPointerType()) { 3944 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3945 Old->getType()); 3946 } 3947 } else { 3948 // C 6.2.7p2: 3949 // All declarations that refer to the same object or function shall have 3950 // compatible type. 3951 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3952 } 3953 if (MergedT.isNull()) { 3954 // It's OK if we couldn't merge types if either type is dependent, for a 3955 // block-scope variable. In other cases (static data members of class 3956 // templates, variable templates, ...), we require the types to be 3957 // equivalent. 3958 // FIXME: The C++ standard doesn't say anything about this. 3959 if ((New->getType()->isDependentType() || 3960 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3961 // If the old type was dependent, we can't merge with it, so the new type 3962 // becomes dependent for now. We'll reproduce the original type when we 3963 // instantiate the TypeSourceInfo for the variable. 3964 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3965 New->setType(Context.DependentTy); 3966 return; 3967 } 3968 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3969 } 3970 3971 // Don't actually update the type on the new declaration if the old 3972 // declaration was an extern declaration in a different scope. 3973 if (MergeTypeWithOld) 3974 New->setType(MergedT); 3975 } 3976 3977 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3978 LookupResult &Previous) { 3979 // C11 6.2.7p4: 3980 // For an identifier with internal or external linkage declared 3981 // in a scope in which a prior declaration of that identifier is 3982 // visible, if the prior declaration specifies internal or 3983 // external linkage, the type of the identifier at the later 3984 // declaration becomes the composite type. 3985 // 3986 // If the variable isn't visible, we do not merge with its type. 3987 if (Previous.isShadowed()) 3988 return false; 3989 3990 if (S.getLangOpts().CPlusPlus) { 3991 // C++11 [dcl.array]p3: 3992 // If there is a preceding declaration of the entity in the same 3993 // scope in which the bound was specified, an omitted array bound 3994 // is taken to be the same as in that earlier declaration. 3995 return NewVD->isPreviousDeclInSameBlockScope() || 3996 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3997 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3998 } else { 3999 // If the old declaration was function-local, don't merge with its 4000 // type unless we're in the same function. 4001 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4002 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4003 } 4004 } 4005 4006 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4007 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4008 /// situation, merging decls or emitting diagnostics as appropriate. 4009 /// 4010 /// Tentative definition rules (C99 6.9.2p2) are checked by 4011 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4012 /// definitions here, since the initializer hasn't been attached. 4013 /// 4014 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4015 // If the new decl is already invalid, don't do any other checking. 4016 if (New->isInvalidDecl()) 4017 return; 4018 4019 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4020 return; 4021 4022 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4023 4024 // Verify the old decl was also a variable or variable template. 4025 VarDecl *Old = nullptr; 4026 VarTemplateDecl *OldTemplate = nullptr; 4027 if (Previous.isSingleResult()) { 4028 if (NewTemplate) { 4029 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4030 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4031 4032 if (auto *Shadow = 4033 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4034 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4035 return New->setInvalidDecl(); 4036 } else { 4037 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4038 4039 if (auto *Shadow = 4040 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4041 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4042 return New->setInvalidDecl(); 4043 } 4044 } 4045 if (!Old) { 4046 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4047 << New->getDeclName(); 4048 notePreviousDefinition(Previous.getRepresentativeDecl(), 4049 New->getLocation()); 4050 return New->setInvalidDecl(); 4051 } 4052 4053 // Ensure the template parameters are compatible. 4054 if (NewTemplate && 4055 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4056 OldTemplate->getTemplateParameters(), 4057 /*Complain=*/true, TPL_TemplateMatch)) 4058 return New->setInvalidDecl(); 4059 4060 // C++ [class.mem]p1: 4061 // A member shall not be declared twice in the member-specification [...] 4062 // 4063 // Here, we need only consider static data members. 4064 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4065 Diag(New->getLocation(), diag::err_duplicate_member) 4066 << New->getIdentifier(); 4067 Diag(Old->getLocation(), diag::note_previous_declaration); 4068 New->setInvalidDecl(); 4069 } 4070 4071 mergeDeclAttributes(New, Old); 4072 // Warn if an already-declared variable is made a weak_import in a subsequent 4073 // declaration 4074 if (New->hasAttr<WeakImportAttr>() && 4075 Old->getStorageClass() == SC_None && 4076 !Old->hasAttr<WeakImportAttr>()) { 4077 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4078 notePreviousDefinition(Old, New->getLocation()); 4079 // Remove weak_import attribute on new declaration. 4080 New->dropAttr<WeakImportAttr>(); 4081 } 4082 4083 if (New->hasAttr<InternalLinkageAttr>() && 4084 !Old->hasAttr<InternalLinkageAttr>()) { 4085 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4086 << New->getDeclName(); 4087 notePreviousDefinition(Old, New->getLocation()); 4088 New->dropAttr<InternalLinkageAttr>(); 4089 } 4090 4091 // Merge the types. 4092 VarDecl *MostRecent = Old->getMostRecentDecl(); 4093 if (MostRecent != Old) { 4094 MergeVarDeclTypes(New, MostRecent, 4095 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4096 if (New->isInvalidDecl()) 4097 return; 4098 } 4099 4100 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4101 if (New->isInvalidDecl()) 4102 return; 4103 4104 diag::kind PrevDiag; 4105 SourceLocation OldLocation; 4106 std::tie(PrevDiag, OldLocation) = 4107 getNoteDiagForInvalidRedeclaration(Old, New); 4108 4109 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4110 if (New->getStorageClass() == SC_Static && 4111 !New->isStaticDataMember() && 4112 Old->hasExternalFormalLinkage()) { 4113 if (getLangOpts().MicrosoftExt) { 4114 Diag(New->getLocation(), diag::ext_static_non_static) 4115 << New->getDeclName(); 4116 Diag(OldLocation, PrevDiag); 4117 } else { 4118 Diag(New->getLocation(), diag::err_static_non_static) 4119 << New->getDeclName(); 4120 Diag(OldLocation, PrevDiag); 4121 return New->setInvalidDecl(); 4122 } 4123 } 4124 // C99 6.2.2p4: 4125 // For an identifier declared with the storage-class specifier 4126 // extern in a scope in which a prior declaration of that 4127 // identifier is visible,23) if the prior declaration specifies 4128 // internal or external linkage, the linkage of the identifier at 4129 // the later declaration is the same as the linkage specified at 4130 // the prior declaration. If no prior declaration is visible, or 4131 // if the prior declaration specifies no linkage, then the 4132 // identifier has external linkage. 4133 if (New->hasExternalStorage() && Old->hasLinkage()) 4134 /* Okay */; 4135 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4136 !New->isStaticDataMember() && 4137 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4138 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4139 Diag(OldLocation, PrevDiag); 4140 return New->setInvalidDecl(); 4141 } 4142 4143 // Check if extern is followed by non-extern and vice-versa. 4144 if (New->hasExternalStorage() && 4145 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4146 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4147 Diag(OldLocation, PrevDiag); 4148 return New->setInvalidDecl(); 4149 } 4150 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4151 !New->hasExternalStorage()) { 4152 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4153 Diag(OldLocation, PrevDiag); 4154 return New->setInvalidDecl(); 4155 } 4156 4157 if (CheckRedeclarationModuleOwnership(New, Old)) 4158 return; 4159 4160 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4161 4162 // FIXME: The test for external storage here seems wrong? We still 4163 // need to check for mismatches. 4164 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4165 // Don't complain about out-of-line definitions of static members. 4166 !(Old->getLexicalDeclContext()->isRecord() && 4167 !New->getLexicalDeclContext()->isRecord())) { 4168 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4169 Diag(OldLocation, PrevDiag); 4170 return New->setInvalidDecl(); 4171 } 4172 4173 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4174 if (VarDecl *Def = Old->getDefinition()) { 4175 // C++1z [dcl.fcn.spec]p4: 4176 // If the definition of a variable appears in a translation unit before 4177 // its first declaration as inline, the program is ill-formed. 4178 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4179 Diag(Def->getLocation(), diag::note_previous_definition); 4180 } 4181 } 4182 4183 // If this redeclaration makes the variable inline, we may need to add it to 4184 // UndefinedButUsed. 4185 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4186 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4187 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4188 SourceLocation())); 4189 4190 if (New->getTLSKind() != Old->getTLSKind()) { 4191 if (!Old->getTLSKind()) { 4192 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4193 Diag(OldLocation, PrevDiag); 4194 } else if (!New->getTLSKind()) { 4195 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4196 Diag(OldLocation, PrevDiag); 4197 } else { 4198 // Do not allow redeclaration to change the variable between requiring 4199 // static and dynamic initialization. 4200 // FIXME: GCC allows this, but uses the TLS keyword on the first 4201 // declaration to determine the kind. Do we need to be compatible here? 4202 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4203 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4204 Diag(OldLocation, PrevDiag); 4205 } 4206 } 4207 4208 // C++ doesn't have tentative definitions, so go right ahead and check here. 4209 if (getLangOpts().CPlusPlus && 4210 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4211 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4212 Old->getCanonicalDecl()->isConstexpr()) { 4213 // This definition won't be a definition any more once it's been merged. 4214 Diag(New->getLocation(), 4215 diag::warn_deprecated_redundant_constexpr_static_def); 4216 } else if (VarDecl *Def = Old->getDefinition()) { 4217 if (checkVarDeclRedefinition(Def, New)) 4218 return; 4219 } 4220 } 4221 4222 if (haveIncompatibleLanguageLinkages(Old, New)) { 4223 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4224 Diag(OldLocation, PrevDiag); 4225 New->setInvalidDecl(); 4226 return; 4227 } 4228 4229 // Merge "used" flag. 4230 if (Old->getMostRecentDecl()->isUsed(false)) 4231 New->setIsUsed(); 4232 4233 // Keep a chain of previous declarations. 4234 New->setPreviousDecl(Old); 4235 if (NewTemplate) 4236 NewTemplate->setPreviousDecl(OldTemplate); 4237 adjustDeclContextForDeclaratorDecl(New, Old); 4238 4239 // Inherit access appropriately. 4240 New->setAccess(Old->getAccess()); 4241 if (NewTemplate) 4242 NewTemplate->setAccess(New->getAccess()); 4243 4244 if (Old->isInline()) 4245 New->setImplicitlyInline(); 4246 } 4247 4248 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4249 SourceManager &SrcMgr = getSourceManager(); 4250 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4251 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4252 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4253 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4254 auto &HSI = PP.getHeaderSearchInfo(); 4255 StringRef HdrFilename = 4256 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4257 4258 auto noteFromModuleOrInclude = [&](Module *Mod, 4259 SourceLocation IncLoc) -> bool { 4260 // Redefinition errors with modules are common with non modular mapped 4261 // headers, example: a non-modular header H in module A that also gets 4262 // included directly in a TU. Pointing twice to the same header/definition 4263 // is confusing, try to get better diagnostics when modules is on. 4264 if (IncLoc.isValid()) { 4265 if (Mod) { 4266 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4267 << HdrFilename.str() << Mod->getFullModuleName(); 4268 if (!Mod->DefinitionLoc.isInvalid()) 4269 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4270 << Mod->getFullModuleName(); 4271 } else { 4272 Diag(IncLoc, diag::note_redefinition_include_same_file) 4273 << HdrFilename.str(); 4274 } 4275 return true; 4276 } 4277 4278 return false; 4279 }; 4280 4281 // Is it the same file and same offset? Provide more information on why 4282 // this leads to a redefinition error. 4283 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4284 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4285 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4286 bool EmittedDiag = 4287 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4288 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4289 4290 // If the header has no guards, emit a note suggesting one. 4291 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4292 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4293 4294 if (EmittedDiag) 4295 return; 4296 } 4297 4298 // Redefinition coming from different files or couldn't do better above. 4299 if (Old->getLocation().isValid()) 4300 Diag(Old->getLocation(), diag::note_previous_definition); 4301 } 4302 4303 /// We've just determined that \p Old and \p New both appear to be definitions 4304 /// of the same variable. Either diagnose or fix the problem. 4305 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4306 if (!hasVisibleDefinition(Old) && 4307 (New->getFormalLinkage() == InternalLinkage || 4308 New->isInline() || 4309 New->getDescribedVarTemplate() || 4310 New->getNumTemplateParameterLists() || 4311 New->getDeclContext()->isDependentContext())) { 4312 // The previous definition is hidden, and multiple definitions are 4313 // permitted (in separate TUs). Demote this to a declaration. 4314 New->demoteThisDefinitionToDeclaration(); 4315 4316 // Make the canonical definition visible. 4317 if (auto *OldTD = Old->getDescribedVarTemplate()) 4318 makeMergedDefinitionVisible(OldTD); 4319 makeMergedDefinitionVisible(Old); 4320 return false; 4321 } else { 4322 Diag(New->getLocation(), diag::err_redefinition) << New; 4323 notePreviousDefinition(Old, New->getLocation()); 4324 New->setInvalidDecl(); 4325 return true; 4326 } 4327 } 4328 4329 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4330 /// no declarator (e.g. "struct foo;") is parsed. 4331 Decl * 4332 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4333 RecordDecl *&AnonRecord) { 4334 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4335 AnonRecord); 4336 } 4337 4338 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4339 // disambiguate entities defined in different scopes. 4340 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4341 // compatibility. 4342 // We will pick our mangling number depending on which version of MSVC is being 4343 // targeted. 4344 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4345 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4346 ? S->getMSCurManglingNumber() 4347 : S->getMSLastManglingNumber(); 4348 } 4349 4350 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4351 if (!Context.getLangOpts().CPlusPlus) 4352 return; 4353 4354 if (isa<CXXRecordDecl>(Tag->getParent())) { 4355 // If this tag is the direct child of a class, number it if 4356 // it is anonymous. 4357 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4358 return; 4359 MangleNumberingContext &MCtx = 4360 Context.getManglingNumberContext(Tag->getParent()); 4361 Context.setManglingNumber( 4362 Tag, MCtx.getManglingNumber( 4363 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4364 return; 4365 } 4366 4367 // If this tag isn't a direct child of a class, number it if it is local. 4368 MangleNumberingContext *MCtx; 4369 Decl *ManglingContextDecl; 4370 std::tie(MCtx, ManglingContextDecl) = 4371 getCurrentMangleNumberContext(Tag->getDeclContext()); 4372 if (MCtx) { 4373 Context.setManglingNumber( 4374 Tag, MCtx->getManglingNumber( 4375 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4376 } 4377 } 4378 4379 namespace { 4380 struct NonCLikeKind { 4381 enum { 4382 None, 4383 BaseClass, 4384 DefaultMemberInit, 4385 Lambda, 4386 Friend, 4387 OtherMember, 4388 Invalid, 4389 } Kind = None; 4390 SourceRange Range; 4391 4392 explicit operator bool() { return Kind != None; } 4393 }; 4394 } 4395 4396 /// Determine whether a class is C-like, according to the rules of C++ 4397 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4398 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4399 if (RD->isInvalidDecl()) 4400 return {NonCLikeKind::Invalid, {}}; 4401 4402 // C++ [dcl.typedef]p9: [P1766R1] 4403 // An unnamed class with a typedef name for linkage purposes shall not 4404 // 4405 // -- have any base classes 4406 if (RD->getNumBases()) 4407 return {NonCLikeKind::BaseClass, 4408 SourceRange(RD->bases_begin()->getBeginLoc(), 4409 RD->bases_end()[-1].getEndLoc())}; 4410 bool Invalid = false; 4411 for (Decl *D : RD->decls()) { 4412 // Don't complain about things we already diagnosed. 4413 if (D->isInvalidDecl()) { 4414 Invalid = true; 4415 continue; 4416 } 4417 4418 // -- have any [...] default member initializers 4419 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4420 if (FD->hasInClassInitializer()) { 4421 auto *Init = FD->getInClassInitializer(); 4422 return {NonCLikeKind::DefaultMemberInit, 4423 Init ? Init->getSourceRange() : D->getSourceRange()}; 4424 } 4425 continue; 4426 } 4427 4428 // FIXME: We don't allow friend declarations. This violates the wording of 4429 // P1766, but not the intent. 4430 if (isa<FriendDecl>(D)) 4431 return {NonCLikeKind::Friend, D->getSourceRange()}; 4432 4433 // -- declare any members other than non-static data members, member 4434 // enumerations, or member classes, 4435 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4436 isa<EnumDecl>(D)) 4437 continue; 4438 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4439 if (!MemberRD) { 4440 if (D->isImplicit()) 4441 continue; 4442 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4443 } 4444 4445 // -- contain a lambda-expression, 4446 if (MemberRD->isLambda()) 4447 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4448 4449 // and all member classes shall also satisfy these requirements 4450 // (recursively). 4451 if (MemberRD->isThisDeclarationADefinition()) { 4452 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4453 return Kind; 4454 } 4455 } 4456 4457 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4458 } 4459 4460 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4461 TypedefNameDecl *NewTD) { 4462 if (TagFromDeclSpec->isInvalidDecl()) 4463 return; 4464 4465 // Do nothing if the tag already has a name for linkage purposes. 4466 if (TagFromDeclSpec->hasNameForLinkage()) 4467 return; 4468 4469 // A well-formed anonymous tag must always be a TUK_Definition. 4470 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4471 4472 // The type must match the tag exactly; no qualifiers allowed. 4473 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4474 Context.getTagDeclType(TagFromDeclSpec))) { 4475 if (getLangOpts().CPlusPlus) 4476 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4477 return; 4478 } 4479 4480 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4481 // An unnamed class with a typedef name for linkage purposes shall [be 4482 // C-like]. 4483 // 4484 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4485 // shouldn't happen, but there are constructs that the language rule doesn't 4486 // disallow for which we can't reasonably avoid computing linkage early. 4487 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4488 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4489 : NonCLikeKind(); 4490 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4491 if (NonCLike || ChangesLinkage) { 4492 if (NonCLike.Kind == NonCLikeKind::Invalid) 4493 return; 4494 4495 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4496 if (ChangesLinkage) { 4497 // If the linkage changes, we can't accept this as an extension. 4498 if (NonCLike.Kind == NonCLikeKind::None) 4499 DiagID = diag::err_typedef_changes_linkage; 4500 else 4501 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4502 } 4503 4504 SourceLocation FixitLoc = 4505 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4506 llvm::SmallString<40> TextToInsert; 4507 TextToInsert += ' '; 4508 TextToInsert += NewTD->getIdentifier()->getName(); 4509 4510 Diag(FixitLoc, DiagID) 4511 << isa<TypeAliasDecl>(NewTD) 4512 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4513 if (NonCLike.Kind != NonCLikeKind::None) { 4514 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4515 << NonCLike.Kind - 1 << NonCLike.Range; 4516 } 4517 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4518 << NewTD << isa<TypeAliasDecl>(NewTD); 4519 4520 if (ChangesLinkage) 4521 return; 4522 } 4523 4524 // Otherwise, set this as the anon-decl typedef for the tag. 4525 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4526 } 4527 4528 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4529 switch (T) { 4530 case DeclSpec::TST_class: 4531 return 0; 4532 case DeclSpec::TST_struct: 4533 return 1; 4534 case DeclSpec::TST_interface: 4535 return 2; 4536 case DeclSpec::TST_union: 4537 return 3; 4538 case DeclSpec::TST_enum: 4539 return 4; 4540 default: 4541 llvm_unreachable("unexpected type specifier"); 4542 } 4543 } 4544 4545 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4546 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4547 /// parameters to cope with template friend declarations. 4548 Decl * 4549 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4550 MultiTemplateParamsArg TemplateParams, 4551 bool IsExplicitInstantiation, 4552 RecordDecl *&AnonRecord) { 4553 Decl *TagD = nullptr; 4554 TagDecl *Tag = nullptr; 4555 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4556 DS.getTypeSpecType() == DeclSpec::TST_struct || 4557 DS.getTypeSpecType() == DeclSpec::TST_interface || 4558 DS.getTypeSpecType() == DeclSpec::TST_union || 4559 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4560 TagD = DS.getRepAsDecl(); 4561 4562 if (!TagD) // We probably had an error 4563 return nullptr; 4564 4565 // Note that the above type specs guarantee that the 4566 // type rep is a Decl, whereas in many of the others 4567 // it's a Type. 4568 if (isa<TagDecl>(TagD)) 4569 Tag = cast<TagDecl>(TagD); 4570 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4571 Tag = CTD->getTemplatedDecl(); 4572 } 4573 4574 if (Tag) { 4575 handleTagNumbering(Tag, S); 4576 Tag->setFreeStanding(); 4577 if (Tag->isInvalidDecl()) 4578 return Tag; 4579 } 4580 4581 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4582 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4583 // or incomplete types shall not be restrict-qualified." 4584 if (TypeQuals & DeclSpec::TQ_restrict) 4585 Diag(DS.getRestrictSpecLoc(), 4586 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4587 << DS.getSourceRange(); 4588 } 4589 4590 if (DS.isInlineSpecified()) 4591 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4592 << getLangOpts().CPlusPlus17; 4593 4594 if (DS.hasConstexprSpecifier()) { 4595 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4596 // and definitions of functions and variables. 4597 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4598 // the declaration of a function or function template 4599 if (Tag) 4600 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4601 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4602 << static_cast<int>(DS.getConstexprSpecifier()); 4603 else 4604 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4605 << static_cast<int>(DS.getConstexprSpecifier()); 4606 // Don't emit warnings after this error. 4607 return TagD; 4608 } 4609 4610 DiagnoseFunctionSpecifiers(DS); 4611 4612 if (DS.isFriendSpecified()) { 4613 // If we're dealing with a decl but not a TagDecl, assume that 4614 // whatever routines created it handled the friendship aspect. 4615 if (TagD && !Tag) 4616 return nullptr; 4617 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4618 } 4619 4620 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4621 bool IsExplicitSpecialization = 4622 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4623 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4624 !IsExplicitInstantiation && !IsExplicitSpecialization && 4625 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4626 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4627 // nested-name-specifier unless it is an explicit instantiation 4628 // or an explicit specialization. 4629 // 4630 // FIXME: We allow class template partial specializations here too, per the 4631 // obvious intent of DR1819. 4632 // 4633 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4634 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4635 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4636 return nullptr; 4637 } 4638 4639 // Track whether this decl-specifier declares anything. 4640 bool DeclaresAnything = true; 4641 4642 // Handle anonymous struct definitions. 4643 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4644 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4645 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4646 if (getLangOpts().CPlusPlus || 4647 Record->getDeclContext()->isRecord()) { 4648 // If CurContext is a DeclContext that can contain statements, 4649 // RecursiveASTVisitor won't visit the decls that 4650 // BuildAnonymousStructOrUnion() will put into CurContext. 4651 // Also store them here so that they can be part of the 4652 // DeclStmt that gets created in this case. 4653 // FIXME: Also return the IndirectFieldDecls created by 4654 // BuildAnonymousStructOr union, for the same reason? 4655 if (CurContext->isFunctionOrMethod()) 4656 AnonRecord = Record; 4657 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4658 Context.getPrintingPolicy()); 4659 } 4660 4661 DeclaresAnything = false; 4662 } 4663 } 4664 4665 // C11 6.7.2.1p2: 4666 // A struct-declaration that does not declare an anonymous structure or 4667 // anonymous union shall contain a struct-declarator-list. 4668 // 4669 // This rule also existed in C89 and C99; the grammar for struct-declaration 4670 // did not permit a struct-declaration without a struct-declarator-list. 4671 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4672 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4673 // Check for Microsoft C extension: anonymous struct/union member. 4674 // Handle 2 kinds of anonymous struct/union: 4675 // struct STRUCT; 4676 // union UNION; 4677 // and 4678 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4679 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4680 if ((Tag && Tag->getDeclName()) || 4681 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4682 RecordDecl *Record = nullptr; 4683 if (Tag) 4684 Record = dyn_cast<RecordDecl>(Tag); 4685 else if (const RecordType *RT = 4686 DS.getRepAsType().get()->getAsStructureType()) 4687 Record = RT->getDecl(); 4688 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4689 Record = UT->getDecl(); 4690 4691 if (Record && getLangOpts().MicrosoftExt) { 4692 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4693 << Record->isUnion() << DS.getSourceRange(); 4694 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4695 } 4696 4697 DeclaresAnything = false; 4698 } 4699 } 4700 4701 // Skip all the checks below if we have a type error. 4702 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4703 (TagD && TagD->isInvalidDecl())) 4704 return TagD; 4705 4706 if (getLangOpts().CPlusPlus && 4707 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4708 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4709 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4710 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4711 DeclaresAnything = false; 4712 4713 if (!DS.isMissingDeclaratorOk()) { 4714 // Customize diagnostic for a typedef missing a name. 4715 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4716 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4717 << DS.getSourceRange(); 4718 else 4719 DeclaresAnything = false; 4720 } 4721 4722 if (DS.isModulePrivateSpecified() && 4723 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4724 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4725 << Tag->getTagKind() 4726 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4727 4728 ActOnDocumentableDecl(TagD); 4729 4730 // C 6.7/2: 4731 // A declaration [...] shall declare at least a declarator [...], a tag, 4732 // or the members of an enumeration. 4733 // C++ [dcl.dcl]p3: 4734 // [If there are no declarators], and except for the declaration of an 4735 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4736 // names into the program, or shall redeclare a name introduced by a 4737 // previous declaration. 4738 if (!DeclaresAnything) { 4739 // In C, we allow this as a (popular) extension / bug. Don't bother 4740 // producing further diagnostics for redundant qualifiers after this. 4741 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4742 ? diag::err_no_declarators 4743 : diag::ext_no_declarators) 4744 << DS.getSourceRange(); 4745 return TagD; 4746 } 4747 4748 // C++ [dcl.stc]p1: 4749 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4750 // init-declarator-list of the declaration shall not be empty. 4751 // C++ [dcl.fct.spec]p1: 4752 // If a cv-qualifier appears in a decl-specifier-seq, the 4753 // init-declarator-list of the declaration shall not be empty. 4754 // 4755 // Spurious qualifiers here appear to be valid in C. 4756 unsigned DiagID = diag::warn_standalone_specifier; 4757 if (getLangOpts().CPlusPlus) 4758 DiagID = diag::ext_standalone_specifier; 4759 4760 // Note that a linkage-specification sets a storage class, but 4761 // 'extern "C" struct foo;' is actually valid and not theoretically 4762 // useless. 4763 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4764 if (SCS == DeclSpec::SCS_mutable) 4765 // Since mutable is not a viable storage class specifier in C, there is 4766 // no reason to treat it as an extension. Instead, diagnose as an error. 4767 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4768 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4769 Diag(DS.getStorageClassSpecLoc(), DiagID) 4770 << DeclSpec::getSpecifierName(SCS); 4771 } 4772 4773 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4774 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4775 << DeclSpec::getSpecifierName(TSCS); 4776 if (DS.getTypeQualifiers()) { 4777 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4778 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4780 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4781 // Restrict is covered above. 4782 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4783 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4784 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4785 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4786 } 4787 4788 // Warn about ignored type attributes, for example: 4789 // __attribute__((aligned)) struct A; 4790 // Attributes should be placed after tag to apply to type declaration. 4791 if (!DS.getAttributes().empty()) { 4792 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4793 if (TypeSpecType == DeclSpec::TST_class || 4794 TypeSpecType == DeclSpec::TST_struct || 4795 TypeSpecType == DeclSpec::TST_interface || 4796 TypeSpecType == DeclSpec::TST_union || 4797 TypeSpecType == DeclSpec::TST_enum) { 4798 for (const ParsedAttr &AL : DS.getAttributes()) 4799 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4800 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4801 } 4802 } 4803 4804 return TagD; 4805 } 4806 4807 /// We are trying to inject an anonymous member into the given scope; 4808 /// check if there's an existing declaration that can't be overloaded. 4809 /// 4810 /// \return true if this is a forbidden redeclaration 4811 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4812 Scope *S, 4813 DeclContext *Owner, 4814 DeclarationName Name, 4815 SourceLocation NameLoc, 4816 bool IsUnion) { 4817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4818 Sema::ForVisibleRedeclaration); 4819 if (!SemaRef.LookupName(R, S)) return false; 4820 4821 // Pick a representative declaration. 4822 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4823 assert(PrevDecl && "Expected a non-null Decl"); 4824 4825 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4826 return false; 4827 4828 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4829 << IsUnion << Name; 4830 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4831 4832 return true; 4833 } 4834 4835 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4836 /// anonymous struct or union AnonRecord into the owning context Owner 4837 /// and scope S. This routine will be invoked just after we realize 4838 /// that an unnamed union or struct is actually an anonymous union or 4839 /// struct, e.g., 4840 /// 4841 /// @code 4842 /// union { 4843 /// int i; 4844 /// float f; 4845 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4846 /// // f into the surrounding scope.x 4847 /// @endcode 4848 /// 4849 /// This routine is recursive, injecting the names of nested anonymous 4850 /// structs/unions into the owning context and scope as well. 4851 static bool 4852 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4853 RecordDecl *AnonRecord, AccessSpecifier AS, 4854 SmallVectorImpl<NamedDecl *> &Chaining) { 4855 bool Invalid = false; 4856 4857 // Look every FieldDecl and IndirectFieldDecl with a name. 4858 for (auto *D : AnonRecord->decls()) { 4859 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4860 cast<NamedDecl>(D)->getDeclName()) { 4861 ValueDecl *VD = cast<ValueDecl>(D); 4862 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4863 VD->getLocation(), 4864 AnonRecord->isUnion())) { 4865 // C++ [class.union]p2: 4866 // The names of the members of an anonymous union shall be 4867 // distinct from the names of any other entity in the 4868 // scope in which the anonymous union is declared. 4869 Invalid = true; 4870 } else { 4871 // C++ [class.union]p2: 4872 // For the purpose of name lookup, after the anonymous union 4873 // definition, the members of the anonymous union are 4874 // considered to have been defined in the scope in which the 4875 // anonymous union is declared. 4876 unsigned OldChainingSize = Chaining.size(); 4877 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4878 Chaining.append(IF->chain_begin(), IF->chain_end()); 4879 else 4880 Chaining.push_back(VD); 4881 4882 assert(Chaining.size() >= 2); 4883 NamedDecl **NamedChain = 4884 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4885 for (unsigned i = 0; i < Chaining.size(); i++) 4886 NamedChain[i] = Chaining[i]; 4887 4888 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4889 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4890 VD->getType(), {NamedChain, Chaining.size()}); 4891 4892 for (const auto *Attr : VD->attrs()) 4893 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4894 4895 IndirectField->setAccess(AS); 4896 IndirectField->setImplicit(); 4897 SemaRef.PushOnScopeChains(IndirectField, S); 4898 4899 // That includes picking up the appropriate access specifier. 4900 if (AS != AS_none) IndirectField->setAccess(AS); 4901 4902 Chaining.resize(OldChainingSize); 4903 } 4904 } 4905 } 4906 4907 return Invalid; 4908 } 4909 4910 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4911 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4912 /// illegal input values are mapped to SC_None. 4913 static StorageClass 4914 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4915 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4916 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4917 "Parser allowed 'typedef' as storage class VarDecl."); 4918 switch (StorageClassSpec) { 4919 case DeclSpec::SCS_unspecified: return SC_None; 4920 case DeclSpec::SCS_extern: 4921 if (DS.isExternInLinkageSpec()) 4922 return SC_None; 4923 return SC_Extern; 4924 case DeclSpec::SCS_static: return SC_Static; 4925 case DeclSpec::SCS_auto: return SC_Auto; 4926 case DeclSpec::SCS_register: return SC_Register; 4927 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4928 // Illegal SCSs map to None: error reporting is up to the caller. 4929 case DeclSpec::SCS_mutable: // Fall through. 4930 case DeclSpec::SCS_typedef: return SC_None; 4931 } 4932 llvm_unreachable("unknown storage class specifier"); 4933 } 4934 4935 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4936 assert(Record->hasInClassInitializer()); 4937 4938 for (const auto *I : Record->decls()) { 4939 const auto *FD = dyn_cast<FieldDecl>(I); 4940 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4941 FD = IFD->getAnonField(); 4942 if (FD && FD->hasInClassInitializer()) 4943 return FD->getLocation(); 4944 } 4945 4946 llvm_unreachable("couldn't find in-class initializer"); 4947 } 4948 4949 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4950 SourceLocation DefaultInitLoc) { 4951 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4952 return; 4953 4954 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4955 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4956 } 4957 4958 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4959 CXXRecordDecl *AnonUnion) { 4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4961 return; 4962 4963 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4964 } 4965 4966 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4967 /// anonymous structure or union. Anonymous unions are a C++ feature 4968 /// (C++ [class.union]) and a C11 feature; anonymous structures 4969 /// are a C11 feature and GNU C++ extension. 4970 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4971 AccessSpecifier AS, 4972 RecordDecl *Record, 4973 const PrintingPolicy &Policy) { 4974 DeclContext *Owner = Record->getDeclContext(); 4975 4976 // Diagnose whether this anonymous struct/union is an extension. 4977 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4978 Diag(Record->getLocation(), diag::ext_anonymous_union); 4979 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4980 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4981 else if (!Record->isUnion() && !getLangOpts().C11) 4982 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4983 4984 // C and C++ require different kinds of checks for anonymous 4985 // structs/unions. 4986 bool Invalid = false; 4987 if (getLangOpts().CPlusPlus) { 4988 const char *PrevSpec = nullptr; 4989 if (Record->isUnion()) { 4990 // C++ [class.union]p6: 4991 // C++17 [class.union.anon]p2: 4992 // Anonymous unions declared in a named namespace or in the 4993 // global namespace shall be declared static. 4994 unsigned DiagID; 4995 DeclContext *OwnerScope = Owner->getRedeclContext(); 4996 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4997 (OwnerScope->isTranslationUnit() || 4998 (OwnerScope->isNamespace() && 4999 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5000 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5001 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5002 5003 // Recover by adding 'static'. 5004 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5005 PrevSpec, DiagID, Policy); 5006 } 5007 // C++ [class.union]p6: 5008 // A storage class is not allowed in a declaration of an 5009 // anonymous union in a class scope. 5010 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5011 isa<RecordDecl>(Owner)) { 5012 Diag(DS.getStorageClassSpecLoc(), 5013 diag::err_anonymous_union_with_storage_spec) 5014 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5015 5016 // Recover by removing the storage specifier. 5017 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5018 SourceLocation(), 5019 PrevSpec, DiagID, Context.getPrintingPolicy()); 5020 } 5021 } 5022 5023 // Ignore const/volatile/restrict qualifiers. 5024 if (DS.getTypeQualifiers()) { 5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5026 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5027 << Record->isUnion() << "const" 5028 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5029 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5030 Diag(DS.getVolatileSpecLoc(), 5031 diag::ext_anonymous_struct_union_qualified) 5032 << Record->isUnion() << "volatile" 5033 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5035 Diag(DS.getRestrictSpecLoc(), 5036 diag::ext_anonymous_struct_union_qualified) 5037 << Record->isUnion() << "restrict" 5038 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5040 Diag(DS.getAtomicSpecLoc(), 5041 diag::ext_anonymous_struct_union_qualified) 5042 << Record->isUnion() << "_Atomic" 5043 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5044 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5045 Diag(DS.getUnalignedSpecLoc(), 5046 diag::ext_anonymous_struct_union_qualified) 5047 << Record->isUnion() << "__unaligned" 5048 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5049 5050 DS.ClearTypeQualifiers(); 5051 } 5052 5053 // C++ [class.union]p2: 5054 // The member-specification of an anonymous union shall only 5055 // define non-static data members. [Note: nested types and 5056 // functions cannot be declared within an anonymous union. ] 5057 for (auto *Mem : Record->decls()) { 5058 // Ignore invalid declarations; we already diagnosed them. 5059 if (Mem->isInvalidDecl()) 5060 continue; 5061 5062 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5063 // C++ [class.union]p3: 5064 // An anonymous union shall not have private or protected 5065 // members (clause 11). 5066 assert(FD->getAccess() != AS_none); 5067 if (FD->getAccess() != AS_public) { 5068 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5069 << Record->isUnion() << (FD->getAccess() == AS_protected); 5070 Invalid = true; 5071 } 5072 5073 // C++ [class.union]p1 5074 // An object of a class with a non-trivial constructor, a non-trivial 5075 // copy constructor, a non-trivial destructor, or a non-trivial copy 5076 // assignment operator cannot be a member of a union, nor can an 5077 // array of such objects. 5078 if (CheckNontrivialField(FD)) 5079 Invalid = true; 5080 } else if (Mem->isImplicit()) { 5081 // Any implicit members are fine. 5082 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5083 // This is a type that showed up in an 5084 // elaborated-type-specifier inside the anonymous struct or 5085 // union, but which actually declares a type outside of the 5086 // anonymous struct or union. It's okay. 5087 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5088 if (!MemRecord->isAnonymousStructOrUnion() && 5089 MemRecord->getDeclName()) { 5090 // Visual C++ allows type definition in anonymous struct or union. 5091 if (getLangOpts().MicrosoftExt) 5092 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5093 << Record->isUnion(); 5094 else { 5095 // This is a nested type declaration. 5096 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5097 << Record->isUnion(); 5098 Invalid = true; 5099 } 5100 } else { 5101 // This is an anonymous type definition within another anonymous type. 5102 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5103 // not part of standard C++. 5104 Diag(MemRecord->getLocation(), 5105 diag::ext_anonymous_record_with_anonymous_type) 5106 << Record->isUnion(); 5107 } 5108 } else if (isa<AccessSpecDecl>(Mem)) { 5109 // Any access specifier is fine. 5110 } else if (isa<StaticAssertDecl>(Mem)) { 5111 // In C++1z, static_assert declarations are also fine. 5112 } else { 5113 // We have something that isn't a non-static data 5114 // member. Complain about it. 5115 unsigned DK = diag::err_anonymous_record_bad_member; 5116 if (isa<TypeDecl>(Mem)) 5117 DK = diag::err_anonymous_record_with_type; 5118 else if (isa<FunctionDecl>(Mem)) 5119 DK = diag::err_anonymous_record_with_function; 5120 else if (isa<VarDecl>(Mem)) 5121 DK = diag::err_anonymous_record_with_static; 5122 5123 // Visual C++ allows type definition in anonymous struct or union. 5124 if (getLangOpts().MicrosoftExt && 5125 DK == diag::err_anonymous_record_with_type) 5126 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5127 << Record->isUnion(); 5128 else { 5129 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5130 Invalid = true; 5131 } 5132 } 5133 } 5134 5135 // C++11 [class.union]p8 (DR1460): 5136 // At most one variant member of a union may have a 5137 // brace-or-equal-initializer. 5138 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5139 Owner->isRecord()) 5140 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5141 cast<CXXRecordDecl>(Record)); 5142 } 5143 5144 if (!Record->isUnion() && !Owner->isRecord()) { 5145 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5146 << getLangOpts().CPlusPlus; 5147 Invalid = true; 5148 } 5149 5150 // C++ [dcl.dcl]p3: 5151 // [If there are no declarators], and except for the declaration of an 5152 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5153 // names into the program 5154 // C++ [class.mem]p2: 5155 // each such member-declaration shall either declare at least one member 5156 // name of the class or declare at least one unnamed bit-field 5157 // 5158 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5159 if (getLangOpts().CPlusPlus && Record->field_empty()) 5160 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5161 5162 // Mock up a declarator. 5163 Declarator Dc(DS, DeclaratorContext::Member); 5164 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5165 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5166 5167 // Create a declaration for this anonymous struct/union. 5168 NamedDecl *Anon = nullptr; 5169 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5170 Anon = FieldDecl::Create( 5171 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5172 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5173 /*BitWidth=*/nullptr, /*Mutable=*/false, 5174 /*InitStyle=*/ICIS_NoInit); 5175 Anon->setAccess(AS); 5176 ProcessDeclAttributes(S, Anon, Dc); 5177 5178 if (getLangOpts().CPlusPlus) 5179 FieldCollector->Add(cast<FieldDecl>(Anon)); 5180 } else { 5181 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5182 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5183 if (SCSpec == DeclSpec::SCS_mutable) { 5184 // mutable can only appear on non-static class members, so it's always 5185 // an error here 5186 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5187 Invalid = true; 5188 SC = SC_None; 5189 } 5190 5191 assert(DS.getAttributes().empty() && "No attribute expected"); 5192 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5193 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5194 Context.getTypeDeclType(Record), TInfo, SC); 5195 5196 // Default-initialize the implicit variable. This initialization will be 5197 // trivial in almost all cases, except if a union member has an in-class 5198 // initializer: 5199 // union { int n = 0; }; 5200 ActOnUninitializedDecl(Anon); 5201 } 5202 Anon->setImplicit(); 5203 5204 // Mark this as an anonymous struct/union type. 5205 Record->setAnonymousStructOrUnion(true); 5206 5207 // Add the anonymous struct/union object to the current 5208 // context. We'll be referencing this object when we refer to one of 5209 // its members. 5210 Owner->addDecl(Anon); 5211 5212 // Inject the members of the anonymous struct/union into the owning 5213 // context and into the identifier resolver chain for name lookup 5214 // purposes. 5215 SmallVector<NamedDecl*, 2> Chain; 5216 Chain.push_back(Anon); 5217 5218 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5219 Invalid = true; 5220 5221 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5222 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5223 MangleNumberingContext *MCtx; 5224 Decl *ManglingContextDecl; 5225 std::tie(MCtx, ManglingContextDecl) = 5226 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5227 if (MCtx) { 5228 Context.setManglingNumber( 5229 NewVD, MCtx->getManglingNumber( 5230 NewVD, getMSManglingNumber(getLangOpts(), S))); 5231 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5232 } 5233 } 5234 } 5235 5236 if (Invalid) 5237 Anon->setInvalidDecl(); 5238 5239 return Anon; 5240 } 5241 5242 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5243 /// Microsoft C anonymous structure. 5244 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5245 /// Example: 5246 /// 5247 /// struct A { int a; }; 5248 /// struct B { struct A; int b; }; 5249 /// 5250 /// void foo() { 5251 /// B var; 5252 /// var.a = 3; 5253 /// } 5254 /// 5255 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5256 RecordDecl *Record) { 5257 assert(Record && "expected a record!"); 5258 5259 // Mock up a declarator. 5260 Declarator Dc(DS, DeclaratorContext::TypeName); 5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5262 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5263 5264 auto *ParentDecl = cast<RecordDecl>(CurContext); 5265 QualType RecTy = Context.getTypeDeclType(Record); 5266 5267 // Create a declaration for this anonymous struct. 5268 NamedDecl *Anon = 5269 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5270 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5271 /*BitWidth=*/nullptr, /*Mutable=*/false, 5272 /*InitStyle=*/ICIS_NoInit); 5273 Anon->setImplicit(); 5274 5275 // Add the anonymous struct object to the current context. 5276 CurContext->addDecl(Anon); 5277 5278 // Inject the members of the anonymous struct into the current 5279 // context and into the identifier resolver chain for name lookup 5280 // purposes. 5281 SmallVector<NamedDecl*, 2> Chain; 5282 Chain.push_back(Anon); 5283 5284 RecordDecl *RecordDef = Record->getDefinition(); 5285 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5286 diag::err_field_incomplete_or_sizeless) || 5287 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5288 AS_none, Chain)) { 5289 Anon->setInvalidDecl(); 5290 ParentDecl->setInvalidDecl(); 5291 } 5292 5293 return Anon; 5294 } 5295 5296 /// GetNameForDeclarator - Determine the full declaration name for the 5297 /// given Declarator. 5298 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5299 return GetNameFromUnqualifiedId(D.getName()); 5300 } 5301 5302 /// Retrieves the declaration name from a parsed unqualified-id. 5303 DeclarationNameInfo 5304 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5305 DeclarationNameInfo NameInfo; 5306 NameInfo.setLoc(Name.StartLocation); 5307 5308 switch (Name.getKind()) { 5309 5310 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5311 case UnqualifiedIdKind::IK_Identifier: 5312 NameInfo.setName(Name.Identifier); 5313 return NameInfo; 5314 5315 case UnqualifiedIdKind::IK_DeductionGuideName: { 5316 // C++ [temp.deduct.guide]p3: 5317 // The simple-template-id shall name a class template specialization. 5318 // The template-name shall be the same identifier as the template-name 5319 // of the simple-template-id. 5320 // These together intend to imply that the template-name shall name a 5321 // class template. 5322 // FIXME: template<typename T> struct X {}; 5323 // template<typename T> using Y = X<T>; 5324 // Y(int) -> Y<int>; 5325 // satisfies these rules but does not name a class template. 5326 TemplateName TN = Name.TemplateName.get().get(); 5327 auto *Template = TN.getAsTemplateDecl(); 5328 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5329 Diag(Name.StartLocation, 5330 diag::err_deduction_guide_name_not_class_template) 5331 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5332 if (Template) 5333 Diag(Template->getLocation(), diag::note_template_decl_here); 5334 return DeclarationNameInfo(); 5335 } 5336 5337 NameInfo.setName( 5338 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5339 return NameInfo; 5340 } 5341 5342 case UnqualifiedIdKind::IK_OperatorFunctionId: 5343 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5344 Name.OperatorFunctionId.Operator)); 5345 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5346 = Name.OperatorFunctionId.SymbolLocations[0]; 5347 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5348 = Name.EndLocation.getRawEncoding(); 5349 return NameInfo; 5350 5351 case UnqualifiedIdKind::IK_LiteralOperatorId: 5352 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5353 Name.Identifier)); 5354 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5355 return NameInfo; 5356 5357 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5358 TypeSourceInfo *TInfo; 5359 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5360 if (Ty.isNull()) 5361 return DeclarationNameInfo(); 5362 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5363 Context.getCanonicalType(Ty))); 5364 NameInfo.setNamedTypeInfo(TInfo); 5365 return NameInfo; 5366 } 5367 5368 case UnqualifiedIdKind::IK_ConstructorName: { 5369 TypeSourceInfo *TInfo; 5370 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5371 if (Ty.isNull()) 5372 return DeclarationNameInfo(); 5373 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5374 Context.getCanonicalType(Ty))); 5375 NameInfo.setNamedTypeInfo(TInfo); 5376 return NameInfo; 5377 } 5378 5379 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5380 // In well-formed code, we can only have a constructor 5381 // template-id that refers to the current context, so go there 5382 // to find the actual type being constructed. 5383 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5384 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5385 return DeclarationNameInfo(); 5386 5387 // Determine the type of the class being constructed. 5388 QualType CurClassType = Context.getTypeDeclType(CurClass); 5389 5390 // FIXME: Check two things: that the template-id names the same type as 5391 // CurClassType, and that the template-id does not occur when the name 5392 // was qualified. 5393 5394 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5395 Context.getCanonicalType(CurClassType))); 5396 // FIXME: should we retrieve TypeSourceInfo? 5397 NameInfo.setNamedTypeInfo(nullptr); 5398 return NameInfo; 5399 } 5400 5401 case UnqualifiedIdKind::IK_DestructorName: { 5402 TypeSourceInfo *TInfo; 5403 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5404 if (Ty.isNull()) 5405 return DeclarationNameInfo(); 5406 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5407 Context.getCanonicalType(Ty))); 5408 NameInfo.setNamedTypeInfo(TInfo); 5409 return NameInfo; 5410 } 5411 5412 case UnqualifiedIdKind::IK_TemplateId: { 5413 TemplateName TName = Name.TemplateId->Template.get(); 5414 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5415 return Context.getNameForTemplate(TName, TNameLoc); 5416 } 5417 5418 } // switch (Name.getKind()) 5419 5420 llvm_unreachable("Unknown name kind"); 5421 } 5422 5423 static QualType getCoreType(QualType Ty) { 5424 do { 5425 if (Ty->isPointerType() || Ty->isReferenceType()) 5426 Ty = Ty->getPointeeType(); 5427 else if (Ty->isArrayType()) 5428 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5429 else 5430 return Ty.withoutLocalFastQualifiers(); 5431 } while (true); 5432 } 5433 5434 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5435 /// and Definition have "nearly" matching parameters. This heuristic is 5436 /// used to improve diagnostics in the case where an out-of-line function 5437 /// definition doesn't match any declaration within the class or namespace. 5438 /// Also sets Params to the list of indices to the parameters that differ 5439 /// between the declaration and the definition. If hasSimilarParameters 5440 /// returns true and Params is empty, then all of the parameters match. 5441 static bool hasSimilarParameters(ASTContext &Context, 5442 FunctionDecl *Declaration, 5443 FunctionDecl *Definition, 5444 SmallVectorImpl<unsigned> &Params) { 5445 Params.clear(); 5446 if (Declaration->param_size() != Definition->param_size()) 5447 return false; 5448 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5449 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5450 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5451 5452 // The parameter types are identical 5453 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5454 continue; 5455 5456 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5457 QualType DefParamBaseTy = getCoreType(DefParamTy); 5458 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5459 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5460 5461 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5462 (DeclTyName && DeclTyName == DefTyName)) 5463 Params.push_back(Idx); 5464 else // The two parameters aren't even close 5465 return false; 5466 } 5467 5468 return true; 5469 } 5470 5471 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5472 /// declarator needs to be rebuilt in the current instantiation. 5473 /// Any bits of declarator which appear before the name are valid for 5474 /// consideration here. That's specifically the type in the decl spec 5475 /// and the base type in any member-pointer chunks. 5476 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5477 DeclarationName Name) { 5478 // The types we specifically need to rebuild are: 5479 // - typenames, typeofs, and decltypes 5480 // - types which will become injected class names 5481 // Of course, we also need to rebuild any type referencing such a 5482 // type. It's safest to just say "dependent", but we call out a 5483 // few cases here. 5484 5485 DeclSpec &DS = D.getMutableDeclSpec(); 5486 switch (DS.getTypeSpecType()) { 5487 case DeclSpec::TST_typename: 5488 case DeclSpec::TST_typeofType: 5489 case DeclSpec::TST_underlyingType: 5490 case DeclSpec::TST_atomic: { 5491 // Grab the type from the parser. 5492 TypeSourceInfo *TSI = nullptr; 5493 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5494 if (T.isNull() || !T->isInstantiationDependentType()) break; 5495 5496 // Make sure there's a type source info. This isn't really much 5497 // of a waste; most dependent types should have type source info 5498 // attached already. 5499 if (!TSI) 5500 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5501 5502 // Rebuild the type in the current instantiation. 5503 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5504 if (!TSI) return true; 5505 5506 // Store the new type back in the decl spec. 5507 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5508 DS.UpdateTypeRep(LocType); 5509 break; 5510 } 5511 5512 case DeclSpec::TST_decltype: 5513 case DeclSpec::TST_typeofExpr: { 5514 Expr *E = DS.getRepAsExpr(); 5515 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5516 if (Result.isInvalid()) return true; 5517 DS.UpdateExprRep(Result.get()); 5518 break; 5519 } 5520 5521 default: 5522 // Nothing to do for these decl specs. 5523 break; 5524 } 5525 5526 // It doesn't matter what order we do this in. 5527 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5528 DeclaratorChunk &Chunk = D.getTypeObject(I); 5529 5530 // The only type information in the declarator which can come 5531 // before the declaration name is the base type of a member 5532 // pointer. 5533 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5534 continue; 5535 5536 // Rebuild the scope specifier in-place. 5537 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5538 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5539 return true; 5540 } 5541 5542 return false; 5543 } 5544 5545 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5546 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5547 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5548 5549 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5550 Dcl && Dcl->getDeclContext()->isFileContext()) 5551 Dcl->setTopLevelDeclInObjCContainer(); 5552 5553 if (getLangOpts().OpenCL) 5554 setCurrentOpenCLExtensionForDecl(Dcl); 5555 5556 return Dcl; 5557 } 5558 5559 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5560 /// If T is the name of a class, then each of the following shall have a 5561 /// name different from T: 5562 /// - every static data member of class T; 5563 /// - every member function of class T 5564 /// - every member of class T that is itself a type; 5565 /// \returns true if the declaration name violates these rules. 5566 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5567 DeclarationNameInfo NameInfo) { 5568 DeclarationName Name = NameInfo.getName(); 5569 5570 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5571 while (Record && Record->isAnonymousStructOrUnion()) 5572 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5573 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5574 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5575 return true; 5576 } 5577 5578 return false; 5579 } 5580 5581 /// Diagnose a declaration whose declarator-id has the given 5582 /// nested-name-specifier. 5583 /// 5584 /// \param SS The nested-name-specifier of the declarator-id. 5585 /// 5586 /// \param DC The declaration context to which the nested-name-specifier 5587 /// resolves. 5588 /// 5589 /// \param Name The name of the entity being declared. 5590 /// 5591 /// \param Loc The location of the name of the entity being declared. 5592 /// 5593 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5594 /// we're declaring an explicit / partial specialization / instantiation. 5595 /// 5596 /// \returns true if we cannot safely recover from this error, false otherwise. 5597 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5598 DeclarationName Name, 5599 SourceLocation Loc, bool IsTemplateId) { 5600 DeclContext *Cur = CurContext; 5601 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5602 Cur = Cur->getParent(); 5603 5604 // If the user provided a superfluous scope specifier that refers back to the 5605 // class in which the entity is already declared, diagnose and ignore it. 5606 // 5607 // class X { 5608 // void X::f(); 5609 // }; 5610 // 5611 // Note, it was once ill-formed to give redundant qualification in all 5612 // contexts, but that rule was removed by DR482. 5613 if (Cur->Equals(DC)) { 5614 if (Cur->isRecord()) { 5615 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5616 : diag::err_member_extra_qualification) 5617 << Name << FixItHint::CreateRemoval(SS.getRange()); 5618 SS.clear(); 5619 } else { 5620 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5621 } 5622 return false; 5623 } 5624 5625 // Check whether the qualifying scope encloses the scope of the original 5626 // declaration. For a template-id, we perform the checks in 5627 // CheckTemplateSpecializationScope. 5628 if (!Cur->Encloses(DC) && !IsTemplateId) { 5629 if (Cur->isRecord()) 5630 Diag(Loc, diag::err_member_qualification) 5631 << Name << SS.getRange(); 5632 else if (isa<TranslationUnitDecl>(DC)) 5633 Diag(Loc, diag::err_invalid_declarator_global_scope) 5634 << Name << SS.getRange(); 5635 else if (isa<FunctionDecl>(Cur)) 5636 Diag(Loc, diag::err_invalid_declarator_in_function) 5637 << Name << SS.getRange(); 5638 else if (isa<BlockDecl>(Cur)) 5639 Diag(Loc, diag::err_invalid_declarator_in_block) 5640 << Name << SS.getRange(); 5641 else 5642 Diag(Loc, diag::err_invalid_declarator_scope) 5643 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5644 5645 return true; 5646 } 5647 5648 if (Cur->isRecord()) { 5649 // Cannot qualify members within a class. 5650 Diag(Loc, diag::err_member_qualification) 5651 << Name << SS.getRange(); 5652 SS.clear(); 5653 5654 // C++ constructors and destructors with incorrect scopes can break 5655 // our AST invariants by having the wrong underlying types. If 5656 // that's the case, then drop this declaration entirely. 5657 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5658 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5659 !Context.hasSameType(Name.getCXXNameType(), 5660 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5661 return true; 5662 5663 return false; 5664 } 5665 5666 // C++11 [dcl.meaning]p1: 5667 // [...] "The nested-name-specifier of the qualified declarator-id shall 5668 // not begin with a decltype-specifer" 5669 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5670 while (SpecLoc.getPrefix()) 5671 SpecLoc = SpecLoc.getPrefix(); 5672 if (dyn_cast_or_null<DecltypeType>( 5673 SpecLoc.getNestedNameSpecifier()->getAsType())) 5674 Diag(Loc, diag::err_decltype_in_declarator) 5675 << SpecLoc.getTypeLoc().getSourceRange(); 5676 5677 return false; 5678 } 5679 5680 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5681 MultiTemplateParamsArg TemplateParamLists) { 5682 // TODO: consider using NameInfo for diagnostic. 5683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5684 DeclarationName Name = NameInfo.getName(); 5685 5686 // All of these full declarators require an identifier. If it doesn't have 5687 // one, the ParsedFreeStandingDeclSpec action should be used. 5688 if (D.isDecompositionDeclarator()) { 5689 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5690 } else if (!Name) { 5691 if (!D.isInvalidType()) // Reject this if we think it is valid. 5692 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5693 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5694 return nullptr; 5695 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5696 return nullptr; 5697 5698 // The scope passed in may not be a decl scope. Zip up the scope tree until 5699 // we find one that is. 5700 while ((S->getFlags() & Scope::DeclScope) == 0 || 5701 (S->getFlags() & Scope::TemplateParamScope) != 0) 5702 S = S->getParent(); 5703 5704 DeclContext *DC = CurContext; 5705 if (D.getCXXScopeSpec().isInvalid()) 5706 D.setInvalidType(); 5707 else if (D.getCXXScopeSpec().isSet()) { 5708 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5709 UPPC_DeclarationQualifier)) 5710 return nullptr; 5711 5712 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5713 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5714 if (!DC || isa<EnumDecl>(DC)) { 5715 // If we could not compute the declaration context, it's because the 5716 // declaration context is dependent but does not refer to a class, 5717 // class template, or class template partial specialization. Complain 5718 // and return early, to avoid the coming semantic disaster. 5719 Diag(D.getIdentifierLoc(), 5720 diag::err_template_qualified_declarator_no_match) 5721 << D.getCXXScopeSpec().getScopeRep() 5722 << D.getCXXScopeSpec().getRange(); 5723 return nullptr; 5724 } 5725 bool IsDependentContext = DC->isDependentContext(); 5726 5727 if (!IsDependentContext && 5728 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5729 return nullptr; 5730 5731 // If a class is incomplete, do not parse entities inside it. 5732 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5733 Diag(D.getIdentifierLoc(), 5734 diag::err_member_def_undefined_record) 5735 << Name << DC << D.getCXXScopeSpec().getRange(); 5736 return nullptr; 5737 } 5738 if (!D.getDeclSpec().isFriendSpecified()) { 5739 if (diagnoseQualifiedDeclaration( 5740 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5741 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5742 if (DC->isRecord()) 5743 return nullptr; 5744 5745 D.setInvalidType(); 5746 } 5747 } 5748 5749 // Check whether we need to rebuild the type of the given 5750 // declaration in the current instantiation. 5751 if (EnteringContext && IsDependentContext && 5752 TemplateParamLists.size() != 0) { 5753 ContextRAII SavedContext(*this, DC); 5754 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5755 D.setInvalidType(); 5756 } 5757 } 5758 5759 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5760 QualType R = TInfo->getType(); 5761 5762 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5763 UPPC_DeclarationType)) 5764 D.setInvalidType(); 5765 5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5767 forRedeclarationInCurContext()); 5768 5769 // See if this is a redefinition of a variable in the same scope. 5770 if (!D.getCXXScopeSpec().isSet()) { 5771 bool IsLinkageLookup = false; 5772 bool CreateBuiltins = false; 5773 5774 // If the declaration we're planning to build will be a function 5775 // or object with linkage, then look for another declaration with 5776 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5777 // 5778 // If the declaration we're planning to build will be declared with 5779 // external linkage in the translation unit, create any builtin with 5780 // the same name. 5781 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5782 /* Do nothing*/; 5783 else if (CurContext->isFunctionOrMethod() && 5784 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5785 R->isFunctionType())) { 5786 IsLinkageLookup = true; 5787 CreateBuiltins = 5788 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5789 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5790 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5791 CreateBuiltins = true; 5792 5793 if (IsLinkageLookup) { 5794 Previous.clear(LookupRedeclarationWithLinkage); 5795 Previous.setRedeclarationKind(ForExternalRedeclaration); 5796 } 5797 5798 LookupName(Previous, S, CreateBuiltins); 5799 } else { // Something like "int foo::x;" 5800 LookupQualifiedName(Previous, DC); 5801 5802 // C++ [dcl.meaning]p1: 5803 // When the declarator-id is qualified, the declaration shall refer to a 5804 // previously declared member of the class or namespace to which the 5805 // qualifier refers (or, in the case of a namespace, of an element of the 5806 // inline namespace set of that namespace (7.3.1)) or to a specialization 5807 // thereof; [...] 5808 // 5809 // Note that we already checked the context above, and that we do not have 5810 // enough information to make sure that Previous contains the declaration 5811 // we want to match. For example, given: 5812 // 5813 // class X { 5814 // void f(); 5815 // void f(float); 5816 // }; 5817 // 5818 // void X::f(int) { } // ill-formed 5819 // 5820 // In this case, Previous will point to the overload set 5821 // containing the two f's declared in X, but neither of them 5822 // matches. 5823 5824 // C++ [dcl.meaning]p1: 5825 // [...] the member shall not merely have been introduced by a 5826 // using-declaration in the scope of the class or namespace nominated by 5827 // the nested-name-specifier of the declarator-id. 5828 RemoveUsingDecls(Previous); 5829 } 5830 5831 if (Previous.isSingleResult() && 5832 Previous.getFoundDecl()->isTemplateParameter()) { 5833 // Maybe we will complain about the shadowed template parameter. 5834 if (!D.isInvalidType()) 5835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5836 Previous.getFoundDecl()); 5837 5838 // Just pretend that we didn't see the previous declaration. 5839 Previous.clear(); 5840 } 5841 5842 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5843 // Forget that the previous declaration is the injected-class-name. 5844 Previous.clear(); 5845 5846 // In C++, the previous declaration we find might be a tag type 5847 // (class or enum). In this case, the new declaration will hide the 5848 // tag type. Note that this applies to functions, function templates, and 5849 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5850 if (Previous.isSingleTagDecl() && 5851 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5852 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5853 Previous.clear(); 5854 5855 // Check that there are no default arguments other than in the parameters 5856 // of a function declaration (C++ only). 5857 if (getLangOpts().CPlusPlus) 5858 CheckExtraCXXDefaultArguments(D); 5859 5860 NamedDecl *New; 5861 5862 bool AddToScope = true; 5863 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5864 if (TemplateParamLists.size()) { 5865 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5866 return nullptr; 5867 } 5868 5869 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5870 } else if (R->isFunctionType()) { 5871 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5872 TemplateParamLists, 5873 AddToScope); 5874 } else { 5875 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5876 AddToScope); 5877 } 5878 5879 if (!New) 5880 return nullptr; 5881 5882 // If this has an identifier and is not a function template specialization, 5883 // add it to the scope stack. 5884 if (New->getDeclName() && AddToScope) 5885 PushOnScopeChains(New, S); 5886 5887 if (isInOpenMPDeclareTargetContext()) 5888 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5889 5890 return New; 5891 } 5892 5893 /// Helper method to turn variable array types into constant array 5894 /// types in certain situations which would otherwise be errors (for 5895 /// GCC compatibility). 5896 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5897 ASTContext &Context, 5898 bool &SizeIsNegative, 5899 llvm::APSInt &Oversized) { 5900 // This method tries to turn a variable array into a constant 5901 // array even when the size isn't an ICE. This is necessary 5902 // for compatibility with code that depends on gcc's buggy 5903 // constant expression folding, like struct {char x[(int)(char*)2];} 5904 SizeIsNegative = false; 5905 Oversized = 0; 5906 5907 if (T->isDependentType()) 5908 return QualType(); 5909 5910 QualifierCollector Qs; 5911 const Type *Ty = Qs.strip(T); 5912 5913 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5914 QualType Pointee = PTy->getPointeeType(); 5915 QualType FixedType = 5916 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5917 Oversized); 5918 if (FixedType.isNull()) return FixedType; 5919 FixedType = Context.getPointerType(FixedType); 5920 return Qs.apply(Context, FixedType); 5921 } 5922 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5923 QualType Inner = PTy->getInnerType(); 5924 QualType FixedType = 5925 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5926 Oversized); 5927 if (FixedType.isNull()) return FixedType; 5928 FixedType = Context.getParenType(FixedType); 5929 return Qs.apply(Context, FixedType); 5930 } 5931 5932 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5933 if (!VLATy) 5934 return QualType(); 5935 5936 QualType ElemTy = VLATy->getElementType(); 5937 if (ElemTy->isVariablyModifiedType()) { 5938 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5939 SizeIsNegative, Oversized); 5940 if (ElemTy.isNull()) 5941 return QualType(); 5942 } 5943 5944 Expr::EvalResult Result; 5945 if (!VLATy->getSizeExpr() || 5946 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5947 return QualType(); 5948 5949 llvm::APSInt Res = Result.Val.getInt(); 5950 5951 // Check whether the array size is negative. 5952 if (Res.isSigned() && Res.isNegative()) { 5953 SizeIsNegative = true; 5954 return QualType(); 5955 } 5956 5957 // Check whether the array is too large to be addressed. 5958 unsigned ActiveSizeBits = 5959 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5960 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5961 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5962 : Res.getActiveBits(); 5963 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5964 Oversized = Res; 5965 return QualType(); 5966 } 5967 5968 QualType FoldedArrayType = Context.getConstantArrayType( 5969 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5970 return Qs.apply(Context, FoldedArrayType); 5971 } 5972 5973 static void 5974 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5975 SrcTL = SrcTL.getUnqualifiedLoc(); 5976 DstTL = DstTL.getUnqualifiedLoc(); 5977 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5978 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5979 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5980 DstPTL.getPointeeLoc()); 5981 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5982 return; 5983 } 5984 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5985 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5986 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5987 DstPTL.getInnerLoc()); 5988 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5989 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5990 return; 5991 } 5992 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5993 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5994 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5995 TypeLoc DstElemTL = DstATL.getElementLoc(); 5996 if (VariableArrayTypeLoc SrcElemATL = 5997 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 5998 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 5999 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6000 } else { 6001 DstElemTL.initializeFullCopy(SrcElemTL); 6002 } 6003 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6004 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6005 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6006 } 6007 6008 /// Helper method to turn variable array types into constant array 6009 /// types in certain situations which would otherwise be errors (for 6010 /// GCC compatibility). 6011 static TypeSourceInfo* 6012 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6013 ASTContext &Context, 6014 bool &SizeIsNegative, 6015 llvm::APSInt &Oversized) { 6016 QualType FixedTy 6017 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6018 SizeIsNegative, Oversized); 6019 if (FixedTy.isNull()) 6020 return nullptr; 6021 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6022 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6023 FixedTInfo->getTypeLoc()); 6024 return FixedTInfo; 6025 } 6026 6027 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6028 /// true if we were successful. 6029 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6030 QualType &T, SourceLocation Loc, 6031 unsigned FailedFoldDiagID) { 6032 bool SizeIsNegative; 6033 llvm::APSInt Oversized; 6034 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6035 TInfo, S.Context, SizeIsNegative, Oversized); 6036 if (FixedTInfo) { 6037 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6038 TInfo = FixedTInfo; 6039 T = FixedTInfo->getType(); 6040 return true; 6041 } 6042 6043 if (SizeIsNegative) 6044 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6045 else if (Oversized.getBoolValue()) 6046 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6047 else if (FailedFoldDiagID) 6048 S.Diag(Loc, FailedFoldDiagID); 6049 return false; 6050 } 6051 6052 /// Register the given locally-scoped extern "C" declaration so 6053 /// that it can be found later for redeclarations. We include any extern "C" 6054 /// declaration that is not visible in the translation unit here, not just 6055 /// function-scope declarations. 6056 void 6057 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6058 if (!getLangOpts().CPlusPlus && 6059 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6060 // Don't need to track declarations in the TU in C. 6061 return; 6062 6063 // Note that we have a locally-scoped external with this name. 6064 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6065 } 6066 6067 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6068 // FIXME: We can have multiple results via __attribute__((overloadable)). 6069 auto Result = Context.getExternCContextDecl()->lookup(Name); 6070 return Result.empty() ? nullptr : *Result.begin(); 6071 } 6072 6073 /// Diagnose function specifiers on a declaration of an identifier that 6074 /// does not identify a function. 6075 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6076 // FIXME: We should probably indicate the identifier in question to avoid 6077 // confusion for constructs like "virtual int a(), b;" 6078 if (DS.isVirtualSpecified()) 6079 Diag(DS.getVirtualSpecLoc(), 6080 diag::err_virtual_non_function); 6081 6082 if (DS.hasExplicitSpecifier()) 6083 Diag(DS.getExplicitSpecLoc(), 6084 diag::err_explicit_non_function); 6085 6086 if (DS.isNoreturnSpecified()) 6087 Diag(DS.getNoreturnSpecLoc(), 6088 diag::err_noreturn_non_function); 6089 } 6090 6091 NamedDecl* 6092 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6093 TypeSourceInfo *TInfo, LookupResult &Previous) { 6094 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6095 if (D.getCXXScopeSpec().isSet()) { 6096 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6097 << D.getCXXScopeSpec().getRange(); 6098 D.setInvalidType(); 6099 // Pretend we didn't see the scope specifier. 6100 DC = CurContext; 6101 Previous.clear(); 6102 } 6103 6104 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6105 6106 if (D.getDeclSpec().isInlineSpecified()) 6107 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6108 << getLangOpts().CPlusPlus17; 6109 if (D.getDeclSpec().hasConstexprSpecifier()) 6110 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6111 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6112 6113 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6114 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6115 Diag(D.getName().StartLocation, 6116 diag::err_deduction_guide_invalid_specifier) 6117 << "typedef"; 6118 else 6119 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6120 << D.getName().getSourceRange(); 6121 return nullptr; 6122 } 6123 6124 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6125 if (!NewTD) return nullptr; 6126 6127 // Handle attributes prior to checking for duplicates in MergeVarDecl 6128 ProcessDeclAttributes(S, NewTD, D); 6129 6130 CheckTypedefForVariablyModifiedType(S, NewTD); 6131 6132 bool Redeclaration = D.isRedeclaration(); 6133 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6134 D.setRedeclaration(Redeclaration); 6135 return ND; 6136 } 6137 6138 void 6139 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6140 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6141 // then it shall have block scope. 6142 // Note that variably modified types must be fixed before merging the decl so 6143 // that redeclarations will match. 6144 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6145 QualType T = TInfo->getType(); 6146 if (T->isVariablyModifiedType()) { 6147 setFunctionHasBranchProtectedScope(); 6148 6149 if (S->getFnParent() == nullptr) { 6150 bool SizeIsNegative; 6151 llvm::APSInt Oversized; 6152 TypeSourceInfo *FixedTInfo = 6153 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6154 SizeIsNegative, 6155 Oversized); 6156 if (FixedTInfo) { 6157 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6158 NewTD->setTypeSourceInfo(FixedTInfo); 6159 } else { 6160 if (SizeIsNegative) 6161 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6162 else if (T->isVariableArrayType()) 6163 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6164 else if (Oversized.getBoolValue()) 6165 Diag(NewTD->getLocation(), diag::err_array_too_large) 6166 << Oversized.toString(10); 6167 else 6168 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6169 NewTD->setInvalidDecl(); 6170 } 6171 } 6172 } 6173 } 6174 6175 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6176 /// declares a typedef-name, either using the 'typedef' type specifier or via 6177 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6178 NamedDecl* 6179 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6180 LookupResult &Previous, bool &Redeclaration) { 6181 6182 // Find the shadowed declaration before filtering for scope. 6183 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6184 6185 // Merge the decl with the existing one if appropriate. If the decl is 6186 // in an outer scope, it isn't the same thing. 6187 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6188 /*AllowInlineNamespace*/false); 6189 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6190 if (!Previous.empty()) { 6191 Redeclaration = true; 6192 MergeTypedefNameDecl(S, NewTD, Previous); 6193 } else { 6194 inferGslPointerAttribute(NewTD); 6195 } 6196 6197 if (ShadowedDecl && !Redeclaration) 6198 CheckShadow(NewTD, ShadowedDecl, Previous); 6199 6200 // If this is the C FILE type, notify the AST context. 6201 if (IdentifierInfo *II = NewTD->getIdentifier()) 6202 if (!NewTD->isInvalidDecl() && 6203 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6204 if (II->isStr("FILE")) 6205 Context.setFILEDecl(NewTD); 6206 else if (II->isStr("jmp_buf")) 6207 Context.setjmp_bufDecl(NewTD); 6208 else if (II->isStr("sigjmp_buf")) 6209 Context.setsigjmp_bufDecl(NewTD); 6210 else if (II->isStr("ucontext_t")) 6211 Context.setucontext_tDecl(NewTD); 6212 } 6213 6214 return NewTD; 6215 } 6216 6217 /// Determines whether the given declaration is an out-of-scope 6218 /// previous declaration. 6219 /// 6220 /// This routine should be invoked when name lookup has found a 6221 /// previous declaration (PrevDecl) that is not in the scope where a 6222 /// new declaration by the same name is being introduced. If the new 6223 /// declaration occurs in a local scope, previous declarations with 6224 /// linkage may still be considered previous declarations (C99 6225 /// 6.2.2p4-5, C++ [basic.link]p6). 6226 /// 6227 /// \param PrevDecl the previous declaration found by name 6228 /// lookup 6229 /// 6230 /// \param DC the context in which the new declaration is being 6231 /// declared. 6232 /// 6233 /// \returns true if PrevDecl is an out-of-scope previous declaration 6234 /// for a new delcaration with the same name. 6235 static bool 6236 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6237 ASTContext &Context) { 6238 if (!PrevDecl) 6239 return false; 6240 6241 if (!PrevDecl->hasLinkage()) 6242 return false; 6243 6244 if (Context.getLangOpts().CPlusPlus) { 6245 // C++ [basic.link]p6: 6246 // If there is a visible declaration of an entity with linkage 6247 // having the same name and type, ignoring entities declared 6248 // outside the innermost enclosing namespace scope, the block 6249 // scope declaration declares that same entity and receives the 6250 // linkage of the previous declaration. 6251 DeclContext *OuterContext = DC->getRedeclContext(); 6252 if (!OuterContext->isFunctionOrMethod()) 6253 // This rule only applies to block-scope declarations. 6254 return false; 6255 6256 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6257 if (PrevOuterContext->isRecord()) 6258 // We found a member function: ignore it. 6259 return false; 6260 6261 // Find the innermost enclosing namespace for the new and 6262 // previous declarations. 6263 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6264 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6265 6266 // The previous declaration is in a different namespace, so it 6267 // isn't the same function. 6268 if (!OuterContext->Equals(PrevOuterContext)) 6269 return false; 6270 } 6271 6272 return true; 6273 } 6274 6275 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6276 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6277 if (!SS.isSet()) return; 6278 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6279 } 6280 6281 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6282 QualType type = decl->getType(); 6283 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6284 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6285 // Various kinds of declaration aren't allowed to be __autoreleasing. 6286 unsigned kind = -1U; 6287 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6288 if (var->hasAttr<BlocksAttr>()) 6289 kind = 0; // __block 6290 else if (!var->hasLocalStorage()) 6291 kind = 1; // global 6292 } else if (isa<ObjCIvarDecl>(decl)) { 6293 kind = 3; // ivar 6294 } else if (isa<FieldDecl>(decl)) { 6295 kind = 2; // field 6296 } 6297 6298 if (kind != -1U) { 6299 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6300 << kind; 6301 } 6302 } else if (lifetime == Qualifiers::OCL_None) { 6303 // Try to infer lifetime. 6304 if (!type->isObjCLifetimeType()) 6305 return false; 6306 6307 lifetime = type->getObjCARCImplicitLifetime(); 6308 type = Context.getLifetimeQualifiedType(type, lifetime); 6309 decl->setType(type); 6310 } 6311 6312 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6313 // Thread-local variables cannot have lifetime. 6314 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6315 var->getTLSKind()) { 6316 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6317 << var->getType(); 6318 return true; 6319 } 6320 } 6321 6322 return false; 6323 } 6324 6325 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6326 if (Decl->getType().hasAddressSpace()) 6327 return; 6328 if (Decl->getType()->isDependentType()) 6329 return; 6330 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6331 QualType Type = Var->getType(); 6332 if (Type->isSamplerT() || Type->isVoidType()) 6333 return; 6334 LangAS ImplAS = LangAS::opencl_private; 6335 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6336 Var->hasGlobalStorage()) 6337 ImplAS = LangAS::opencl_global; 6338 // If the original type from a decayed type is an array type and that array 6339 // type has no address space yet, deduce it now. 6340 if (auto DT = dyn_cast<DecayedType>(Type)) { 6341 auto OrigTy = DT->getOriginalType(); 6342 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6343 // Add the address space to the original array type and then propagate 6344 // that to the element type through `getAsArrayType`. 6345 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6346 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6347 // Re-generate the decayed type. 6348 Type = Context.getDecayedType(OrigTy); 6349 } 6350 } 6351 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6352 // Apply any qualifiers (including address space) from the array type to 6353 // the element type. This implements C99 6.7.3p8: "If the specification of 6354 // an array type includes any type qualifiers, the element type is so 6355 // qualified, not the array type." 6356 if (Type->isArrayType()) 6357 Type = QualType(Context.getAsArrayType(Type), 0); 6358 Decl->setType(Type); 6359 } 6360 } 6361 6362 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6363 // Ensure that an auto decl is deduced otherwise the checks below might cache 6364 // the wrong linkage. 6365 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6366 6367 // 'weak' only applies to declarations with external linkage. 6368 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6369 if (!ND.isExternallyVisible()) { 6370 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6371 ND.dropAttr<WeakAttr>(); 6372 } 6373 } 6374 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6375 if (ND.isExternallyVisible()) { 6376 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6377 ND.dropAttr<WeakRefAttr>(); 6378 ND.dropAttr<AliasAttr>(); 6379 } 6380 } 6381 6382 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6383 if (VD->hasInit()) { 6384 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6385 assert(VD->isThisDeclarationADefinition() && 6386 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6387 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6388 VD->dropAttr<AliasAttr>(); 6389 } 6390 } 6391 } 6392 6393 // 'selectany' only applies to externally visible variable declarations. 6394 // It does not apply to functions. 6395 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6396 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6397 S.Diag(Attr->getLocation(), 6398 diag::err_attribute_selectany_non_extern_data); 6399 ND.dropAttr<SelectAnyAttr>(); 6400 } 6401 } 6402 6403 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6404 auto *VD = dyn_cast<VarDecl>(&ND); 6405 bool IsAnonymousNS = false; 6406 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6407 if (VD) { 6408 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6409 while (NS && !IsAnonymousNS) { 6410 IsAnonymousNS = NS->isAnonymousNamespace(); 6411 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6412 } 6413 } 6414 // dll attributes require external linkage. Static locals may have external 6415 // linkage but still cannot be explicitly imported or exported. 6416 // In Microsoft mode, a variable defined in anonymous namespace must have 6417 // external linkage in order to be exported. 6418 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6419 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6420 (!AnonNSInMicrosoftMode && 6421 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6422 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6423 << &ND << Attr; 6424 ND.setInvalidDecl(); 6425 } 6426 } 6427 6428 // Virtual functions cannot be marked as 'notail'. 6429 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6430 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6431 if (MD->isVirtual()) { 6432 S.Diag(ND.getLocation(), 6433 diag::err_invalid_attribute_on_virtual_function) 6434 << Attr; 6435 ND.dropAttr<NotTailCalledAttr>(); 6436 } 6437 6438 // Check the attributes on the function type, if any. 6439 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6440 // Don't declare this variable in the second operand of the for-statement; 6441 // GCC miscompiles that by ending its lifetime before evaluating the 6442 // third operand. See gcc.gnu.org/PR86769. 6443 AttributedTypeLoc ATL; 6444 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6445 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6446 TL = ATL.getModifiedLoc()) { 6447 // The [[lifetimebound]] attribute can be applied to the implicit object 6448 // parameter of a non-static member function (other than a ctor or dtor) 6449 // by applying it to the function type. 6450 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6451 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6452 if (!MD || MD->isStatic()) { 6453 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6454 << !MD << A->getRange(); 6455 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6456 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6457 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6458 } 6459 } 6460 } 6461 } 6462 } 6463 6464 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6465 NamedDecl *NewDecl, 6466 bool IsSpecialization, 6467 bool IsDefinition) { 6468 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6469 return; 6470 6471 bool IsTemplate = false; 6472 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6473 OldDecl = OldTD->getTemplatedDecl(); 6474 IsTemplate = true; 6475 if (!IsSpecialization) 6476 IsDefinition = false; 6477 } 6478 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6479 NewDecl = NewTD->getTemplatedDecl(); 6480 IsTemplate = true; 6481 } 6482 6483 if (!OldDecl || !NewDecl) 6484 return; 6485 6486 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6487 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6488 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6489 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6490 6491 // dllimport and dllexport are inheritable attributes so we have to exclude 6492 // inherited attribute instances. 6493 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6494 (NewExportAttr && !NewExportAttr->isInherited()); 6495 6496 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6497 // the only exception being explicit specializations. 6498 // Implicitly generated declarations are also excluded for now because there 6499 // is no other way to switch these to use dllimport or dllexport. 6500 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6501 6502 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6503 // Allow with a warning for free functions and global variables. 6504 bool JustWarn = false; 6505 if (!OldDecl->isCXXClassMember()) { 6506 auto *VD = dyn_cast<VarDecl>(OldDecl); 6507 if (VD && !VD->getDescribedVarTemplate()) 6508 JustWarn = true; 6509 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6510 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6511 JustWarn = true; 6512 } 6513 6514 // We cannot change a declaration that's been used because IR has already 6515 // been emitted. Dllimported functions will still work though (modulo 6516 // address equality) as they can use the thunk. 6517 if (OldDecl->isUsed()) 6518 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6519 JustWarn = false; 6520 6521 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6522 : diag::err_attribute_dll_redeclaration; 6523 S.Diag(NewDecl->getLocation(), DiagID) 6524 << NewDecl 6525 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6526 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6527 if (!JustWarn) { 6528 NewDecl->setInvalidDecl(); 6529 return; 6530 } 6531 } 6532 6533 // A redeclaration is not allowed to drop a dllimport attribute, the only 6534 // exceptions being inline function definitions (except for function 6535 // templates), local extern declarations, qualified friend declarations or 6536 // special MSVC extension: in the last case, the declaration is treated as if 6537 // it were marked dllexport. 6538 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6539 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6540 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6541 // Ignore static data because out-of-line definitions are diagnosed 6542 // separately. 6543 IsStaticDataMember = VD->isStaticDataMember(); 6544 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6545 VarDecl::DeclarationOnly; 6546 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6547 IsInline = FD->isInlined(); 6548 IsQualifiedFriend = FD->getQualifier() && 6549 FD->getFriendObjectKind() == Decl::FOK_Declared; 6550 } 6551 6552 if (OldImportAttr && !HasNewAttr && 6553 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6554 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6555 if (IsMicrosoftABI && IsDefinition) { 6556 S.Diag(NewDecl->getLocation(), 6557 diag::warn_redeclaration_without_import_attribute) 6558 << NewDecl; 6559 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6560 NewDecl->dropAttr<DLLImportAttr>(); 6561 NewDecl->addAttr( 6562 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6563 } else { 6564 S.Diag(NewDecl->getLocation(), 6565 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6566 << NewDecl << OldImportAttr; 6567 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6568 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6569 OldDecl->dropAttr<DLLImportAttr>(); 6570 NewDecl->dropAttr<DLLImportAttr>(); 6571 } 6572 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6573 // In MinGW, seeing a function declared inline drops the dllimport 6574 // attribute. 6575 OldDecl->dropAttr<DLLImportAttr>(); 6576 NewDecl->dropAttr<DLLImportAttr>(); 6577 S.Diag(NewDecl->getLocation(), 6578 diag::warn_dllimport_dropped_from_inline_function) 6579 << NewDecl << OldImportAttr; 6580 } 6581 6582 // A specialization of a class template member function is processed here 6583 // since it's a redeclaration. If the parent class is dllexport, the 6584 // specialization inherits that attribute. This doesn't happen automatically 6585 // since the parent class isn't instantiated until later. 6586 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6587 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6588 !NewImportAttr && !NewExportAttr) { 6589 if (const DLLExportAttr *ParentExportAttr = 6590 MD->getParent()->getAttr<DLLExportAttr>()) { 6591 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6592 NewAttr->setInherited(true); 6593 NewDecl->addAttr(NewAttr); 6594 } 6595 } 6596 } 6597 } 6598 6599 /// Given that we are within the definition of the given function, 6600 /// will that definition behave like C99's 'inline', where the 6601 /// definition is discarded except for optimization purposes? 6602 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6603 // Try to avoid calling GetGVALinkageForFunction. 6604 6605 // All cases of this require the 'inline' keyword. 6606 if (!FD->isInlined()) return false; 6607 6608 // This is only possible in C++ with the gnu_inline attribute. 6609 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6610 return false; 6611 6612 // Okay, go ahead and call the relatively-more-expensive function. 6613 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6614 } 6615 6616 /// Determine whether a variable is extern "C" prior to attaching 6617 /// an initializer. We can't just call isExternC() here, because that 6618 /// will also compute and cache whether the declaration is externally 6619 /// visible, which might change when we attach the initializer. 6620 /// 6621 /// This can only be used if the declaration is known to not be a 6622 /// redeclaration of an internal linkage declaration. 6623 /// 6624 /// For instance: 6625 /// 6626 /// auto x = []{}; 6627 /// 6628 /// Attaching the initializer here makes this declaration not externally 6629 /// visible, because its type has internal linkage. 6630 /// 6631 /// FIXME: This is a hack. 6632 template<typename T> 6633 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6634 if (S.getLangOpts().CPlusPlus) { 6635 // In C++, the overloadable attribute negates the effects of extern "C". 6636 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6637 return false; 6638 6639 // So do CUDA's host/device attributes. 6640 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6641 D->template hasAttr<CUDAHostAttr>())) 6642 return false; 6643 } 6644 return D->isExternC(); 6645 } 6646 6647 static bool shouldConsiderLinkage(const VarDecl *VD) { 6648 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6649 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6650 isa<OMPDeclareMapperDecl>(DC)) 6651 return VD->hasExternalStorage(); 6652 if (DC->isFileContext()) 6653 return true; 6654 if (DC->isRecord()) 6655 return false; 6656 if (isa<RequiresExprBodyDecl>(DC)) 6657 return false; 6658 llvm_unreachable("Unexpected context"); 6659 } 6660 6661 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6662 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6663 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6664 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6665 return true; 6666 if (DC->isRecord()) 6667 return false; 6668 llvm_unreachable("Unexpected context"); 6669 } 6670 6671 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6672 ParsedAttr::Kind Kind) { 6673 // Check decl attributes on the DeclSpec. 6674 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6675 return true; 6676 6677 // Walk the declarator structure, checking decl attributes that were in a type 6678 // position to the decl itself. 6679 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6680 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6681 return true; 6682 } 6683 6684 // Finally, check attributes on the decl itself. 6685 return PD.getAttributes().hasAttribute(Kind); 6686 } 6687 6688 /// Adjust the \c DeclContext for a function or variable that might be a 6689 /// function-local external declaration. 6690 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6691 if (!DC->isFunctionOrMethod()) 6692 return false; 6693 6694 // If this is a local extern function or variable declared within a function 6695 // template, don't add it into the enclosing namespace scope until it is 6696 // instantiated; it might have a dependent type right now. 6697 if (DC->isDependentContext()) 6698 return true; 6699 6700 // C++11 [basic.link]p7: 6701 // When a block scope declaration of an entity with linkage is not found to 6702 // refer to some other declaration, then that entity is a member of the 6703 // innermost enclosing namespace. 6704 // 6705 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6706 // semantically-enclosing namespace, not a lexically-enclosing one. 6707 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6708 DC = DC->getParent(); 6709 return true; 6710 } 6711 6712 /// Returns true if given declaration has external C language linkage. 6713 static bool isDeclExternC(const Decl *D) { 6714 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6715 return FD->isExternC(); 6716 if (const auto *VD = dyn_cast<VarDecl>(D)) 6717 return VD->isExternC(); 6718 6719 llvm_unreachable("Unknown type of decl!"); 6720 } 6721 /// Returns true if there hasn't been any invalid type diagnosed. 6722 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6723 DeclContext *DC, QualType R) { 6724 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6725 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6726 // argument. 6727 if (R->isImageType() || R->isPipeType()) { 6728 Se.Diag(D.getIdentifierLoc(), 6729 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6730 << R; 6731 D.setInvalidType(); 6732 return false; 6733 } 6734 6735 // OpenCL v1.2 s6.9.r: 6736 // The event type cannot be used to declare a program scope variable. 6737 // OpenCL v2.0 s6.9.q: 6738 // The clk_event_t and reserve_id_t types cannot be declared in program 6739 // scope. 6740 if (NULL == S->getParent()) { 6741 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6742 Se.Diag(D.getIdentifierLoc(), 6743 diag::err_invalid_type_for_program_scope_var) 6744 << R; 6745 D.setInvalidType(); 6746 return false; 6747 } 6748 } 6749 6750 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6751 QualType NR = R; 6752 while (NR->isPointerType()) { 6753 if (NR->isFunctionPointerType()) { 6754 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6755 D.setInvalidType(); 6756 return false; 6757 } 6758 NR = NR->getPointeeType(); 6759 } 6760 6761 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6762 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6763 // half array type (unless the cl_khr_fp16 extension is enabled). 6764 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6765 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6766 D.setInvalidType(); 6767 return false; 6768 } 6769 } 6770 6771 // OpenCL v1.2 s6.9.r: 6772 // The event type cannot be used with the __local, __constant and __global 6773 // address space qualifiers. 6774 if (R->isEventT()) { 6775 if (R.getAddressSpace() != LangAS::opencl_private) { 6776 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6777 D.setInvalidType(); 6778 return false; 6779 } 6780 } 6781 6782 // C++ for OpenCL does not allow the thread_local storage qualifier. 6783 // OpenCL C does not support thread_local either, and 6784 // also reject all other thread storage class specifiers. 6785 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6786 if (TSC != TSCS_unspecified) { 6787 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6788 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6789 diag::err_opencl_unknown_type_specifier) 6790 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6791 << DeclSpec::getSpecifierName(TSC) << 1; 6792 D.setInvalidType(); 6793 return false; 6794 } 6795 6796 if (R->isSamplerT()) { 6797 // OpenCL v1.2 s6.9.b p4: 6798 // The sampler type cannot be used with the __local and __global address 6799 // space qualifiers. 6800 if (R.getAddressSpace() == LangAS::opencl_local || 6801 R.getAddressSpace() == LangAS::opencl_global) { 6802 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6803 D.setInvalidType(); 6804 } 6805 6806 // OpenCL v1.2 s6.12.14.1: 6807 // A global sampler must be declared with either the constant address 6808 // space qualifier or with the const qualifier. 6809 if (DC->isTranslationUnit() && 6810 !(R.getAddressSpace() == LangAS::opencl_constant || 6811 R.isConstQualified())) { 6812 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6813 D.setInvalidType(); 6814 } 6815 if (D.isInvalidType()) 6816 return false; 6817 } 6818 return true; 6819 } 6820 6821 NamedDecl *Sema::ActOnVariableDeclarator( 6822 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6823 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6824 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6825 QualType R = TInfo->getType(); 6826 DeclarationName Name = GetNameForDeclarator(D).getName(); 6827 6828 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6829 6830 if (D.isDecompositionDeclarator()) { 6831 // Take the name of the first declarator as our name for diagnostic 6832 // purposes. 6833 auto &Decomp = D.getDecompositionDeclarator(); 6834 if (!Decomp.bindings().empty()) { 6835 II = Decomp.bindings()[0].Name; 6836 Name = II; 6837 } 6838 } else if (!II) { 6839 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6840 return nullptr; 6841 } 6842 6843 6844 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6845 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6846 6847 // dllimport globals without explicit storage class are treated as extern. We 6848 // have to change the storage class this early to get the right DeclContext. 6849 if (SC == SC_None && !DC->isRecord() && 6850 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6851 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6852 SC = SC_Extern; 6853 6854 DeclContext *OriginalDC = DC; 6855 bool IsLocalExternDecl = SC == SC_Extern && 6856 adjustContextForLocalExternDecl(DC); 6857 6858 if (SCSpec == DeclSpec::SCS_mutable) { 6859 // mutable can only appear on non-static class members, so it's always 6860 // an error here 6861 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6862 D.setInvalidType(); 6863 SC = SC_None; 6864 } 6865 6866 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6867 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6868 D.getDeclSpec().getStorageClassSpecLoc())) { 6869 // In C++11, the 'register' storage class specifier is deprecated. 6870 // Suppress the warning in system macros, it's used in macros in some 6871 // popular C system headers, such as in glibc's htonl() macro. 6872 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6873 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6874 : diag::warn_deprecated_register) 6875 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6876 } 6877 6878 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6879 6880 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6881 // C99 6.9p2: The storage-class specifiers auto and register shall not 6882 // appear in the declaration specifiers in an external declaration. 6883 // Global Register+Asm is a GNU extension we support. 6884 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6885 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6886 D.setInvalidType(); 6887 } 6888 } 6889 6890 // If this variable has a variable-modified type and an initializer, try to 6891 // fold to a constant-sized type. This is otherwise invalid. 6892 if (D.hasInitializer() && R->isVariablyModifiedType()) 6893 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6894 /*DiagID=*/0); 6895 6896 bool IsMemberSpecialization = false; 6897 bool IsVariableTemplateSpecialization = false; 6898 bool IsPartialSpecialization = false; 6899 bool IsVariableTemplate = false; 6900 VarDecl *NewVD = nullptr; 6901 VarTemplateDecl *NewTemplate = nullptr; 6902 TemplateParameterList *TemplateParams = nullptr; 6903 if (!getLangOpts().CPlusPlus) { 6904 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6905 II, R, TInfo, SC); 6906 6907 if (R->getContainedDeducedType()) 6908 ParsingInitForAutoVars.insert(NewVD); 6909 6910 if (D.isInvalidType()) 6911 NewVD->setInvalidDecl(); 6912 6913 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6914 NewVD->hasLocalStorage()) 6915 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6916 NTCUC_AutoVar, NTCUK_Destruct); 6917 } else { 6918 bool Invalid = false; 6919 6920 if (DC->isRecord() && !CurContext->isRecord()) { 6921 // This is an out-of-line definition of a static data member. 6922 switch (SC) { 6923 case SC_None: 6924 break; 6925 case SC_Static: 6926 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6927 diag::err_static_out_of_line) 6928 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6929 break; 6930 case SC_Auto: 6931 case SC_Register: 6932 case SC_Extern: 6933 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6934 // to names of variables declared in a block or to function parameters. 6935 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6936 // of class members 6937 6938 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6939 diag::err_storage_class_for_static_member) 6940 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6941 break; 6942 case SC_PrivateExtern: 6943 llvm_unreachable("C storage class in c++!"); 6944 } 6945 } 6946 6947 if (SC == SC_Static && CurContext->isRecord()) { 6948 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6949 // Walk up the enclosing DeclContexts to check for any that are 6950 // incompatible with static data members. 6951 const DeclContext *FunctionOrMethod = nullptr; 6952 const CXXRecordDecl *AnonStruct = nullptr; 6953 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6954 if (Ctxt->isFunctionOrMethod()) { 6955 FunctionOrMethod = Ctxt; 6956 break; 6957 } 6958 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6959 if (ParentDecl && !ParentDecl->getDeclName()) { 6960 AnonStruct = ParentDecl; 6961 break; 6962 } 6963 } 6964 if (FunctionOrMethod) { 6965 // C++ [class.static.data]p5: A local class shall not have static data 6966 // members. 6967 Diag(D.getIdentifierLoc(), 6968 diag::err_static_data_member_not_allowed_in_local_class) 6969 << Name << RD->getDeclName() << RD->getTagKind(); 6970 } else if (AnonStruct) { 6971 // C++ [class.static.data]p4: Unnamed classes and classes contained 6972 // directly or indirectly within unnamed classes shall not contain 6973 // static data members. 6974 Diag(D.getIdentifierLoc(), 6975 diag::err_static_data_member_not_allowed_in_anon_struct) 6976 << Name << AnonStruct->getTagKind(); 6977 Invalid = true; 6978 } else if (RD->isUnion()) { 6979 // C++98 [class.union]p1: If a union contains a static data member, 6980 // the program is ill-formed. C++11 drops this restriction. 6981 Diag(D.getIdentifierLoc(), 6982 getLangOpts().CPlusPlus11 6983 ? diag::warn_cxx98_compat_static_data_member_in_union 6984 : diag::ext_static_data_member_in_union) << Name; 6985 } 6986 } 6987 } 6988 6989 // Match up the template parameter lists with the scope specifier, then 6990 // determine whether we have a template or a template specialization. 6991 bool InvalidScope = false; 6992 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6993 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6994 D.getCXXScopeSpec(), 6995 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6996 ? D.getName().TemplateId 6997 : nullptr, 6998 TemplateParamLists, 6999 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7000 Invalid |= InvalidScope; 7001 7002 if (TemplateParams) { 7003 if (!TemplateParams->size() && 7004 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7005 // There is an extraneous 'template<>' for this variable. Complain 7006 // about it, but allow the declaration of the variable. 7007 Diag(TemplateParams->getTemplateLoc(), 7008 diag::err_template_variable_noparams) 7009 << II 7010 << SourceRange(TemplateParams->getTemplateLoc(), 7011 TemplateParams->getRAngleLoc()); 7012 TemplateParams = nullptr; 7013 } else { 7014 // Check that we can declare a template here. 7015 if (CheckTemplateDeclScope(S, TemplateParams)) 7016 return nullptr; 7017 7018 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7019 // This is an explicit specialization or a partial specialization. 7020 IsVariableTemplateSpecialization = true; 7021 IsPartialSpecialization = TemplateParams->size() > 0; 7022 } else { // if (TemplateParams->size() > 0) 7023 // This is a template declaration. 7024 IsVariableTemplate = true; 7025 7026 // Only C++1y supports variable templates (N3651). 7027 Diag(D.getIdentifierLoc(), 7028 getLangOpts().CPlusPlus14 7029 ? diag::warn_cxx11_compat_variable_template 7030 : diag::ext_variable_template); 7031 } 7032 } 7033 } else { 7034 // Check that we can declare a member specialization here. 7035 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7036 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7037 return nullptr; 7038 assert((Invalid || 7039 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7040 "should have a 'template<>' for this decl"); 7041 } 7042 7043 if (IsVariableTemplateSpecialization) { 7044 SourceLocation TemplateKWLoc = 7045 TemplateParamLists.size() > 0 7046 ? TemplateParamLists[0]->getTemplateLoc() 7047 : SourceLocation(); 7048 DeclResult Res = ActOnVarTemplateSpecialization( 7049 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7050 IsPartialSpecialization); 7051 if (Res.isInvalid()) 7052 return nullptr; 7053 NewVD = cast<VarDecl>(Res.get()); 7054 AddToScope = false; 7055 } else if (D.isDecompositionDeclarator()) { 7056 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7057 D.getIdentifierLoc(), R, TInfo, SC, 7058 Bindings); 7059 } else 7060 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7061 D.getIdentifierLoc(), II, R, TInfo, SC); 7062 7063 // If this is supposed to be a variable template, create it as such. 7064 if (IsVariableTemplate) { 7065 NewTemplate = 7066 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7067 TemplateParams, NewVD); 7068 NewVD->setDescribedVarTemplate(NewTemplate); 7069 } 7070 7071 // If this decl has an auto type in need of deduction, make a note of the 7072 // Decl so we can diagnose uses of it in its own initializer. 7073 if (R->getContainedDeducedType()) 7074 ParsingInitForAutoVars.insert(NewVD); 7075 7076 if (D.isInvalidType() || Invalid) { 7077 NewVD->setInvalidDecl(); 7078 if (NewTemplate) 7079 NewTemplate->setInvalidDecl(); 7080 } 7081 7082 SetNestedNameSpecifier(*this, NewVD, D); 7083 7084 // If we have any template parameter lists that don't directly belong to 7085 // the variable (matching the scope specifier), store them. 7086 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7087 if (TemplateParamLists.size() > VDTemplateParamLists) 7088 NewVD->setTemplateParameterListsInfo( 7089 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7090 } 7091 7092 if (D.getDeclSpec().isInlineSpecified()) { 7093 if (!getLangOpts().CPlusPlus) { 7094 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7095 << 0; 7096 } else if (CurContext->isFunctionOrMethod()) { 7097 // 'inline' is not allowed on block scope variable declaration. 7098 Diag(D.getDeclSpec().getInlineSpecLoc(), 7099 diag::err_inline_declaration_block_scope) << Name 7100 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7101 } else { 7102 Diag(D.getDeclSpec().getInlineSpecLoc(), 7103 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7104 : diag::ext_inline_variable); 7105 NewVD->setInlineSpecified(); 7106 } 7107 } 7108 7109 // Set the lexical context. If the declarator has a C++ scope specifier, the 7110 // lexical context will be different from the semantic context. 7111 NewVD->setLexicalDeclContext(CurContext); 7112 if (NewTemplate) 7113 NewTemplate->setLexicalDeclContext(CurContext); 7114 7115 if (IsLocalExternDecl) { 7116 if (D.isDecompositionDeclarator()) 7117 for (auto *B : Bindings) 7118 B->setLocalExternDecl(); 7119 else 7120 NewVD->setLocalExternDecl(); 7121 } 7122 7123 bool EmitTLSUnsupportedError = false; 7124 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7125 // C++11 [dcl.stc]p4: 7126 // When thread_local is applied to a variable of block scope the 7127 // storage-class-specifier static is implied if it does not appear 7128 // explicitly. 7129 // Core issue: 'static' is not implied if the variable is declared 7130 // 'extern'. 7131 if (NewVD->hasLocalStorage() && 7132 (SCSpec != DeclSpec::SCS_unspecified || 7133 TSCS != DeclSpec::TSCS_thread_local || 7134 !DC->isFunctionOrMethod())) 7135 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7136 diag::err_thread_non_global) 7137 << DeclSpec::getSpecifierName(TSCS); 7138 else if (!Context.getTargetInfo().isTLSSupported()) { 7139 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7140 getLangOpts().SYCLIsDevice) { 7141 // Postpone error emission until we've collected attributes required to 7142 // figure out whether it's a host or device variable and whether the 7143 // error should be ignored. 7144 EmitTLSUnsupportedError = true; 7145 // We still need to mark the variable as TLS so it shows up in AST with 7146 // proper storage class for other tools to use even if we're not going 7147 // to emit any code for it. 7148 NewVD->setTSCSpec(TSCS); 7149 } else 7150 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7151 diag::err_thread_unsupported); 7152 } else 7153 NewVD->setTSCSpec(TSCS); 7154 } 7155 7156 switch (D.getDeclSpec().getConstexprSpecifier()) { 7157 case ConstexprSpecKind::Unspecified: 7158 break; 7159 7160 case ConstexprSpecKind::Consteval: 7161 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7162 diag::err_constexpr_wrong_decl_kind) 7163 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7164 LLVM_FALLTHROUGH; 7165 7166 case ConstexprSpecKind::Constexpr: 7167 NewVD->setConstexpr(true); 7168 MaybeAddCUDAConstantAttr(NewVD); 7169 // C++1z [dcl.spec.constexpr]p1: 7170 // A static data member declared with the constexpr specifier is 7171 // implicitly an inline variable. 7172 if (NewVD->isStaticDataMember() && 7173 (getLangOpts().CPlusPlus17 || 7174 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7175 NewVD->setImplicitlyInline(); 7176 break; 7177 7178 case ConstexprSpecKind::Constinit: 7179 if (!NewVD->hasGlobalStorage()) 7180 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7181 diag::err_constinit_local_variable); 7182 else 7183 NewVD->addAttr(ConstInitAttr::Create( 7184 Context, D.getDeclSpec().getConstexprSpecLoc(), 7185 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7186 break; 7187 } 7188 7189 // C99 6.7.4p3 7190 // An inline definition of a function with external linkage shall 7191 // not contain a definition of a modifiable object with static or 7192 // thread storage duration... 7193 // We only apply this when the function is required to be defined 7194 // elsewhere, i.e. when the function is not 'extern inline'. Note 7195 // that a local variable with thread storage duration still has to 7196 // be marked 'static'. Also note that it's possible to get these 7197 // semantics in C++ using __attribute__((gnu_inline)). 7198 if (SC == SC_Static && S->getFnParent() != nullptr && 7199 !NewVD->getType().isConstQualified()) { 7200 FunctionDecl *CurFD = getCurFunctionDecl(); 7201 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7202 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7203 diag::warn_static_local_in_extern_inline); 7204 MaybeSuggestAddingStaticToDecl(CurFD); 7205 } 7206 } 7207 7208 if (D.getDeclSpec().isModulePrivateSpecified()) { 7209 if (IsVariableTemplateSpecialization) 7210 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7211 << (IsPartialSpecialization ? 1 : 0) 7212 << FixItHint::CreateRemoval( 7213 D.getDeclSpec().getModulePrivateSpecLoc()); 7214 else if (IsMemberSpecialization) 7215 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7216 << 2 7217 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7218 else if (NewVD->hasLocalStorage()) 7219 Diag(NewVD->getLocation(), diag::err_module_private_local) 7220 << 0 << NewVD 7221 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7222 << FixItHint::CreateRemoval( 7223 D.getDeclSpec().getModulePrivateSpecLoc()); 7224 else { 7225 NewVD->setModulePrivate(); 7226 if (NewTemplate) 7227 NewTemplate->setModulePrivate(); 7228 for (auto *B : Bindings) 7229 B->setModulePrivate(); 7230 } 7231 } 7232 7233 if (getLangOpts().OpenCL) { 7234 7235 deduceOpenCLAddressSpace(NewVD); 7236 7237 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7238 } 7239 7240 // Handle attributes prior to checking for duplicates in MergeVarDecl 7241 ProcessDeclAttributes(S, NewVD, D); 7242 7243 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7244 getLangOpts().SYCLIsDevice) { 7245 if (EmitTLSUnsupportedError && 7246 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7247 (getLangOpts().OpenMPIsDevice && 7248 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7249 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7250 diag::err_thread_unsupported); 7251 7252 if (EmitTLSUnsupportedError && 7253 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7254 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7255 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7256 // storage [duration]." 7257 if (SC == SC_None && S->getFnParent() != nullptr && 7258 (NewVD->hasAttr<CUDASharedAttr>() || 7259 NewVD->hasAttr<CUDAConstantAttr>())) { 7260 NewVD->setStorageClass(SC_Static); 7261 } 7262 } 7263 7264 // Ensure that dllimport globals without explicit storage class are treated as 7265 // extern. The storage class is set above using parsed attributes. Now we can 7266 // check the VarDecl itself. 7267 assert(!NewVD->hasAttr<DLLImportAttr>() || 7268 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7269 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7270 7271 // In auto-retain/release, infer strong retension for variables of 7272 // retainable type. 7273 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7274 NewVD->setInvalidDecl(); 7275 7276 // Handle GNU asm-label extension (encoded as an attribute). 7277 if (Expr *E = (Expr*)D.getAsmLabel()) { 7278 // The parser guarantees this is a string. 7279 StringLiteral *SE = cast<StringLiteral>(E); 7280 StringRef Label = SE->getString(); 7281 if (S->getFnParent() != nullptr) { 7282 switch (SC) { 7283 case SC_None: 7284 case SC_Auto: 7285 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7286 break; 7287 case SC_Register: 7288 // Local Named register 7289 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7290 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7291 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7292 break; 7293 case SC_Static: 7294 case SC_Extern: 7295 case SC_PrivateExtern: 7296 break; 7297 } 7298 } else if (SC == SC_Register) { 7299 // Global Named register 7300 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7301 const auto &TI = Context.getTargetInfo(); 7302 bool HasSizeMismatch; 7303 7304 if (!TI.isValidGCCRegisterName(Label)) 7305 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7306 else if (!TI.validateGlobalRegisterVariable(Label, 7307 Context.getTypeSize(R), 7308 HasSizeMismatch)) 7309 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7310 else if (HasSizeMismatch) 7311 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7312 } 7313 7314 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7315 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7316 NewVD->setInvalidDecl(true); 7317 } 7318 } 7319 7320 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7321 /*IsLiteralLabel=*/true, 7322 SE->getStrTokenLoc(0))); 7323 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7324 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7325 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7326 if (I != ExtnameUndeclaredIdentifiers.end()) { 7327 if (isDeclExternC(NewVD)) { 7328 NewVD->addAttr(I->second); 7329 ExtnameUndeclaredIdentifiers.erase(I); 7330 } else 7331 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7332 << /*Variable*/1 << NewVD; 7333 } 7334 } 7335 7336 // Find the shadowed declaration before filtering for scope. 7337 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7338 ? getShadowedDeclaration(NewVD, Previous) 7339 : nullptr; 7340 7341 // Don't consider existing declarations that are in a different 7342 // scope and are out-of-semantic-context declarations (if the new 7343 // declaration has linkage). 7344 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7345 D.getCXXScopeSpec().isNotEmpty() || 7346 IsMemberSpecialization || 7347 IsVariableTemplateSpecialization); 7348 7349 // Check whether the previous declaration is in the same block scope. This 7350 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7351 if (getLangOpts().CPlusPlus && 7352 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7353 NewVD->setPreviousDeclInSameBlockScope( 7354 Previous.isSingleResult() && !Previous.isShadowed() && 7355 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7356 7357 if (!getLangOpts().CPlusPlus) { 7358 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7359 } else { 7360 // If this is an explicit specialization of a static data member, check it. 7361 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7362 CheckMemberSpecialization(NewVD, Previous)) 7363 NewVD->setInvalidDecl(); 7364 7365 // Merge the decl with the existing one if appropriate. 7366 if (!Previous.empty()) { 7367 if (Previous.isSingleResult() && 7368 isa<FieldDecl>(Previous.getFoundDecl()) && 7369 D.getCXXScopeSpec().isSet()) { 7370 // The user tried to define a non-static data member 7371 // out-of-line (C++ [dcl.meaning]p1). 7372 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7373 << D.getCXXScopeSpec().getRange(); 7374 Previous.clear(); 7375 NewVD->setInvalidDecl(); 7376 } 7377 } else if (D.getCXXScopeSpec().isSet()) { 7378 // No previous declaration in the qualifying scope. 7379 Diag(D.getIdentifierLoc(), diag::err_no_member) 7380 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7381 << D.getCXXScopeSpec().getRange(); 7382 NewVD->setInvalidDecl(); 7383 } 7384 7385 if (!IsVariableTemplateSpecialization) 7386 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7387 7388 if (NewTemplate) { 7389 VarTemplateDecl *PrevVarTemplate = 7390 NewVD->getPreviousDecl() 7391 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7392 : nullptr; 7393 7394 // Check the template parameter list of this declaration, possibly 7395 // merging in the template parameter list from the previous variable 7396 // template declaration. 7397 if (CheckTemplateParameterList( 7398 TemplateParams, 7399 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7400 : nullptr, 7401 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7402 DC->isDependentContext()) 7403 ? TPC_ClassTemplateMember 7404 : TPC_VarTemplate)) 7405 NewVD->setInvalidDecl(); 7406 7407 // If we are providing an explicit specialization of a static variable 7408 // template, make a note of that. 7409 if (PrevVarTemplate && 7410 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7411 PrevVarTemplate->setMemberSpecialization(); 7412 } 7413 } 7414 7415 // Diagnose shadowed variables iff this isn't a redeclaration. 7416 if (ShadowedDecl && !D.isRedeclaration()) 7417 CheckShadow(NewVD, ShadowedDecl, Previous); 7418 7419 ProcessPragmaWeak(S, NewVD); 7420 7421 // If this is the first declaration of an extern C variable, update 7422 // the map of such variables. 7423 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7424 isIncompleteDeclExternC(*this, NewVD)) 7425 RegisterLocallyScopedExternCDecl(NewVD, S); 7426 7427 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7428 MangleNumberingContext *MCtx; 7429 Decl *ManglingContextDecl; 7430 std::tie(MCtx, ManglingContextDecl) = 7431 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7432 if (MCtx) { 7433 Context.setManglingNumber( 7434 NewVD, MCtx->getManglingNumber( 7435 NewVD, getMSManglingNumber(getLangOpts(), S))); 7436 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7437 } 7438 } 7439 7440 // Special handling of variable named 'main'. 7441 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7442 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7443 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7444 7445 // C++ [basic.start.main]p3 7446 // A program that declares a variable main at global scope is ill-formed. 7447 if (getLangOpts().CPlusPlus) 7448 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7449 7450 // In C, and external-linkage variable named main results in undefined 7451 // behavior. 7452 else if (NewVD->hasExternalFormalLinkage()) 7453 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7454 } 7455 7456 if (D.isRedeclaration() && !Previous.empty()) { 7457 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7458 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7459 D.isFunctionDefinition()); 7460 } 7461 7462 if (NewTemplate) { 7463 if (NewVD->isInvalidDecl()) 7464 NewTemplate->setInvalidDecl(); 7465 ActOnDocumentableDecl(NewTemplate); 7466 return NewTemplate; 7467 } 7468 7469 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7470 CompleteMemberSpecialization(NewVD, Previous); 7471 7472 return NewVD; 7473 } 7474 7475 /// Enum describing the %select options in diag::warn_decl_shadow. 7476 enum ShadowedDeclKind { 7477 SDK_Local, 7478 SDK_Global, 7479 SDK_StaticMember, 7480 SDK_Field, 7481 SDK_Typedef, 7482 SDK_Using 7483 }; 7484 7485 /// Determine what kind of declaration we're shadowing. 7486 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7487 const DeclContext *OldDC) { 7488 if (isa<TypeAliasDecl>(ShadowedDecl)) 7489 return SDK_Using; 7490 else if (isa<TypedefDecl>(ShadowedDecl)) 7491 return SDK_Typedef; 7492 else if (isa<RecordDecl>(OldDC)) 7493 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7494 7495 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7496 } 7497 7498 /// Return the location of the capture if the given lambda captures the given 7499 /// variable \p VD, or an invalid source location otherwise. 7500 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7501 const VarDecl *VD) { 7502 for (const Capture &Capture : LSI->Captures) { 7503 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7504 return Capture.getLocation(); 7505 } 7506 return SourceLocation(); 7507 } 7508 7509 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7510 const LookupResult &R) { 7511 // Only diagnose if we're shadowing an unambiguous field or variable. 7512 if (R.getResultKind() != LookupResult::Found) 7513 return false; 7514 7515 // Return false if warning is ignored. 7516 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7517 } 7518 7519 /// Return the declaration shadowed by the given variable \p D, or null 7520 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7521 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7522 const LookupResult &R) { 7523 if (!shouldWarnIfShadowedDecl(Diags, R)) 7524 return nullptr; 7525 7526 // Don't diagnose declarations at file scope. 7527 if (D->hasGlobalStorage()) 7528 return nullptr; 7529 7530 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7531 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7532 ? ShadowedDecl 7533 : nullptr; 7534 } 7535 7536 /// Return the declaration shadowed by the given typedef \p D, or null 7537 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7538 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7539 const LookupResult &R) { 7540 // Don't warn if typedef declaration is part of a class 7541 if (D->getDeclContext()->isRecord()) 7542 return nullptr; 7543 7544 if (!shouldWarnIfShadowedDecl(Diags, R)) 7545 return nullptr; 7546 7547 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7548 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7549 } 7550 7551 /// Diagnose variable or built-in function shadowing. Implements 7552 /// -Wshadow. 7553 /// 7554 /// This method is called whenever a VarDecl is added to a "useful" 7555 /// scope. 7556 /// 7557 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7558 /// \param R the lookup of the name 7559 /// 7560 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7561 const LookupResult &R) { 7562 DeclContext *NewDC = D->getDeclContext(); 7563 7564 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7565 // Fields are not shadowed by variables in C++ static methods. 7566 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7567 if (MD->isStatic()) 7568 return; 7569 7570 // Fields shadowed by constructor parameters are a special case. Usually 7571 // the constructor initializes the field with the parameter. 7572 if (isa<CXXConstructorDecl>(NewDC)) 7573 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7574 // Remember that this was shadowed so we can either warn about its 7575 // modification or its existence depending on warning settings. 7576 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7577 return; 7578 } 7579 } 7580 7581 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7582 if (shadowedVar->isExternC()) { 7583 // For shadowing external vars, make sure that we point to the global 7584 // declaration, not a locally scoped extern declaration. 7585 for (auto I : shadowedVar->redecls()) 7586 if (I->isFileVarDecl()) { 7587 ShadowedDecl = I; 7588 break; 7589 } 7590 } 7591 7592 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7593 7594 unsigned WarningDiag = diag::warn_decl_shadow; 7595 SourceLocation CaptureLoc; 7596 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7597 isa<CXXMethodDecl>(NewDC)) { 7598 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7599 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7600 if (RD->getLambdaCaptureDefault() == LCD_None) { 7601 // Try to avoid warnings for lambdas with an explicit capture list. 7602 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7603 // Warn only when the lambda captures the shadowed decl explicitly. 7604 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7605 if (CaptureLoc.isInvalid()) 7606 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7607 } else { 7608 // Remember that this was shadowed so we can avoid the warning if the 7609 // shadowed decl isn't captured and the warning settings allow it. 7610 cast<LambdaScopeInfo>(getCurFunction()) 7611 ->ShadowingDecls.push_back( 7612 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7613 return; 7614 } 7615 } 7616 7617 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7618 // A variable can't shadow a local variable in an enclosing scope, if 7619 // they are separated by a non-capturing declaration context. 7620 for (DeclContext *ParentDC = NewDC; 7621 ParentDC && !ParentDC->Equals(OldDC); 7622 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7623 // Only block literals, captured statements, and lambda expressions 7624 // can capture; other scopes don't. 7625 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7626 !isLambdaCallOperator(ParentDC)) { 7627 return; 7628 } 7629 } 7630 } 7631 } 7632 } 7633 7634 // Only warn about certain kinds of shadowing for class members. 7635 if (NewDC && NewDC->isRecord()) { 7636 // In particular, don't warn about shadowing non-class members. 7637 if (!OldDC->isRecord()) 7638 return; 7639 7640 // TODO: should we warn about static data members shadowing 7641 // static data members from base classes? 7642 7643 // TODO: don't diagnose for inaccessible shadowed members. 7644 // This is hard to do perfectly because we might friend the 7645 // shadowing context, but that's just a false negative. 7646 } 7647 7648 7649 DeclarationName Name = R.getLookupName(); 7650 7651 // Emit warning and note. 7652 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7653 return; 7654 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7655 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7656 if (!CaptureLoc.isInvalid()) 7657 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7658 << Name << /*explicitly*/ 1; 7659 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7660 } 7661 7662 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7663 /// when these variables are captured by the lambda. 7664 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7665 for (const auto &Shadow : LSI->ShadowingDecls) { 7666 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7667 // Try to avoid the warning when the shadowed decl isn't captured. 7668 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7669 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7670 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7671 ? diag::warn_decl_shadow_uncaptured_local 7672 : diag::warn_decl_shadow) 7673 << Shadow.VD->getDeclName() 7674 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7675 if (!CaptureLoc.isInvalid()) 7676 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7677 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7678 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7679 } 7680 } 7681 7682 /// Check -Wshadow without the advantage of a previous lookup. 7683 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7684 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7685 return; 7686 7687 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7688 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7689 LookupName(R, S); 7690 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7691 CheckShadow(D, ShadowedDecl, R); 7692 } 7693 7694 /// Check if 'E', which is an expression that is about to be modified, refers 7695 /// to a constructor parameter that shadows a field. 7696 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7697 // Quickly ignore expressions that can't be shadowing ctor parameters. 7698 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7699 return; 7700 E = E->IgnoreParenImpCasts(); 7701 auto *DRE = dyn_cast<DeclRefExpr>(E); 7702 if (!DRE) 7703 return; 7704 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7705 auto I = ShadowingDecls.find(D); 7706 if (I == ShadowingDecls.end()) 7707 return; 7708 const NamedDecl *ShadowedDecl = I->second; 7709 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7710 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7711 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7712 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7713 7714 // Avoid issuing multiple warnings about the same decl. 7715 ShadowingDecls.erase(I); 7716 } 7717 7718 /// Check for conflict between this global or extern "C" declaration and 7719 /// previous global or extern "C" declarations. This is only used in C++. 7720 template<typename T> 7721 static bool checkGlobalOrExternCConflict( 7722 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7723 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7724 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7725 7726 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7727 // The common case: this global doesn't conflict with any extern "C" 7728 // declaration. 7729 return false; 7730 } 7731 7732 if (Prev) { 7733 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7734 // Both the old and new declarations have C language linkage. This is a 7735 // redeclaration. 7736 Previous.clear(); 7737 Previous.addDecl(Prev); 7738 return true; 7739 } 7740 7741 // This is a global, non-extern "C" declaration, and there is a previous 7742 // non-global extern "C" declaration. Diagnose if this is a variable 7743 // declaration. 7744 if (!isa<VarDecl>(ND)) 7745 return false; 7746 } else { 7747 // The declaration is extern "C". Check for any declaration in the 7748 // translation unit which might conflict. 7749 if (IsGlobal) { 7750 // We have already performed the lookup into the translation unit. 7751 IsGlobal = false; 7752 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7753 I != E; ++I) { 7754 if (isa<VarDecl>(*I)) { 7755 Prev = *I; 7756 break; 7757 } 7758 } 7759 } else { 7760 DeclContext::lookup_result R = 7761 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7762 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7763 I != E; ++I) { 7764 if (isa<VarDecl>(*I)) { 7765 Prev = *I; 7766 break; 7767 } 7768 // FIXME: If we have any other entity with this name in global scope, 7769 // the declaration is ill-formed, but that is a defect: it breaks the 7770 // 'stat' hack, for instance. Only variables can have mangled name 7771 // clashes with extern "C" declarations, so only they deserve a 7772 // diagnostic. 7773 } 7774 } 7775 7776 if (!Prev) 7777 return false; 7778 } 7779 7780 // Use the first declaration's location to ensure we point at something which 7781 // is lexically inside an extern "C" linkage-spec. 7782 assert(Prev && "should have found a previous declaration to diagnose"); 7783 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7784 Prev = FD->getFirstDecl(); 7785 else 7786 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7787 7788 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7789 << IsGlobal << ND; 7790 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7791 << IsGlobal; 7792 return false; 7793 } 7794 7795 /// Apply special rules for handling extern "C" declarations. Returns \c true 7796 /// if we have found that this is a redeclaration of some prior entity. 7797 /// 7798 /// Per C++ [dcl.link]p6: 7799 /// Two declarations [for a function or variable] with C language linkage 7800 /// with the same name that appear in different scopes refer to the same 7801 /// [entity]. An entity with C language linkage shall not be declared with 7802 /// the same name as an entity in global scope. 7803 template<typename T> 7804 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7805 LookupResult &Previous) { 7806 if (!S.getLangOpts().CPlusPlus) { 7807 // In C, when declaring a global variable, look for a corresponding 'extern' 7808 // variable declared in function scope. We don't need this in C++, because 7809 // we find local extern decls in the surrounding file-scope DeclContext. 7810 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7811 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7812 Previous.clear(); 7813 Previous.addDecl(Prev); 7814 return true; 7815 } 7816 } 7817 return false; 7818 } 7819 7820 // A declaration in the translation unit can conflict with an extern "C" 7821 // declaration. 7822 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7823 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7824 7825 // An extern "C" declaration can conflict with a declaration in the 7826 // translation unit or can be a redeclaration of an extern "C" declaration 7827 // in another scope. 7828 if (isIncompleteDeclExternC(S,ND)) 7829 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7830 7831 // Neither global nor extern "C": nothing to do. 7832 return false; 7833 } 7834 7835 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7836 // If the decl is already known invalid, don't check it. 7837 if (NewVD->isInvalidDecl()) 7838 return; 7839 7840 QualType T = NewVD->getType(); 7841 7842 // Defer checking an 'auto' type until its initializer is attached. 7843 if (T->isUndeducedType()) 7844 return; 7845 7846 if (NewVD->hasAttrs()) 7847 CheckAlignasUnderalignment(NewVD); 7848 7849 if (T->isObjCObjectType()) { 7850 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7851 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7852 T = Context.getObjCObjectPointerType(T); 7853 NewVD->setType(T); 7854 } 7855 7856 // Emit an error if an address space was applied to decl with local storage. 7857 // This includes arrays of objects with address space qualifiers, but not 7858 // automatic variables that point to other address spaces. 7859 // ISO/IEC TR 18037 S5.1.2 7860 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7861 T.getAddressSpace() != LangAS::Default) { 7862 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7863 NewVD->setInvalidDecl(); 7864 return; 7865 } 7866 7867 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7868 // scope. 7869 if (getLangOpts().OpenCLVersion == 120 && 7870 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7871 NewVD->isStaticLocal()) { 7872 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7873 NewVD->setInvalidDecl(); 7874 return; 7875 } 7876 7877 if (getLangOpts().OpenCL) { 7878 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7879 if (NewVD->hasAttr<BlocksAttr>()) { 7880 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7881 return; 7882 } 7883 7884 if (T->isBlockPointerType()) { 7885 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7886 // can't use 'extern' storage class. 7887 if (!T.isConstQualified()) { 7888 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7889 << 0 /*const*/; 7890 NewVD->setInvalidDecl(); 7891 return; 7892 } 7893 if (NewVD->hasExternalStorage()) { 7894 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7895 NewVD->setInvalidDecl(); 7896 return; 7897 } 7898 } 7899 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7900 // __constant address space. 7901 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7902 // variables inside a function can also be declared in the global 7903 // address space. 7904 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7905 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7906 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7907 NewVD->hasExternalStorage()) { 7908 if (!T->isSamplerT() && 7909 !T->isDependentType() && 7910 !(T.getAddressSpace() == LangAS::opencl_constant || 7911 (T.getAddressSpace() == LangAS::opencl_global && 7912 (getLangOpts().OpenCLVersion == 200 || 7913 getLangOpts().OpenCLCPlusPlus)))) { 7914 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7915 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7916 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7917 << Scope << "global or constant"; 7918 else 7919 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7920 << Scope << "constant"; 7921 NewVD->setInvalidDecl(); 7922 return; 7923 } 7924 } else { 7925 if (T.getAddressSpace() == LangAS::opencl_global) { 7926 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7927 << 1 /*is any function*/ << "global"; 7928 NewVD->setInvalidDecl(); 7929 return; 7930 } 7931 if (T.getAddressSpace() == LangAS::opencl_constant || 7932 T.getAddressSpace() == LangAS::opencl_local) { 7933 FunctionDecl *FD = getCurFunctionDecl(); 7934 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7935 // in functions. 7936 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7937 if (T.getAddressSpace() == LangAS::opencl_constant) 7938 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7939 << 0 /*non-kernel only*/ << "constant"; 7940 else 7941 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7942 << 0 /*non-kernel only*/ << "local"; 7943 NewVD->setInvalidDecl(); 7944 return; 7945 } 7946 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7947 // in the outermost scope of a kernel function. 7948 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7949 if (!getCurScope()->isFunctionScope()) { 7950 if (T.getAddressSpace() == LangAS::opencl_constant) 7951 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7952 << "constant"; 7953 else 7954 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7955 << "local"; 7956 NewVD->setInvalidDecl(); 7957 return; 7958 } 7959 } 7960 } else if (T.getAddressSpace() != LangAS::opencl_private && 7961 // If we are parsing a template we didn't deduce an addr 7962 // space yet. 7963 T.getAddressSpace() != LangAS::Default) { 7964 // Do not allow other address spaces on automatic variable. 7965 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7966 NewVD->setInvalidDecl(); 7967 return; 7968 } 7969 } 7970 } 7971 7972 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7973 && !NewVD->hasAttr<BlocksAttr>()) { 7974 if (getLangOpts().getGC() != LangOptions::NonGC) 7975 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7976 else { 7977 assert(!getLangOpts().ObjCAutoRefCount); 7978 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7979 } 7980 } 7981 7982 bool isVM = T->isVariablyModifiedType(); 7983 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7984 NewVD->hasAttr<BlocksAttr>()) 7985 setFunctionHasBranchProtectedScope(); 7986 7987 if ((isVM && NewVD->hasLinkage()) || 7988 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7989 bool SizeIsNegative; 7990 llvm::APSInt Oversized; 7991 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7992 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7993 QualType FixedT; 7994 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7995 FixedT = FixedTInfo->getType(); 7996 else if (FixedTInfo) { 7997 // Type and type-as-written are canonically different. We need to fix up 7998 // both types separately. 7999 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8000 Oversized); 8001 } 8002 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8003 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8004 // FIXME: This won't give the correct result for 8005 // int a[10][n]; 8006 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8007 8008 if (NewVD->isFileVarDecl()) 8009 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8010 << SizeRange; 8011 else if (NewVD->isStaticLocal()) 8012 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8013 << SizeRange; 8014 else 8015 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8016 << SizeRange; 8017 NewVD->setInvalidDecl(); 8018 return; 8019 } 8020 8021 if (!FixedTInfo) { 8022 if (NewVD->isFileVarDecl()) 8023 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8024 else 8025 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8026 NewVD->setInvalidDecl(); 8027 return; 8028 } 8029 8030 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8031 NewVD->setType(FixedT); 8032 NewVD->setTypeSourceInfo(FixedTInfo); 8033 } 8034 8035 if (T->isVoidType()) { 8036 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8037 // of objects and functions. 8038 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8039 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8040 << T; 8041 NewVD->setInvalidDecl(); 8042 return; 8043 } 8044 } 8045 8046 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8047 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8048 NewVD->setInvalidDecl(); 8049 return; 8050 } 8051 8052 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8053 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8054 NewVD->setInvalidDecl(); 8055 return; 8056 } 8057 8058 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8059 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8060 NewVD->setInvalidDecl(); 8061 return; 8062 } 8063 8064 if (NewVD->isConstexpr() && !T->isDependentType() && 8065 RequireLiteralType(NewVD->getLocation(), T, 8066 diag::err_constexpr_var_non_literal)) { 8067 NewVD->setInvalidDecl(); 8068 return; 8069 } 8070 8071 // PPC MMA non-pointer types are not allowed as non-local variable types. 8072 if (Context.getTargetInfo().getTriple().isPPC64() && 8073 !NewVD->isLocalVarDecl() && 8074 CheckPPCMMAType(T, NewVD->getLocation())) { 8075 NewVD->setInvalidDecl(); 8076 return; 8077 } 8078 } 8079 8080 /// Perform semantic checking on a newly-created variable 8081 /// declaration. 8082 /// 8083 /// This routine performs all of the type-checking required for a 8084 /// variable declaration once it has been built. It is used both to 8085 /// check variables after they have been parsed and their declarators 8086 /// have been translated into a declaration, and to check variables 8087 /// that have been instantiated from a template. 8088 /// 8089 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8090 /// 8091 /// Returns true if the variable declaration is a redeclaration. 8092 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8093 CheckVariableDeclarationType(NewVD); 8094 8095 // If the decl is already known invalid, don't check it. 8096 if (NewVD->isInvalidDecl()) 8097 return false; 8098 8099 // If we did not find anything by this name, look for a non-visible 8100 // extern "C" declaration with the same name. 8101 if (Previous.empty() && 8102 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8103 Previous.setShadowed(); 8104 8105 if (!Previous.empty()) { 8106 MergeVarDecl(NewVD, Previous); 8107 return true; 8108 } 8109 return false; 8110 } 8111 8112 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8113 /// and if so, check that it's a valid override and remember it. 8114 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8115 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8116 8117 // Look for methods in base classes that this method might override. 8118 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8119 /*DetectVirtual=*/false); 8120 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8121 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8122 DeclarationName Name = MD->getDeclName(); 8123 8124 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8125 // We really want to find the base class destructor here. 8126 QualType T = Context.getTypeDeclType(BaseRecord); 8127 CanQualType CT = Context.getCanonicalType(T); 8128 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8129 } 8130 8131 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8132 CXXMethodDecl *BaseMD = 8133 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8134 if (!BaseMD || !BaseMD->isVirtual() || 8135 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8136 /*ConsiderCudaAttrs=*/true, 8137 // C++2a [class.virtual]p2 does not consider requires 8138 // clauses when overriding. 8139 /*ConsiderRequiresClauses=*/false)) 8140 continue; 8141 8142 if (Overridden.insert(BaseMD).second) { 8143 MD->addOverriddenMethod(BaseMD); 8144 CheckOverridingFunctionReturnType(MD, BaseMD); 8145 CheckOverridingFunctionAttributes(MD, BaseMD); 8146 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8147 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8148 } 8149 8150 // A method can only override one function from each base class. We 8151 // don't track indirectly overridden methods from bases of bases. 8152 return true; 8153 } 8154 8155 return false; 8156 }; 8157 8158 DC->lookupInBases(VisitBase, Paths); 8159 return !Overridden.empty(); 8160 } 8161 8162 namespace { 8163 // Struct for holding all of the extra arguments needed by 8164 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8165 struct ActOnFDArgs { 8166 Scope *S; 8167 Declarator &D; 8168 MultiTemplateParamsArg TemplateParamLists; 8169 bool AddToScope; 8170 }; 8171 } // end anonymous namespace 8172 8173 namespace { 8174 8175 // Callback to only accept typo corrections that have a non-zero edit distance. 8176 // Also only accept corrections that have the same parent decl. 8177 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8178 public: 8179 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8180 CXXRecordDecl *Parent) 8181 : Context(Context), OriginalFD(TypoFD), 8182 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8183 8184 bool ValidateCandidate(const TypoCorrection &candidate) override { 8185 if (candidate.getEditDistance() == 0) 8186 return false; 8187 8188 SmallVector<unsigned, 1> MismatchedParams; 8189 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8190 CDeclEnd = candidate.end(); 8191 CDecl != CDeclEnd; ++CDecl) { 8192 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8193 8194 if (FD && !FD->hasBody() && 8195 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8196 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8197 CXXRecordDecl *Parent = MD->getParent(); 8198 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8199 return true; 8200 } else if (!ExpectedParent) { 8201 return true; 8202 } 8203 } 8204 } 8205 8206 return false; 8207 } 8208 8209 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8210 return std::make_unique<DifferentNameValidatorCCC>(*this); 8211 } 8212 8213 private: 8214 ASTContext &Context; 8215 FunctionDecl *OriginalFD; 8216 CXXRecordDecl *ExpectedParent; 8217 }; 8218 8219 } // end anonymous namespace 8220 8221 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8222 TypoCorrectedFunctionDefinitions.insert(F); 8223 } 8224 8225 /// Generate diagnostics for an invalid function redeclaration. 8226 /// 8227 /// This routine handles generating the diagnostic messages for an invalid 8228 /// function redeclaration, including finding possible similar declarations 8229 /// or performing typo correction if there are no previous declarations with 8230 /// the same name. 8231 /// 8232 /// Returns a NamedDecl iff typo correction was performed and substituting in 8233 /// the new declaration name does not cause new errors. 8234 static NamedDecl *DiagnoseInvalidRedeclaration( 8235 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8236 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8237 DeclarationName Name = NewFD->getDeclName(); 8238 DeclContext *NewDC = NewFD->getDeclContext(); 8239 SmallVector<unsigned, 1> MismatchedParams; 8240 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8241 TypoCorrection Correction; 8242 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8243 unsigned DiagMsg = 8244 IsLocalFriend ? diag::err_no_matching_local_friend : 8245 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8246 diag::err_member_decl_does_not_match; 8247 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8248 IsLocalFriend ? Sema::LookupLocalFriendName 8249 : Sema::LookupOrdinaryName, 8250 Sema::ForVisibleRedeclaration); 8251 8252 NewFD->setInvalidDecl(); 8253 if (IsLocalFriend) 8254 SemaRef.LookupName(Prev, S); 8255 else 8256 SemaRef.LookupQualifiedName(Prev, NewDC); 8257 assert(!Prev.isAmbiguous() && 8258 "Cannot have an ambiguity in previous-declaration lookup"); 8259 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8260 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8261 MD ? MD->getParent() : nullptr); 8262 if (!Prev.empty()) { 8263 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8264 Func != FuncEnd; ++Func) { 8265 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8266 if (FD && 8267 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8268 // Add 1 to the index so that 0 can mean the mismatch didn't 8269 // involve a parameter 8270 unsigned ParamNum = 8271 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8272 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8273 } 8274 } 8275 // If the qualified name lookup yielded nothing, try typo correction 8276 } else if ((Correction = SemaRef.CorrectTypo( 8277 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8278 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8279 IsLocalFriend ? nullptr : NewDC))) { 8280 // Set up everything for the call to ActOnFunctionDeclarator 8281 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8282 ExtraArgs.D.getIdentifierLoc()); 8283 Previous.clear(); 8284 Previous.setLookupName(Correction.getCorrection()); 8285 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8286 CDeclEnd = Correction.end(); 8287 CDecl != CDeclEnd; ++CDecl) { 8288 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8289 if (FD && !FD->hasBody() && 8290 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8291 Previous.addDecl(FD); 8292 } 8293 } 8294 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8295 8296 NamedDecl *Result; 8297 // Retry building the function declaration with the new previous 8298 // declarations, and with errors suppressed. 8299 { 8300 // Trap errors. 8301 Sema::SFINAETrap Trap(SemaRef); 8302 8303 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8304 // pieces need to verify the typo-corrected C++ declaration and hopefully 8305 // eliminate the need for the parameter pack ExtraArgs. 8306 Result = SemaRef.ActOnFunctionDeclarator( 8307 ExtraArgs.S, ExtraArgs.D, 8308 Correction.getCorrectionDecl()->getDeclContext(), 8309 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8310 ExtraArgs.AddToScope); 8311 8312 if (Trap.hasErrorOccurred()) 8313 Result = nullptr; 8314 } 8315 8316 if (Result) { 8317 // Determine which correction we picked. 8318 Decl *Canonical = Result->getCanonicalDecl(); 8319 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8320 I != E; ++I) 8321 if ((*I)->getCanonicalDecl() == Canonical) 8322 Correction.setCorrectionDecl(*I); 8323 8324 // Let Sema know about the correction. 8325 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8326 SemaRef.diagnoseTypo( 8327 Correction, 8328 SemaRef.PDiag(IsLocalFriend 8329 ? diag::err_no_matching_local_friend_suggest 8330 : diag::err_member_decl_does_not_match_suggest) 8331 << Name << NewDC << IsDefinition); 8332 return Result; 8333 } 8334 8335 // Pretend the typo correction never occurred 8336 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8337 ExtraArgs.D.getIdentifierLoc()); 8338 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8339 Previous.clear(); 8340 Previous.setLookupName(Name); 8341 } 8342 8343 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8344 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8345 8346 bool NewFDisConst = false; 8347 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8348 NewFDisConst = NewMD->isConst(); 8349 8350 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8351 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8352 NearMatch != NearMatchEnd; ++NearMatch) { 8353 FunctionDecl *FD = NearMatch->first; 8354 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8355 bool FDisConst = MD && MD->isConst(); 8356 bool IsMember = MD || !IsLocalFriend; 8357 8358 // FIXME: These notes are poorly worded for the local friend case. 8359 if (unsigned Idx = NearMatch->second) { 8360 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8361 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8362 if (Loc.isInvalid()) Loc = FD->getLocation(); 8363 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8364 : diag::note_local_decl_close_param_match) 8365 << Idx << FDParam->getType() 8366 << NewFD->getParamDecl(Idx - 1)->getType(); 8367 } else if (FDisConst != NewFDisConst) { 8368 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8369 << NewFDisConst << FD->getSourceRange().getEnd(); 8370 } else 8371 SemaRef.Diag(FD->getLocation(), 8372 IsMember ? diag::note_member_def_close_match 8373 : diag::note_local_decl_close_match); 8374 } 8375 return nullptr; 8376 } 8377 8378 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8379 switch (D.getDeclSpec().getStorageClassSpec()) { 8380 default: llvm_unreachable("Unknown storage class!"); 8381 case DeclSpec::SCS_auto: 8382 case DeclSpec::SCS_register: 8383 case DeclSpec::SCS_mutable: 8384 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8385 diag::err_typecheck_sclass_func); 8386 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8387 D.setInvalidType(); 8388 break; 8389 case DeclSpec::SCS_unspecified: break; 8390 case DeclSpec::SCS_extern: 8391 if (D.getDeclSpec().isExternInLinkageSpec()) 8392 return SC_None; 8393 return SC_Extern; 8394 case DeclSpec::SCS_static: { 8395 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8396 // C99 6.7.1p5: 8397 // The declaration of an identifier for a function that has 8398 // block scope shall have no explicit storage-class specifier 8399 // other than extern 8400 // See also (C++ [dcl.stc]p4). 8401 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8402 diag::err_static_block_func); 8403 break; 8404 } else 8405 return SC_Static; 8406 } 8407 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8408 } 8409 8410 // No explicit storage class has already been returned 8411 return SC_None; 8412 } 8413 8414 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8415 DeclContext *DC, QualType &R, 8416 TypeSourceInfo *TInfo, 8417 StorageClass SC, 8418 bool &IsVirtualOkay) { 8419 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8420 DeclarationName Name = NameInfo.getName(); 8421 8422 FunctionDecl *NewFD = nullptr; 8423 bool isInline = D.getDeclSpec().isInlineSpecified(); 8424 8425 if (!SemaRef.getLangOpts().CPlusPlus) { 8426 // Determine whether the function was written with a 8427 // prototype. This true when: 8428 // - there is a prototype in the declarator, or 8429 // - the type R of the function is some kind of typedef or other non- 8430 // attributed reference to a type name (which eventually refers to a 8431 // function type). 8432 bool HasPrototype = 8433 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8434 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8435 8436 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8437 R, TInfo, SC, isInline, HasPrototype, 8438 ConstexprSpecKind::Unspecified, 8439 /*TrailingRequiresClause=*/nullptr); 8440 if (D.isInvalidType()) 8441 NewFD->setInvalidDecl(); 8442 8443 return NewFD; 8444 } 8445 8446 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8447 8448 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8449 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8450 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8451 diag::err_constexpr_wrong_decl_kind) 8452 << static_cast<int>(ConstexprKind); 8453 ConstexprKind = ConstexprSpecKind::Unspecified; 8454 D.getMutableDeclSpec().ClearConstexprSpec(); 8455 } 8456 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8457 8458 // Check that the return type is not an abstract class type. 8459 // For record types, this is done by the AbstractClassUsageDiagnoser once 8460 // the class has been completely parsed. 8461 if (!DC->isRecord() && 8462 SemaRef.RequireNonAbstractType( 8463 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8464 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8465 D.setInvalidType(); 8466 8467 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8468 // This is a C++ constructor declaration. 8469 assert(DC->isRecord() && 8470 "Constructors can only be declared in a member context"); 8471 8472 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8473 return CXXConstructorDecl::Create( 8474 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8475 TInfo, ExplicitSpecifier, isInline, 8476 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8477 TrailingRequiresClause); 8478 8479 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8480 // This is a C++ destructor declaration. 8481 if (DC->isRecord()) { 8482 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8483 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8484 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8485 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8486 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8487 TrailingRequiresClause); 8488 8489 // If the destructor needs an implicit exception specification, set it 8490 // now. FIXME: It'd be nice to be able to create the right type to start 8491 // with, but the type needs to reference the destructor declaration. 8492 if (SemaRef.getLangOpts().CPlusPlus11) 8493 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8494 8495 IsVirtualOkay = true; 8496 return NewDD; 8497 8498 } else { 8499 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8500 D.setInvalidType(); 8501 8502 // Create a FunctionDecl to satisfy the function definition parsing 8503 // code path. 8504 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8505 D.getIdentifierLoc(), Name, R, TInfo, SC, 8506 isInline, 8507 /*hasPrototype=*/true, ConstexprKind, 8508 TrailingRequiresClause); 8509 } 8510 8511 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8512 if (!DC->isRecord()) { 8513 SemaRef.Diag(D.getIdentifierLoc(), 8514 diag::err_conv_function_not_member); 8515 return nullptr; 8516 } 8517 8518 SemaRef.CheckConversionDeclarator(D, R, SC); 8519 if (D.isInvalidType()) 8520 return nullptr; 8521 8522 IsVirtualOkay = true; 8523 return CXXConversionDecl::Create( 8524 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8525 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8526 TrailingRequiresClause); 8527 8528 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8529 if (TrailingRequiresClause) 8530 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8531 diag::err_trailing_requires_clause_on_deduction_guide) 8532 << TrailingRequiresClause->getSourceRange(); 8533 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8534 8535 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8536 ExplicitSpecifier, NameInfo, R, TInfo, 8537 D.getEndLoc()); 8538 } else if (DC->isRecord()) { 8539 // If the name of the function is the same as the name of the record, 8540 // then this must be an invalid constructor that has a return type. 8541 // (The parser checks for a return type and makes the declarator a 8542 // constructor if it has no return type). 8543 if (Name.getAsIdentifierInfo() && 8544 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8545 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8546 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8547 << SourceRange(D.getIdentifierLoc()); 8548 return nullptr; 8549 } 8550 8551 // This is a C++ method declaration. 8552 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8553 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8554 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8555 TrailingRequiresClause); 8556 IsVirtualOkay = !Ret->isStatic(); 8557 return Ret; 8558 } else { 8559 bool isFriend = 8560 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8561 if (!isFriend && SemaRef.CurContext->isRecord()) 8562 return nullptr; 8563 8564 // Determine whether the function was written with a 8565 // prototype. This true when: 8566 // - we're in C++ (where every function has a prototype), 8567 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8568 R, TInfo, SC, isInline, true /*HasPrototype*/, 8569 ConstexprKind, TrailingRequiresClause); 8570 } 8571 } 8572 8573 enum OpenCLParamType { 8574 ValidKernelParam, 8575 PtrPtrKernelParam, 8576 PtrKernelParam, 8577 InvalidAddrSpacePtrKernelParam, 8578 InvalidKernelParam, 8579 RecordKernelParam 8580 }; 8581 8582 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8583 // Size dependent types are just typedefs to normal integer types 8584 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8585 // integers other than by their names. 8586 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8587 8588 // Remove typedefs one by one until we reach a typedef 8589 // for a size dependent type. 8590 QualType DesugaredTy = Ty; 8591 do { 8592 ArrayRef<StringRef> Names(SizeTypeNames); 8593 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8594 if (Names.end() != Match) 8595 return true; 8596 8597 Ty = DesugaredTy; 8598 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8599 } while (DesugaredTy != Ty); 8600 8601 return false; 8602 } 8603 8604 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8605 if (PT->isPointerType()) { 8606 QualType PointeeType = PT->getPointeeType(); 8607 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8608 PointeeType.getAddressSpace() == LangAS::opencl_private || 8609 PointeeType.getAddressSpace() == LangAS::Default) 8610 return InvalidAddrSpacePtrKernelParam; 8611 8612 if (PointeeType->isPointerType()) { 8613 // This is a pointer to pointer parameter. 8614 // Recursively check inner type. 8615 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8616 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8617 ParamKind == InvalidKernelParam) 8618 return ParamKind; 8619 8620 return PtrPtrKernelParam; 8621 } 8622 return PtrKernelParam; 8623 } 8624 8625 // OpenCL v1.2 s6.9.k: 8626 // Arguments to kernel functions in a program cannot be declared with the 8627 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8628 // uintptr_t or a struct and/or union that contain fields declared to be one 8629 // of these built-in scalar types. 8630 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8631 return InvalidKernelParam; 8632 8633 if (PT->isImageType()) 8634 return PtrKernelParam; 8635 8636 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8637 return InvalidKernelParam; 8638 8639 // OpenCL extension spec v1.2 s9.5: 8640 // This extension adds support for half scalar and vector types as built-in 8641 // types that can be used for arithmetic operations, conversions etc. 8642 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8643 return InvalidKernelParam; 8644 8645 if (PT->isRecordType()) 8646 return RecordKernelParam; 8647 8648 // Look into an array argument to check if it has a forbidden type. 8649 if (PT->isArrayType()) { 8650 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8651 // Call ourself to check an underlying type of an array. Since the 8652 // getPointeeOrArrayElementType returns an innermost type which is not an 8653 // array, this recursive call only happens once. 8654 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8655 } 8656 8657 return ValidKernelParam; 8658 } 8659 8660 static void checkIsValidOpenCLKernelParameter( 8661 Sema &S, 8662 Declarator &D, 8663 ParmVarDecl *Param, 8664 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8665 QualType PT = Param->getType(); 8666 8667 // Cache the valid types we encounter to avoid rechecking structs that are 8668 // used again 8669 if (ValidTypes.count(PT.getTypePtr())) 8670 return; 8671 8672 switch (getOpenCLKernelParameterType(S, PT)) { 8673 case PtrPtrKernelParam: 8674 // OpenCL v3.0 s6.11.a: 8675 // A kernel function argument cannot be declared as a pointer to a pointer 8676 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8677 if (S.getLangOpts().OpenCLVersion < 120 && 8678 !S.getLangOpts().OpenCLCPlusPlus) { 8679 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8680 D.setInvalidType(); 8681 return; 8682 } 8683 8684 ValidTypes.insert(PT.getTypePtr()); 8685 return; 8686 8687 case InvalidAddrSpacePtrKernelParam: 8688 // OpenCL v1.0 s6.5: 8689 // __kernel function arguments declared to be a pointer of a type can point 8690 // to one of the following address spaces only : __global, __local or 8691 // __constant. 8692 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8693 D.setInvalidType(); 8694 return; 8695 8696 // OpenCL v1.2 s6.9.k: 8697 // Arguments to kernel functions in a program cannot be declared with the 8698 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8699 // uintptr_t or a struct and/or union that contain fields declared to be 8700 // one of these built-in scalar types. 8701 8702 case InvalidKernelParam: 8703 // OpenCL v1.2 s6.8 n: 8704 // A kernel function argument cannot be declared 8705 // of event_t type. 8706 // Do not diagnose half type since it is diagnosed as invalid argument 8707 // type for any function elsewhere. 8708 if (!PT->isHalfType()) { 8709 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8710 8711 // Explain what typedefs are involved. 8712 const TypedefType *Typedef = nullptr; 8713 while ((Typedef = PT->getAs<TypedefType>())) { 8714 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8715 // SourceLocation may be invalid for a built-in type. 8716 if (Loc.isValid()) 8717 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8718 PT = Typedef->desugar(); 8719 } 8720 } 8721 8722 D.setInvalidType(); 8723 return; 8724 8725 case PtrKernelParam: 8726 case ValidKernelParam: 8727 ValidTypes.insert(PT.getTypePtr()); 8728 return; 8729 8730 case RecordKernelParam: 8731 break; 8732 } 8733 8734 // Track nested structs we will inspect 8735 SmallVector<const Decl *, 4> VisitStack; 8736 8737 // Track where we are in the nested structs. Items will migrate from 8738 // VisitStack to HistoryStack as we do the DFS for bad field. 8739 SmallVector<const FieldDecl *, 4> HistoryStack; 8740 HistoryStack.push_back(nullptr); 8741 8742 // At this point we already handled everything except of a RecordType or 8743 // an ArrayType of a RecordType. 8744 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8745 const RecordType *RecTy = 8746 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8747 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8748 8749 VisitStack.push_back(RecTy->getDecl()); 8750 assert(VisitStack.back() && "First decl null?"); 8751 8752 do { 8753 const Decl *Next = VisitStack.pop_back_val(); 8754 if (!Next) { 8755 assert(!HistoryStack.empty()); 8756 // Found a marker, we have gone up a level 8757 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8758 ValidTypes.insert(Hist->getType().getTypePtr()); 8759 8760 continue; 8761 } 8762 8763 // Adds everything except the original parameter declaration (which is not a 8764 // field itself) to the history stack. 8765 const RecordDecl *RD; 8766 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8767 HistoryStack.push_back(Field); 8768 8769 QualType FieldTy = Field->getType(); 8770 // Other field types (known to be valid or invalid) are handled while we 8771 // walk around RecordDecl::fields(). 8772 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8773 "Unexpected type."); 8774 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8775 8776 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8777 } else { 8778 RD = cast<RecordDecl>(Next); 8779 } 8780 8781 // Add a null marker so we know when we've gone back up a level 8782 VisitStack.push_back(nullptr); 8783 8784 for (const auto *FD : RD->fields()) { 8785 QualType QT = FD->getType(); 8786 8787 if (ValidTypes.count(QT.getTypePtr())) 8788 continue; 8789 8790 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8791 if (ParamType == ValidKernelParam) 8792 continue; 8793 8794 if (ParamType == RecordKernelParam) { 8795 VisitStack.push_back(FD); 8796 continue; 8797 } 8798 8799 // OpenCL v1.2 s6.9.p: 8800 // Arguments to kernel functions that are declared to be a struct or union 8801 // do not allow OpenCL objects to be passed as elements of the struct or 8802 // union. 8803 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8804 ParamType == InvalidAddrSpacePtrKernelParam) { 8805 S.Diag(Param->getLocation(), 8806 diag::err_record_with_pointers_kernel_param) 8807 << PT->isUnionType() 8808 << PT; 8809 } else { 8810 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8811 } 8812 8813 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8814 << OrigRecDecl->getDeclName(); 8815 8816 // We have an error, now let's go back up through history and show where 8817 // the offending field came from 8818 for (ArrayRef<const FieldDecl *>::const_iterator 8819 I = HistoryStack.begin() + 1, 8820 E = HistoryStack.end(); 8821 I != E; ++I) { 8822 const FieldDecl *OuterField = *I; 8823 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8824 << OuterField->getType(); 8825 } 8826 8827 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8828 << QT->isPointerType() 8829 << QT; 8830 D.setInvalidType(); 8831 return; 8832 } 8833 } while (!VisitStack.empty()); 8834 } 8835 8836 /// Find the DeclContext in which a tag is implicitly declared if we see an 8837 /// elaborated type specifier in the specified context, and lookup finds 8838 /// nothing. 8839 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8840 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8841 DC = DC->getParent(); 8842 return DC; 8843 } 8844 8845 /// Find the Scope in which a tag is implicitly declared if we see an 8846 /// elaborated type specifier in the specified context, and lookup finds 8847 /// nothing. 8848 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8849 while (S->isClassScope() || 8850 (LangOpts.CPlusPlus && 8851 S->isFunctionPrototypeScope()) || 8852 ((S->getFlags() & Scope::DeclScope) == 0) || 8853 (S->getEntity() && S->getEntity()->isTransparentContext())) 8854 S = S->getParent(); 8855 return S; 8856 } 8857 8858 NamedDecl* 8859 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8860 TypeSourceInfo *TInfo, LookupResult &Previous, 8861 MultiTemplateParamsArg TemplateParamListsRef, 8862 bool &AddToScope) { 8863 QualType R = TInfo->getType(); 8864 8865 assert(R->isFunctionType()); 8866 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8867 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8868 8869 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8870 for (TemplateParameterList *TPL : TemplateParamListsRef) 8871 TemplateParamLists.push_back(TPL); 8872 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8873 if (!TemplateParamLists.empty() && 8874 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8875 TemplateParamLists.back() = Invented; 8876 else 8877 TemplateParamLists.push_back(Invented); 8878 } 8879 8880 // TODO: consider using NameInfo for diagnostic. 8881 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8882 DeclarationName Name = NameInfo.getName(); 8883 StorageClass SC = getFunctionStorageClass(*this, D); 8884 8885 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8886 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8887 diag::err_invalid_thread) 8888 << DeclSpec::getSpecifierName(TSCS); 8889 8890 if (D.isFirstDeclarationOfMember()) 8891 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8892 D.getIdentifierLoc()); 8893 8894 bool isFriend = false; 8895 FunctionTemplateDecl *FunctionTemplate = nullptr; 8896 bool isMemberSpecialization = false; 8897 bool isFunctionTemplateSpecialization = false; 8898 8899 bool isDependentClassScopeExplicitSpecialization = false; 8900 bool HasExplicitTemplateArgs = false; 8901 TemplateArgumentListInfo TemplateArgs; 8902 8903 bool isVirtualOkay = false; 8904 8905 DeclContext *OriginalDC = DC; 8906 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8907 8908 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8909 isVirtualOkay); 8910 if (!NewFD) return nullptr; 8911 8912 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8913 NewFD->setTopLevelDeclInObjCContainer(); 8914 8915 // Set the lexical context. If this is a function-scope declaration, or has a 8916 // C++ scope specifier, or is the object of a friend declaration, the lexical 8917 // context will be different from the semantic context. 8918 NewFD->setLexicalDeclContext(CurContext); 8919 8920 if (IsLocalExternDecl) 8921 NewFD->setLocalExternDecl(); 8922 8923 if (getLangOpts().CPlusPlus) { 8924 bool isInline = D.getDeclSpec().isInlineSpecified(); 8925 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8926 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8927 isFriend = D.getDeclSpec().isFriendSpecified(); 8928 if (isFriend && !isInline && D.isFunctionDefinition()) { 8929 // C++ [class.friend]p5 8930 // A function can be defined in a friend declaration of a 8931 // class . . . . Such a function is implicitly inline. 8932 NewFD->setImplicitlyInline(); 8933 } 8934 8935 // If this is a method defined in an __interface, and is not a constructor 8936 // or an overloaded operator, then set the pure flag (isVirtual will already 8937 // return true). 8938 if (const CXXRecordDecl *Parent = 8939 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8940 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8941 NewFD->setPure(true); 8942 8943 // C++ [class.union]p2 8944 // A union can have member functions, but not virtual functions. 8945 if (isVirtual && Parent->isUnion()) 8946 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8947 } 8948 8949 SetNestedNameSpecifier(*this, NewFD, D); 8950 isMemberSpecialization = false; 8951 isFunctionTemplateSpecialization = false; 8952 if (D.isInvalidType()) 8953 NewFD->setInvalidDecl(); 8954 8955 // Match up the template parameter lists with the scope specifier, then 8956 // determine whether we have a template or a template specialization. 8957 bool Invalid = false; 8958 TemplateParameterList *TemplateParams = 8959 MatchTemplateParametersToScopeSpecifier( 8960 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8961 D.getCXXScopeSpec(), 8962 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8963 ? D.getName().TemplateId 8964 : nullptr, 8965 TemplateParamLists, isFriend, isMemberSpecialization, 8966 Invalid); 8967 if (TemplateParams) { 8968 // Check that we can declare a template here. 8969 if (CheckTemplateDeclScope(S, TemplateParams)) 8970 NewFD->setInvalidDecl(); 8971 8972 if (TemplateParams->size() > 0) { 8973 // This is a function template 8974 8975 // A destructor cannot be a template. 8976 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8977 Diag(NewFD->getLocation(), diag::err_destructor_template); 8978 NewFD->setInvalidDecl(); 8979 } 8980 8981 // If we're adding a template to a dependent context, we may need to 8982 // rebuilding some of the types used within the template parameter list, 8983 // now that we know what the current instantiation is. 8984 if (DC->isDependentContext()) { 8985 ContextRAII SavedContext(*this, DC); 8986 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8987 Invalid = true; 8988 } 8989 8990 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8991 NewFD->getLocation(), 8992 Name, TemplateParams, 8993 NewFD); 8994 FunctionTemplate->setLexicalDeclContext(CurContext); 8995 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8996 8997 // For source fidelity, store the other template param lists. 8998 if (TemplateParamLists.size() > 1) { 8999 NewFD->setTemplateParameterListsInfo(Context, 9000 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9001 .drop_back(1)); 9002 } 9003 } else { 9004 // This is a function template specialization. 9005 isFunctionTemplateSpecialization = true; 9006 // For source fidelity, store all the template param lists. 9007 if (TemplateParamLists.size() > 0) 9008 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9009 9010 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9011 if (isFriend) { 9012 // We want to remove the "template<>", found here. 9013 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9014 9015 // If we remove the template<> and the name is not a 9016 // template-id, we're actually silently creating a problem: 9017 // the friend declaration will refer to an untemplated decl, 9018 // and clearly the user wants a template specialization. So 9019 // we need to insert '<>' after the name. 9020 SourceLocation InsertLoc; 9021 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9022 InsertLoc = D.getName().getSourceRange().getEnd(); 9023 InsertLoc = getLocForEndOfToken(InsertLoc); 9024 } 9025 9026 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9027 << Name << RemoveRange 9028 << FixItHint::CreateRemoval(RemoveRange) 9029 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9030 } 9031 } 9032 } else { 9033 // Check that we can declare a template here. 9034 if (!TemplateParamLists.empty() && isMemberSpecialization && 9035 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9036 NewFD->setInvalidDecl(); 9037 9038 // All template param lists were matched against the scope specifier: 9039 // this is NOT (an explicit specialization of) a template. 9040 if (TemplateParamLists.size() > 0) 9041 // For source fidelity, store all the template param lists. 9042 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9043 } 9044 9045 if (Invalid) { 9046 NewFD->setInvalidDecl(); 9047 if (FunctionTemplate) 9048 FunctionTemplate->setInvalidDecl(); 9049 } 9050 9051 // C++ [dcl.fct.spec]p5: 9052 // The virtual specifier shall only be used in declarations of 9053 // nonstatic class member functions that appear within a 9054 // member-specification of a class declaration; see 10.3. 9055 // 9056 if (isVirtual && !NewFD->isInvalidDecl()) { 9057 if (!isVirtualOkay) { 9058 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9059 diag::err_virtual_non_function); 9060 } else if (!CurContext->isRecord()) { 9061 // 'virtual' was specified outside of the class. 9062 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9063 diag::err_virtual_out_of_class) 9064 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9065 } else if (NewFD->getDescribedFunctionTemplate()) { 9066 // C++ [temp.mem]p3: 9067 // A member function template shall not be virtual. 9068 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9069 diag::err_virtual_member_function_template) 9070 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9071 } else { 9072 // Okay: Add virtual to the method. 9073 NewFD->setVirtualAsWritten(true); 9074 } 9075 9076 if (getLangOpts().CPlusPlus14 && 9077 NewFD->getReturnType()->isUndeducedType()) 9078 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9079 } 9080 9081 if (getLangOpts().CPlusPlus14 && 9082 (NewFD->isDependentContext() || 9083 (isFriend && CurContext->isDependentContext())) && 9084 NewFD->getReturnType()->isUndeducedType()) { 9085 // If the function template is referenced directly (for instance, as a 9086 // member of the current instantiation), pretend it has a dependent type. 9087 // This is not really justified by the standard, but is the only sane 9088 // thing to do. 9089 // FIXME: For a friend function, we have not marked the function as being 9090 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9091 const FunctionProtoType *FPT = 9092 NewFD->getType()->castAs<FunctionProtoType>(); 9093 QualType Result = 9094 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9095 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9096 FPT->getExtProtoInfo())); 9097 } 9098 9099 // C++ [dcl.fct.spec]p3: 9100 // The inline specifier shall not appear on a block scope function 9101 // declaration. 9102 if (isInline && !NewFD->isInvalidDecl()) { 9103 if (CurContext->isFunctionOrMethod()) { 9104 // 'inline' is not allowed on block scope function declaration. 9105 Diag(D.getDeclSpec().getInlineSpecLoc(), 9106 diag::err_inline_declaration_block_scope) << Name 9107 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9108 } 9109 } 9110 9111 // C++ [dcl.fct.spec]p6: 9112 // The explicit specifier shall be used only in the declaration of a 9113 // constructor or conversion function within its class definition; 9114 // see 12.3.1 and 12.3.2. 9115 if (hasExplicit && !NewFD->isInvalidDecl() && 9116 !isa<CXXDeductionGuideDecl>(NewFD)) { 9117 if (!CurContext->isRecord()) { 9118 // 'explicit' was specified outside of the class. 9119 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9120 diag::err_explicit_out_of_class) 9121 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9122 } else if (!isa<CXXConstructorDecl>(NewFD) && 9123 !isa<CXXConversionDecl>(NewFD)) { 9124 // 'explicit' was specified on a function that wasn't a constructor 9125 // or conversion function. 9126 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9127 diag::err_explicit_non_ctor_or_conv_function) 9128 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9129 } 9130 } 9131 9132 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9133 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9134 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9135 // are implicitly inline. 9136 NewFD->setImplicitlyInline(); 9137 9138 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9139 // be either constructors or to return a literal type. Therefore, 9140 // destructors cannot be declared constexpr. 9141 if (isa<CXXDestructorDecl>(NewFD) && 9142 (!getLangOpts().CPlusPlus20 || 9143 ConstexprKind == ConstexprSpecKind::Consteval)) { 9144 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9145 << static_cast<int>(ConstexprKind); 9146 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9147 ? ConstexprSpecKind::Unspecified 9148 : ConstexprSpecKind::Constexpr); 9149 } 9150 // C++20 [dcl.constexpr]p2: An allocation function, or a 9151 // deallocation function shall not be declared with the consteval 9152 // specifier. 9153 if (ConstexprKind == ConstexprSpecKind::Consteval && 9154 (NewFD->getOverloadedOperator() == OO_New || 9155 NewFD->getOverloadedOperator() == OO_Array_New || 9156 NewFD->getOverloadedOperator() == OO_Delete || 9157 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9158 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9159 diag::err_invalid_consteval_decl_kind) 9160 << NewFD; 9161 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9162 } 9163 } 9164 9165 // If __module_private__ was specified, mark the function accordingly. 9166 if (D.getDeclSpec().isModulePrivateSpecified()) { 9167 if (isFunctionTemplateSpecialization) { 9168 SourceLocation ModulePrivateLoc 9169 = D.getDeclSpec().getModulePrivateSpecLoc(); 9170 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9171 << 0 9172 << FixItHint::CreateRemoval(ModulePrivateLoc); 9173 } else { 9174 NewFD->setModulePrivate(); 9175 if (FunctionTemplate) 9176 FunctionTemplate->setModulePrivate(); 9177 } 9178 } 9179 9180 if (isFriend) { 9181 if (FunctionTemplate) { 9182 FunctionTemplate->setObjectOfFriendDecl(); 9183 FunctionTemplate->setAccess(AS_public); 9184 } 9185 NewFD->setObjectOfFriendDecl(); 9186 NewFD->setAccess(AS_public); 9187 } 9188 9189 // If a function is defined as defaulted or deleted, mark it as such now. 9190 // We'll do the relevant checks on defaulted / deleted functions later. 9191 switch (D.getFunctionDefinitionKind()) { 9192 case FunctionDefinitionKind::Declaration: 9193 case FunctionDefinitionKind::Definition: 9194 break; 9195 9196 case FunctionDefinitionKind::Defaulted: 9197 NewFD->setDefaulted(); 9198 break; 9199 9200 case FunctionDefinitionKind::Deleted: 9201 NewFD->setDeletedAsWritten(); 9202 break; 9203 } 9204 9205 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9206 D.isFunctionDefinition()) { 9207 // C++ [class.mfct]p2: 9208 // A member function may be defined (8.4) in its class definition, in 9209 // which case it is an inline member function (7.1.2) 9210 NewFD->setImplicitlyInline(); 9211 } 9212 9213 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9214 !CurContext->isRecord()) { 9215 // C++ [class.static]p1: 9216 // A data or function member of a class may be declared static 9217 // in a class definition, in which case it is a static member of 9218 // the class. 9219 9220 // Complain about the 'static' specifier if it's on an out-of-line 9221 // member function definition. 9222 9223 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9224 // member function template declaration and class member template 9225 // declaration (MSVC versions before 2015), warn about this. 9226 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9227 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9228 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9229 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9230 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9231 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9232 } 9233 9234 // C++11 [except.spec]p15: 9235 // A deallocation function with no exception-specification is treated 9236 // as if it were specified with noexcept(true). 9237 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9238 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9239 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9240 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9241 NewFD->setType(Context.getFunctionType( 9242 FPT->getReturnType(), FPT->getParamTypes(), 9243 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9244 } 9245 9246 // Filter out previous declarations that don't match the scope. 9247 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9248 D.getCXXScopeSpec().isNotEmpty() || 9249 isMemberSpecialization || 9250 isFunctionTemplateSpecialization); 9251 9252 // Handle GNU asm-label extension (encoded as an attribute). 9253 if (Expr *E = (Expr*) D.getAsmLabel()) { 9254 // The parser guarantees this is a string. 9255 StringLiteral *SE = cast<StringLiteral>(E); 9256 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9257 /*IsLiteralLabel=*/true, 9258 SE->getStrTokenLoc(0))); 9259 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9260 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9261 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9262 if (I != ExtnameUndeclaredIdentifiers.end()) { 9263 if (isDeclExternC(NewFD)) { 9264 NewFD->addAttr(I->second); 9265 ExtnameUndeclaredIdentifiers.erase(I); 9266 } else 9267 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9268 << /*Variable*/0 << NewFD; 9269 } 9270 } 9271 9272 // Copy the parameter declarations from the declarator D to the function 9273 // declaration NewFD, if they are available. First scavenge them into Params. 9274 SmallVector<ParmVarDecl*, 16> Params; 9275 unsigned FTIIdx; 9276 if (D.isFunctionDeclarator(FTIIdx)) { 9277 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9278 9279 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9280 // function that takes no arguments, not a function that takes a 9281 // single void argument. 9282 // We let through "const void" here because Sema::GetTypeForDeclarator 9283 // already checks for that case. 9284 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9285 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9286 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9287 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9288 Param->setDeclContext(NewFD); 9289 Params.push_back(Param); 9290 9291 if (Param->isInvalidDecl()) 9292 NewFD->setInvalidDecl(); 9293 } 9294 } 9295 9296 if (!getLangOpts().CPlusPlus) { 9297 // In C, find all the tag declarations from the prototype and move them 9298 // into the function DeclContext. Remove them from the surrounding tag 9299 // injection context of the function, which is typically but not always 9300 // the TU. 9301 DeclContext *PrototypeTagContext = 9302 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9303 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9304 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9305 9306 // We don't want to reparent enumerators. Look at their parent enum 9307 // instead. 9308 if (!TD) { 9309 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9310 TD = cast<EnumDecl>(ECD->getDeclContext()); 9311 } 9312 if (!TD) 9313 continue; 9314 DeclContext *TagDC = TD->getLexicalDeclContext(); 9315 if (!TagDC->containsDecl(TD)) 9316 continue; 9317 TagDC->removeDecl(TD); 9318 TD->setDeclContext(NewFD); 9319 NewFD->addDecl(TD); 9320 9321 // Preserve the lexical DeclContext if it is not the surrounding tag 9322 // injection context of the FD. In this example, the semantic context of 9323 // E will be f and the lexical context will be S, while both the 9324 // semantic and lexical contexts of S will be f: 9325 // void f(struct S { enum E { a } f; } s); 9326 if (TagDC != PrototypeTagContext) 9327 TD->setLexicalDeclContext(TagDC); 9328 } 9329 } 9330 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9331 // When we're declaring a function with a typedef, typeof, etc as in the 9332 // following example, we'll need to synthesize (unnamed) 9333 // parameters for use in the declaration. 9334 // 9335 // @code 9336 // typedef void fn(int); 9337 // fn f; 9338 // @endcode 9339 9340 // Synthesize a parameter for each argument type. 9341 for (const auto &AI : FT->param_types()) { 9342 ParmVarDecl *Param = 9343 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9344 Param->setScopeInfo(0, Params.size()); 9345 Params.push_back(Param); 9346 } 9347 } else { 9348 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9349 "Should not need args for typedef of non-prototype fn"); 9350 } 9351 9352 // Finally, we know we have the right number of parameters, install them. 9353 NewFD->setParams(Params); 9354 9355 if (D.getDeclSpec().isNoreturnSpecified()) 9356 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9357 D.getDeclSpec().getNoreturnSpecLoc(), 9358 AttributeCommonInfo::AS_Keyword)); 9359 9360 // Functions returning a variably modified type violate C99 6.7.5.2p2 9361 // because all functions have linkage. 9362 if (!NewFD->isInvalidDecl() && 9363 NewFD->getReturnType()->isVariablyModifiedType()) { 9364 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9365 NewFD->setInvalidDecl(); 9366 } 9367 9368 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9369 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9370 !NewFD->hasAttr<SectionAttr>()) 9371 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9372 Context, PragmaClangTextSection.SectionName, 9373 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9374 9375 // Apply an implicit SectionAttr if #pragma code_seg is active. 9376 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9377 !NewFD->hasAttr<SectionAttr>()) { 9378 NewFD->addAttr(SectionAttr::CreateImplicit( 9379 Context, CodeSegStack.CurrentValue->getString(), 9380 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9381 SectionAttr::Declspec_allocate)); 9382 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9383 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9384 ASTContext::PSF_Read, 9385 NewFD)) 9386 NewFD->dropAttr<SectionAttr>(); 9387 } 9388 9389 // Apply an implicit CodeSegAttr from class declspec or 9390 // apply an implicit SectionAttr from #pragma code_seg if active. 9391 if (!NewFD->hasAttr<CodeSegAttr>()) { 9392 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9393 D.isFunctionDefinition())) { 9394 NewFD->addAttr(SAttr); 9395 } 9396 } 9397 9398 // Handle attributes. 9399 ProcessDeclAttributes(S, NewFD, D); 9400 9401 if (getLangOpts().OpenCL) { 9402 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9403 // type declaration will generate a compilation error. 9404 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9405 if (AddressSpace != LangAS::Default) { 9406 Diag(NewFD->getLocation(), 9407 diag::err_opencl_return_value_with_address_space); 9408 NewFD->setInvalidDecl(); 9409 } 9410 } 9411 9412 if (!getLangOpts().CPlusPlus) { 9413 // Perform semantic checking on the function declaration. 9414 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9415 CheckMain(NewFD, D.getDeclSpec()); 9416 9417 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9418 CheckMSVCRTEntryPoint(NewFD); 9419 9420 if (!NewFD->isInvalidDecl()) 9421 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9422 isMemberSpecialization)); 9423 else if (!Previous.empty()) 9424 // Recover gracefully from an invalid redeclaration. 9425 D.setRedeclaration(true); 9426 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9427 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9428 "previous declaration set still overloaded"); 9429 9430 // Diagnose no-prototype function declarations with calling conventions that 9431 // don't support variadic calls. Only do this in C and do it after merging 9432 // possibly prototyped redeclarations. 9433 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9434 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9435 CallingConv CC = FT->getExtInfo().getCC(); 9436 if (!supportsVariadicCall(CC)) { 9437 // Windows system headers sometimes accidentally use stdcall without 9438 // (void) parameters, so we relax this to a warning. 9439 int DiagID = 9440 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9441 Diag(NewFD->getLocation(), DiagID) 9442 << FunctionType::getNameForCallConv(CC); 9443 } 9444 } 9445 9446 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9447 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9448 checkNonTrivialCUnion(NewFD->getReturnType(), 9449 NewFD->getReturnTypeSourceRange().getBegin(), 9450 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9451 } else { 9452 // C++11 [replacement.functions]p3: 9453 // The program's definitions shall not be specified as inline. 9454 // 9455 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9456 // 9457 // Suppress the diagnostic if the function is __attribute__((used)), since 9458 // that forces an external definition to be emitted. 9459 if (D.getDeclSpec().isInlineSpecified() && 9460 NewFD->isReplaceableGlobalAllocationFunction() && 9461 !NewFD->hasAttr<UsedAttr>()) 9462 Diag(D.getDeclSpec().getInlineSpecLoc(), 9463 diag::ext_operator_new_delete_declared_inline) 9464 << NewFD->getDeclName(); 9465 9466 // If the declarator is a template-id, translate the parser's template 9467 // argument list into our AST format. 9468 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9469 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9470 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9471 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9472 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9473 TemplateId->NumArgs); 9474 translateTemplateArguments(TemplateArgsPtr, 9475 TemplateArgs); 9476 9477 HasExplicitTemplateArgs = true; 9478 9479 if (NewFD->isInvalidDecl()) { 9480 HasExplicitTemplateArgs = false; 9481 } else if (FunctionTemplate) { 9482 // Function template with explicit template arguments. 9483 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9484 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9485 9486 HasExplicitTemplateArgs = false; 9487 } else { 9488 assert((isFunctionTemplateSpecialization || 9489 D.getDeclSpec().isFriendSpecified()) && 9490 "should have a 'template<>' for this decl"); 9491 // "friend void foo<>(int);" is an implicit specialization decl. 9492 isFunctionTemplateSpecialization = true; 9493 } 9494 } else if (isFriend && isFunctionTemplateSpecialization) { 9495 // This combination is only possible in a recovery case; the user 9496 // wrote something like: 9497 // template <> friend void foo(int); 9498 // which we're recovering from as if the user had written: 9499 // friend void foo<>(int); 9500 // Go ahead and fake up a template id. 9501 HasExplicitTemplateArgs = true; 9502 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9503 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9504 } 9505 9506 // We do not add HD attributes to specializations here because 9507 // they may have different constexpr-ness compared to their 9508 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9509 // may end up with different effective targets. Instead, a 9510 // specialization inherits its target attributes from its template 9511 // in the CheckFunctionTemplateSpecialization() call below. 9512 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9513 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9514 9515 // If it's a friend (and only if it's a friend), it's possible 9516 // that either the specialized function type or the specialized 9517 // template is dependent, and therefore matching will fail. In 9518 // this case, don't check the specialization yet. 9519 if (isFunctionTemplateSpecialization && isFriend && 9520 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9521 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9522 TemplateArgs.arguments()))) { 9523 assert(HasExplicitTemplateArgs && 9524 "friend function specialization without template args"); 9525 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9526 Previous)) 9527 NewFD->setInvalidDecl(); 9528 } else if (isFunctionTemplateSpecialization) { 9529 if (CurContext->isDependentContext() && CurContext->isRecord() 9530 && !isFriend) { 9531 isDependentClassScopeExplicitSpecialization = true; 9532 } else if (!NewFD->isInvalidDecl() && 9533 CheckFunctionTemplateSpecialization( 9534 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9535 Previous)) 9536 NewFD->setInvalidDecl(); 9537 9538 // C++ [dcl.stc]p1: 9539 // A storage-class-specifier shall not be specified in an explicit 9540 // specialization (14.7.3) 9541 FunctionTemplateSpecializationInfo *Info = 9542 NewFD->getTemplateSpecializationInfo(); 9543 if (Info && SC != SC_None) { 9544 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9545 Diag(NewFD->getLocation(), 9546 diag::err_explicit_specialization_inconsistent_storage_class) 9547 << SC 9548 << FixItHint::CreateRemoval( 9549 D.getDeclSpec().getStorageClassSpecLoc()); 9550 9551 else 9552 Diag(NewFD->getLocation(), 9553 diag::ext_explicit_specialization_storage_class) 9554 << FixItHint::CreateRemoval( 9555 D.getDeclSpec().getStorageClassSpecLoc()); 9556 } 9557 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9558 if (CheckMemberSpecialization(NewFD, Previous)) 9559 NewFD->setInvalidDecl(); 9560 } 9561 9562 // Perform semantic checking on the function declaration. 9563 if (!isDependentClassScopeExplicitSpecialization) { 9564 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9565 CheckMain(NewFD, D.getDeclSpec()); 9566 9567 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9568 CheckMSVCRTEntryPoint(NewFD); 9569 9570 if (!NewFD->isInvalidDecl()) 9571 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9572 isMemberSpecialization)); 9573 else if (!Previous.empty()) 9574 // Recover gracefully from an invalid redeclaration. 9575 D.setRedeclaration(true); 9576 } 9577 9578 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9579 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9580 "previous declaration set still overloaded"); 9581 9582 NamedDecl *PrincipalDecl = (FunctionTemplate 9583 ? cast<NamedDecl>(FunctionTemplate) 9584 : NewFD); 9585 9586 if (isFriend && NewFD->getPreviousDecl()) { 9587 AccessSpecifier Access = AS_public; 9588 if (!NewFD->isInvalidDecl()) 9589 Access = NewFD->getPreviousDecl()->getAccess(); 9590 9591 NewFD->setAccess(Access); 9592 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9593 } 9594 9595 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9596 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9597 PrincipalDecl->setNonMemberOperator(); 9598 9599 // If we have a function template, check the template parameter 9600 // list. This will check and merge default template arguments. 9601 if (FunctionTemplate) { 9602 FunctionTemplateDecl *PrevTemplate = 9603 FunctionTemplate->getPreviousDecl(); 9604 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9605 PrevTemplate ? PrevTemplate->getTemplateParameters() 9606 : nullptr, 9607 D.getDeclSpec().isFriendSpecified() 9608 ? (D.isFunctionDefinition() 9609 ? TPC_FriendFunctionTemplateDefinition 9610 : TPC_FriendFunctionTemplate) 9611 : (D.getCXXScopeSpec().isSet() && 9612 DC && DC->isRecord() && 9613 DC->isDependentContext()) 9614 ? TPC_ClassTemplateMember 9615 : TPC_FunctionTemplate); 9616 } 9617 9618 if (NewFD->isInvalidDecl()) { 9619 // Ignore all the rest of this. 9620 } else if (!D.isRedeclaration()) { 9621 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9622 AddToScope }; 9623 // Fake up an access specifier if it's supposed to be a class member. 9624 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9625 NewFD->setAccess(AS_public); 9626 9627 // Qualified decls generally require a previous declaration. 9628 if (D.getCXXScopeSpec().isSet()) { 9629 // ...with the major exception of templated-scope or 9630 // dependent-scope friend declarations. 9631 9632 // TODO: we currently also suppress this check in dependent 9633 // contexts because (1) the parameter depth will be off when 9634 // matching friend templates and (2) we might actually be 9635 // selecting a friend based on a dependent factor. But there 9636 // are situations where these conditions don't apply and we 9637 // can actually do this check immediately. 9638 // 9639 // Unless the scope is dependent, it's always an error if qualified 9640 // redeclaration lookup found nothing at all. Diagnose that now; 9641 // nothing will diagnose that error later. 9642 if (isFriend && 9643 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9644 (!Previous.empty() && CurContext->isDependentContext()))) { 9645 // ignore these 9646 } else { 9647 // The user tried to provide an out-of-line definition for a 9648 // function that is a member of a class or namespace, but there 9649 // was no such member function declared (C++ [class.mfct]p2, 9650 // C++ [namespace.memdef]p2). For example: 9651 // 9652 // class X { 9653 // void f() const; 9654 // }; 9655 // 9656 // void X::f() { } // ill-formed 9657 // 9658 // Complain about this problem, and attempt to suggest close 9659 // matches (e.g., those that differ only in cv-qualifiers and 9660 // whether the parameter types are references). 9661 9662 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9663 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9664 AddToScope = ExtraArgs.AddToScope; 9665 return Result; 9666 } 9667 } 9668 9669 // Unqualified local friend declarations are required to resolve 9670 // to something. 9671 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9672 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9673 *this, Previous, NewFD, ExtraArgs, true, S)) { 9674 AddToScope = ExtraArgs.AddToScope; 9675 return Result; 9676 } 9677 } 9678 } else if (!D.isFunctionDefinition() && 9679 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9680 !isFriend && !isFunctionTemplateSpecialization && 9681 !isMemberSpecialization) { 9682 // An out-of-line member function declaration must also be a 9683 // definition (C++ [class.mfct]p2). 9684 // Note that this is not the case for explicit specializations of 9685 // function templates or member functions of class templates, per 9686 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9687 // extension for compatibility with old SWIG code which likes to 9688 // generate them. 9689 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9690 << D.getCXXScopeSpec().getRange(); 9691 } 9692 } 9693 9694 // If this is the first declaration of a library builtin function, add 9695 // attributes as appropriate. 9696 if (!D.isRedeclaration() && 9697 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9698 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9699 if (unsigned BuiltinID = II->getBuiltinID()) { 9700 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9701 // Validate the type matches unless this builtin is specified as 9702 // matching regardless of its declared type. 9703 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9704 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9705 } else { 9706 ASTContext::GetBuiltinTypeError Error; 9707 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9708 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9709 9710 if (!Error && !BuiltinType.isNull() && 9711 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9712 NewFD->getType(), BuiltinType)) 9713 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9714 } 9715 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9716 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9717 // FIXME: We should consider this a builtin only in the std namespace. 9718 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9719 } 9720 } 9721 } 9722 } 9723 9724 ProcessPragmaWeak(S, NewFD); 9725 checkAttributesAfterMerging(*this, *NewFD); 9726 9727 AddKnownFunctionAttributes(NewFD); 9728 9729 if (NewFD->hasAttr<OverloadableAttr>() && 9730 !NewFD->getType()->getAs<FunctionProtoType>()) { 9731 Diag(NewFD->getLocation(), 9732 diag::err_attribute_overloadable_no_prototype) 9733 << NewFD; 9734 9735 // Turn this into a variadic function with no parameters. 9736 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9737 FunctionProtoType::ExtProtoInfo EPI( 9738 Context.getDefaultCallingConvention(true, false)); 9739 EPI.Variadic = true; 9740 EPI.ExtInfo = FT->getExtInfo(); 9741 9742 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9743 NewFD->setType(R); 9744 } 9745 9746 // If there's a #pragma GCC visibility in scope, and this isn't a class 9747 // member, set the visibility of this function. 9748 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9749 AddPushedVisibilityAttribute(NewFD); 9750 9751 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9752 // marking the function. 9753 AddCFAuditedAttribute(NewFD); 9754 9755 // If this is a function definition, check if we have to apply optnone due to 9756 // a pragma. 9757 if(D.isFunctionDefinition()) 9758 AddRangeBasedOptnone(NewFD); 9759 9760 // If this is the first declaration of an extern C variable, update 9761 // the map of such variables. 9762 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9763 isIncompleteDeclExternC(*this, NewFD)) 9764 RegisterLocallyScopedExternCDecl(NewFD, S); 9765 9766 // Set this FunctionDecl's range up to the right paren. 9767 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9768 9769 if (D.isRedeclaration() && !Previous.empty()) { 9770 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9771 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9772 isMemberSpecialization || 9773 isFunctionTemplateSpecialization, 9774 D.isFunctionDefinition()); 9775 } 9776 9777 if (getLangOpts().CUDA) { 9778 IdentifierInfo *II = NewFD->getIdentifier(); 9779 if (II && II->isStr(getCudaConfigureFuncName()) && 9780 !NewFD->isInvalidDecl() && 9781 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9782 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9783 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9784 << getCudaConfigureFuncName(); 9785 Context.setcudaConfigureCallDecl(NewFD); 9786 } 9787 9788 // Variadic functions, other than a *declaration* of printf, are not allowed 9789 // in device-side CUDA code, unless someone passed 9790 // -fcuda-allow-variadic-functions. 9791 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9792 (NewFD->hasAttr<CUDADeviceAttr>() || 9793 NewFD->hasAttr<CUDAGlobalAttr>()) && 9794 !(II && II->isStr("printf") && NewFD->isExternC() && 9795 !D.isFunctionDefinition())) { 9796 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9797 } 9798 } 9799 9800 MarkUnusedFileScopedDecl(NewFD); 9801 9802 9803 9804 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9805 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9806 if ((getLangOpts().OpenCLVersion >= 120) 9807 && (SC == SC_Static)) { 9808 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9809 D.setInvalidType(); 9810 } 9811 9812 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9813 if (!NewFD->getReturnType()->isVoidType()) { 9814 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9815 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9816 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9817 : FixItHint()); 9818 D.setInvalidType(); 9819 } 9820 9821 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9822 for (auto Param : NewFD->parameters()) 9823 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9824 9825 if (getLangOpts().OpenCLCPlusPlus) { 9826 if (DC->isRecord()) { 9827 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9828 D.setInvalidType(); 9829 } 9830 if (FunctionTemplate) { 9831 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9832 D.setInvalidType(); 9833 } 9834 } 9835 } 9836 9837 if (getLangOpts().CPlusPlus) { 9838 if (FunctionTemplate) { 9839 if (NewFD->isInvalidDecl()) 9840 FunctionTemplate->setInvalidDecl(); 9841 return FunctionTemplate; 9842 } 9843 9844 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9845 CompleteMemberSpecialization(NewFD, Previous); 9846 } 9847 9848 for (const ParmVarDecl *Param : NewFD->parameters()) { 9849 QualType PT = Param->getType(); 9850 9851 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9852 // types. 9853 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9854 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9855 QualType ElemTy = PipeTy->getElementType(); 9856 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9857 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9858 D.setInvalidType(); 9859 } 9860 } 9861 } 9862 } 9863 9864 // Here we have an function template explicit specialization at class scope. 9865 // The actual specialization will be postponed to template instatiation 9866 // time via the ClassScopeFunctionSpecializationDecl node. 9867 if (isDependentClassScopeExplicitSpecialization) { 9868 ClassScopeFunctionSpecializationDecl *NewSpec = 9869 ClassScopeFunctionSpecializationDecl::Create( 9870 Context, CurContext, NewFD->getLocation(), 9871 cast<CXXMethodDecl>(NewFD), 9872 HasExplicitTemplateArgs, TemplateArgs); 9873 CurContext->addDecl(NewSpec); 9874 AddToScope = false; 9875 } 9876 9877 // Diagnose availability attributes. Availability cannot be used on functions 9878 // that are run during load/unload. 9879 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9880 if (NewFD->hasAttr<ConstructorAttr>()) { 9881 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9882 << 1; 9883 NewFD->dropAttr<AvailabilityAttr>(); 9884 } 9885 if (NewFD->hasAttr<DestructorAttr>()) { 9886 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9887 << 2; 9888 NewFD->dropAttr<AvailabilityAttr>(); 9889 } 9890 } 9891 9892 // Diagnose no_builtin attribute on function declaration that are not a 9893 // definition. 9894 // FIXME: We should really be doing this in 9895 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9896 // the FunctionDecl and at this point of the code 9897 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9898 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9899 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9900 switch (D.getFunctionDefinitionKind()) { 9901 case FunctionDefinitionKind::Defaulted: 9902 case FunctionDefinitionKind::Deleted: 9903 Diag(NBA->getLocation(), 9904 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9905 << NBA->getSpelling(); 9906 break; 9907 case FunctionDefinitionKind::Declaration: 9908 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9909 << NBA->getSpelling(); 9910 break; 9911 case FunctionDefinitionKind::Definition: 9912 break; 9913 } 9914 9915 return NewFD; 9916 } 9917 9918 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9919 /// when __declspec(code_seg) "is applied to a class, all member functions of 9920 /// the class and nested classes -- this includes compiler-generated special 9921 /// member functions -- are put in the specified segment." 9922 /// The actual behavior is a little more complicated. The Microsoft compiler 9923 /// won't check outer classes if there is an active value from #pragma code_seg. 9924 /// The CodeSeg is always applied from the direct parent but only from outer 9925 /// classes when the #pragma code_seg stack is empty. See: 9926 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9927 /// available since MS has removed the page. 9928 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9929 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9930 if (!Method) 9931 return nullptr; 9932 const CXXRecordDecl *Parent = Method->getParent(); 9933 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9934 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9935 NewAttr->setImplicit(true); 9936 return NewAttr; 9937 } 9938 9939 // The Microsoft compiler won't check outer classes for the CodeSeg 9940 // when the #pragma code_seg stack is active. 9941 if (S.CodeSegStack.CurrentValue) 9942 return nullptr; 9943 9944 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9945 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9946 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9947 NewAttr->setImplicit(true); 9948 return NewAttr; 9949 } 9950 } 9951 return nullptr; 9952 } 9953 9954 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9955 /// containing class. Otherwise it will return implicit SectionAttr if the 9956 /// function is a definition and there is an active value on CodeSegStack 9957 /// (from the current #pragma code-seg value). 9958 /// 9959 /// \param FD Function being declared. 9960 /// \param IsDefinition Whether it is a definition or just a declarartion. 9961 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9962 /// nullptr if no attribute should be added. 9963 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9964 bool IsDefinition) { 9965 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9966 return A; 9967 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9968 CodeSegStack.CurrentValue) 9969 return SectionAttr::CreateImplicit( 9970 getASTContext(), CodeSegStack.CurrentValue->getString(), 9971 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9972 SectionAttr::Declspec_allocate); 9973 return nullptr; 9974 } 9975 9976 /// Determines if we can perform a correct type check for \p D as a 9977 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9978 /// best-effort check. 9979 /// 9980 /// \param NewD The new declaration. 9981 /// \param OldD The old declaration. 9982 /// \param NewT The portion of the type of the new declaration to check. 9983 /// \param OldT The portion of the type of the old declaration to check. 9984 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9985 QualType NewT, QualType OldT) { 9986 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9987 return true; 9988 9989 // For dependently-typed local extern declarations and friends, we can't 9990 // perform a correct type check in general until instantiation: 9991 // 9992 // int f(); 9993 // template<typename T> void g() { T f(); } 9994 // 9995 // (valid if g() is only instantiated with T = int). 9996 if (NewT->isDependentType() && 9997 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9998 return false; 9999 10000 // Similarly, if the previous declaration was a dependent local extern 10001 // declaration, we don't really know its type yet. 10002 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10003 return false; 10004 10005 return true; 10006 } 10007 10008 /// Checks if the new declaration declared in dependent context must be 10009 /// put in the same redeclaration chain as the specified declaration. 10010 /// 10011 /// \param D Declaration that is checked. 10012 /// \param PrevDecl Previous declaration found with proper lookup method for the 10013 /// same declaration name. 10014 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10015 /// belongs to. 10016 /// 10017 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10018 if (!D->getLexicalDeclContext()->isDependentContext()) 10019 return true; 10020 10021 // Don't chain dependent friend function definitions until instantiation, to 10022 // permit cases like 10023 // 10024 // void func(); 10025 // template<typename T> class C1 { friend void func() {} }; 10026 // template<typename T> class C2 { friend void func() {} }; 10027 // 10028 // ... which is valid if only one of C1 and C2 is ever instantiated. 10029 // 10030 // FIXME: This need only apply to function definitions. For now, we proxy 10031 // this by checking for a file-scope function. We do not want this to apply 10032 // to friend declarations nominating member functions, because that gets in 10033 // the way of access checks. 10034 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10035 return false; 10036 10037 auto *VD = dyn_cast<ValueDecl>(D); 10038 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10039 return !VD || !PrevVD || 10040 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10041 PrevVD->getType()); 10042 } 10043 10044 /// Check the target attribute of the function for MultiVersion 10045 /// validity. 10046 /// 10047 /// Returns true if there was an error, false otherwise. 10048 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10049 const auto *TA = FD->getAttr<TargetAttr>(); 10050 assert(TA && "MultiVersion Candidate requires a target attribute"); 10051 ParsedTargetAttr ParseInfo = TA->parse(); 10052 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10053 enum ErrType { Feature = 0, Architecture = 1 }; 10054 10055 if (!ParseInfo.Architecture.empty() && 10056 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10057 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10058 << Architecture << ParseInfo.Architecture; 10059 return true; 10060 } 10061 10062 for (const auto &Feat : ParseInfo.Features) { 10063 auto BareFeat = StringRef{Feat}.substr(1); 10064 if (Feat[0] == '-') { 10065 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10066 << Feature << ("no-" + BareFeat).str(); 10067 return true; 10068 } 10069 10070 if (!TargetInfo.validateCpuSupports(BareFeat) || 10071 !TargetInfo.isValidFeatureName(BareFeat)) { 10072 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10073 << Feature << BareFeat; 10074 return true; 10075 } 10076 } 10077 return false; 10078 } 10079 10080 // Provide a white-list of attributes that are allowed to be combined with 10081 // multiversion functions. 10082 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10083 MultiVersionKind MVType) { 10084 // Note: this list/diagnosis must match the list in 10085 // checkMultiversionAttributesAllSame. 10086 switch (Kind) { 10087 default: 10088 return false; 10089 case attr::Used: 10090 return MVType == MultiVersionKind::Target; 10091 case attr::NonNull: 10092 case attr::NoThrow: 10093 return true; 10094 } 10095 } 10096 10097 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10098 const FunctionDecl *FD, 10099 const FunctionDecl *CausedFD, 10100 MultiVersionKind MVType) { 10101 bool IsCPUSpecificCPUDispatchMVType = 10102 MVType == MultiVersionKind::CPUDispatch || 10103 MVType == MultiVersionKind::CPUSpecific; 10104 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10105 Sema &S, const Attr *A) { 10106 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10107 << IsCPUSpecificCPUDispatchMVType << A; 10108 if (CausedFD) 10109 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10110 return true; 10111 }; 10112 10113 for (const Attr *A : FD->attrs()) { 10114 switch (A->getKind()) { 10115 case attr::CPUDispatch: 10116 case attr::CPUSpecific: 10117 if (MVType != MultiVersionKind::CPUDispatch && 10118 MVType != MultiVersionKind::CPUSpecific) 10119 return Diagnose(S, A); 10120 break; 10121 case attr::Target: 10122 if (MVType != MultiVersionKind::Target) 10123 return Diagnose(S, A); 10124 break; 10125 default: 10126 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10127 return Diagnose(S, A); 10128 break; 10129 } 10130 } 10131 return false; 10132 } 10133 10134 bool Sema::areMultiversionVariantFunctionsCompatible( 10135 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10136 const PartialDiagnostic &NoProtoDiagID, 10137 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10138 const PartialDiagnosticAt &NoSupportDiagIDAt, 10139 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10140 bool ConstexprSupported, bool CLinkageMayDiffer) { 10141 enum DoesntSupport { 10142 FuncTemplates = 0, 10143 VirtFuncs = 1, 10144 DeducedReturn = 2, 10145 Constructors = 3, 10146 Destructors = 4, 10147 DeletedFuncs = 5, 10148 DefaultedFuncs = 6, 10149 ConstexprFuncs = 7, 10150 ConstevalFuncs = 8, 10151 }; 10152 enum Different { 10153 CallingConv = 0, 10154 ReturnType = 1, 10155 ConstexprSpec = 2, 10156 InlineSpec = 3, 10157 StorageClass = 4, 10158 Linkage = 5, 10159 }; 10160 10161 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10162 !OldFD->getType()->getAs<FunctionProtoType>()) { 10163 Diag(OldFD->getLocation(), NoProtoDiagID); 10164 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10165 return true; 10166 } 10167 10168 if (NoProtoDiagID.getDiagID() != 0 && 10169 !NewFD->getType()->getAs<FunctionProtoType>()) 10170 return Diag(NewFD->getLocation(), NoProtoDiagID); 10171 10172 if (!TemplatesSupported && 10173 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10174 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10175 << FuncTemplates; 10176 10177 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10178 if (NewCXXFD->isVirtual()) 10179 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10180 << VirtFuncs; 10181 10182 if (isa<CXXConstructorDecl>(NewCXXFD)) 10183 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10184 << Constructors; 10185 10186 if (isa<CXXDestructorDecl>(NewCXXFD)) 10187 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10188 << Destructors; 10189 } 10190 10191 if (NewFD->isDeleted()) 10192 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10193 << DeletedFuncs; 10194 10195 if (NewFD->isDefaulted()) 10196 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10197 << DefaultedFuncs; 10198 10199 if (!ConstexprSupported && NewFD->isConstexpr()) 10200 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10201 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10202 10203 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10204 const auto *NewType = cast<FunctionType>(NewQType); 10205 QualType NewReturnType = NewType->getReturnType(); 10206 10207 if (NewReturnType->isUndeducedType()) 10208 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10209 << DeducedReturn; 10210 10211 // Ensure the return type is identical. 10212 if (OldFD) { 10213 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10214 const auto *OldType = cast<FunctionType>(OldQType); 10215 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10216 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10217 10218 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10219 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10220 10221 QualType OldReturnType = OldType->getReturnType(); 10222 10223 if (OldReturnType != NewReturnType) 10224 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10225 10226 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10227 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10228 10229 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10230 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10231 10232 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10233 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10234 10235 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10236 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10237 10238 if (CheckEquivalentExceptionSpec( 10239 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10240 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10241 return true; 10242 } 10243 return false; 10244 } 10245 10246 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10247 const FunctionDecl *NewFD, 10248 bool CausesMV, 10249 MultiVersionKind MVType) { 10250 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10251 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10252 if (OldFD) 10253 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10254 return true; 10255 } 10256 10257 bool IsCPUSpecificCPUDispatchMVType = 10258 MVType == MultiVersionKind::CPUDispatch || 10259 MVType == MultiVersionKind::CPUSpecific; 10260 10261 if (CausesMV && OldFD && 10262 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10263 return true; 10264 10265 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10266 return true; 10267 10268 // Only allow transition to MultiVersion if it hasn't been used. 10269 if (OldFD && CausesMV && OldFD->isUsed(false)) 10270 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10271 10272 return S.areMultiversionVariantFunctionsCompatible( 10273 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10274 PartialDiagnosticAt(NewFD->getLocation(), 10275 S.PDiag(diag::note_multiversioning_caused_here)), 10276 PartialDiagnosticAt(NewFD->getLocation(), 10277 S.PDiag(diag::err_multiversion_doesnt_support) 10278 << IsCPUSpecificCPUDispatchMVType), 10279 PartialDiagnosticAt(NewFD->getLocation(), 10280 S.PDiag(diag::err_multiversion_diff)), 10281 /*TemplatesSupported=*/false, 10282 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10283 /*CLinkageMayDiffer=*/false); 10284 } 10285 10286 /// Check the validity of a multiversion function declaration that is the 10287 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10288 /// 10289 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10290 /// 10291 /// Returns true if there was an error, false otherwise. 10292 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10293 MultiVersionKind MVType, 10294 const TargetAttr *TA) { 10295 assert(MVType != MultiVersionKind::None && 10296 "Function lacks multiversion attribute"); 10297 10298 // Target only causes MV if it is default, otherwise this is a normal 10299 // function. 10300 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10301 return false; 10302 10303 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10304 FD->setInvalidDecl(); 10305 return true; 10306 } 10307 10308 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10309 FD->setInvalidDecl(); 10310 return true; 10311 } 10312 10313 FD->setIsMultiVersion(); 10314 return false; 10315 } 10316 10317 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10318 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10319 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10320 return true; 10321 } 10322 10323 return false; 10324 } 10325 10326 static bool CheckTargetCausesMultiVersioning( 10327 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10328 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10329 LookupResult &Previous) { 10330 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10331 ParsedTargetAttr NewParsed = NewTA->parse(); 10332 // Sort order doesn't matter, it just needs to be consistent. 10333 llvm::sort(NewParsed.Features); 10334 10335 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10336 // to change, this is a simple redeclaration. 10337 if (!NewTA->isDefaultVersion() && 10338 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10339 return false; 10340 10341 // Otherwise, this decl causes MultiVersioning. 10342 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10343 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10344 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10345 NewFD->setInvalidDecl(); 10346 return true; 10347 } 10348 10349 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10350 MultiVersionKind::Target)) { 10351 NewFD->setInvalidDecl(); 10352 return true; 10353 } 10354 10355 if (CheckMultiVersionValue(S, NewFD)) { 10356 NewFD->setInvalidDecl(); 10357 return true; 10358 } 10359 10360 // If this is 'default', permit the forward declaration. 10361 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10362 Redeclaration = true; 10363 OldDecl = OldFD; 10364 OldFD->setIsMultiVersion(); 10365 NewFD->setIsMultiVersion(); 10366 return false; 10367 } 10368 10369 if (CheckMultiVersionValue(S, OldFD)) { 10370 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10371 NewFD->setInvalidDecl(); 10372 return true; 10373 } 10374 10375 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10376 10377 if (OldParsed == NewParsed) { 10378 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10379 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10380 NewFD->setInvalidDecl(); 10381 return true; 10382 } 10383 10384 for (const auto *FD : OldFD->redecls()) { 10385 const auto *CurTA = FD->getAttr<TargetAttr>(); 10386 // We allow forward declarations before ANY multiversioning attributes, but 10387 // nothing after the fact. 10388 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10389 (!CurTA || CurTA->isInherited())) { 10390 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10391 << 0; 10392 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10393 NewFD->setInvalidDecl(); 10394 return true; 10395 } 10396 } 10397 10398 OldFD->setIsMultiVersion(); 10399 NewFD->setIsMultiVersion(); 10400 Redeclaration = false; 10401 MergeTypeWithPrevious = false; 10402 OldDecl = nullptr; 10403 Previous.clear(); 10404 return false; 10405 } 10406 10407 /// Check the validity of a new function declaration being added to an existing 10408 /// multiversioned declaration collection. 10409 static bool CheckMultiVersionAdditionalDecl( 10410 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10411 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10412 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10413 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10414 LookupResult &Previous) { 10415 10416 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10417 // Disallow mixing of multiversioning types. 10418 if ((OldMVType == MultiVersionKind::Target && 10419 NewMVType != MultiVersionKind::Target) || 10420 (NewMVType == MultiVersionKind::Target && 10421 OldMVType != MultiVersionKind::Target)) { 10422 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10423 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10424 NewFD->setInvalidDecl(); 10425 return true; 10426 } 10427 10428 ParsedTargetAttr NewParsed; 10429 if (NewTA) { 10430 NewParsed = NewTA->parse(); 10431 llvm::sort(NewParsed.Features); 10432 } 10433 10434 bool UseMemberUsingDeclRules = 10435 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10436 10437 // Next, check ALL non-overloads to see if this is a redeclaration of a 10438 // previous member of the MultiVersion set. 10439 for (NamedDecl *ND : Previous) { 10440 FunctionDecl *CurFD = ND->getAsFunction(); 10441 if (!CurFD) 10442 continue; 10443 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10444 continue; 10445 10446 if (NewMVType == MultiVersionKind::Target) { 10447 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10448 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10449 NewFD->setIsMultiVersion(); 10450 Redeclaration = true; 10451 OldDecl = ND; 10452 return false; 10453 } 10454 10455 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10456 if (CurParsed == NewParsed) { 10457 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10458 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10459 NewFD->setInvalidDecl(); 10460 return true; 10461 } 10462 } else { 10463 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10464 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10465 // Handle CPUDispatch/CPUSpecific versions. 10466 // Only 1 CPUDispatch function is allowed, this will make it go through 10467 // the redeclaration errors. 10468 if (NewMVType == MultiVersionKind::CPUDispatch && 10469 CurFD->hasAttr<CPUDispatchAttr>()) { 10470 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10471 std::equal( 10472 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10473 NewCPUDisp->cpus_begin(), 10474 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10475 return Cur->getName() == New->getName(); 10476 })) { 10477 NewFD->setIsMultiVersion(); 10478 Redeclaration = true; 10479 OldDecl = ND; 10480 return false; 10481 } 10482 10483 // If the declarations don't match, this is an error condition. 10484 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10485 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10486 NewFD->setInvalidDecl(); 10487 return true; 10488 } 10489 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10490 10491 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10492 std::equal( 10493 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10494 NewCPUSpec->cpus_begin(), 10495 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10496 return Cur->getName() == New->getName(); 10497 })) { 10498 NewFD->setIsMultiVersion(); 10499 Redeclaration = true; 10500 OldDecl = ND; 10501 return false; 10502 } 10503 10504 // Only 1 version of CPUSpecific is allowed for each CPU. 10505 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10506 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10507 if (CurII == NewII) { 10508 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10509 << NewII; 10510 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10511 NewFD->setInvalidDecl(); 10512 return true; 10513 } 10514 } 10515 } 10516 } 10517 // If the two decls aren't the same MVType, there is no possible error 10518 // condition. 10519 } 10520 } 10521 10522 // Else, this is simply a non-redecl case. Checking the 'value' is only 10523 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10524 // handled in the attribute adding step. 10525 if (NewMVType == MultiVersionKind::Target && 10526 CheckMultiVersionValue(S, NewFD)) { 10527 NewFD->setInvalidDecl(); 10528 return true; 10529 } 10530 10531 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10532 !OldFD->isMultiVersion(), NewMVType)) { 10533 NewFD->setInvalidDecl(); 10534 return true; 10535 } 10536 10537 // Permit forward declarations in the case where these two are compatible. 10538 if (!OldFD->isMultiVersion()) { 10539 OldFD->setIsMultiVersion(); 10540 NewFD->setIsMultiVersion(); 10541 Redeclaration = true; 10542 OldDecl = OldFD; 10543 return false; 10544 } 10545 10546 NewFD->setIsMultiVersion(); 10547 Redeclaration = false; 10548 MergeTypeWithPrevious = false; 10549 OldDecl = nullptr; 10550 Previous.clear(); 10551 return false; 10552 } 10553 10554 10555 /// Check the validity of a mulitversion function declaration. 10556 /// Also sets the multiversion'ness' of the function itself. 10557 /// 10558 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10559 /// 10560 /// Returns true if there was an error, false otherwise. 10561 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10562 bool &Redeclaration, NamedDecl *&OldDecl, 10563 bool &MergeTypeWithPrevious, 10564 LookupResult &Previous) { 10565 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10566 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10567 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10568 10569 // Mixing Multiversioning types is prohibited. 10570 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10571 (NewCPUDisp && NewCPUSpec)) { 10572 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10573 NewFD->setInvalidDecl(); 10574 return true; 10575 } 10576 10577 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10578 10579 // Main isn't allowed to become a multiversion function, however it IS 10580 // permitted to have 'main' be marked with the 'target' optimization hint. 10581 if (NewFD->isMain()) { 10582 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10583 MVType == MultiVersionKind::CPUDispatch || 10584 MVType == MultiVersionKind::CPUSpecific) { 10585 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10586 NewFD->setInvalidDecl(); 10587 return true; 10588 } 10589 return false; 10590 } 10591 10592 if (!OldDecl || !OldDecl->getAsFunction() || 10593 OldDecl->getDeclContext()->getRedeclContext() != 10594 NewFD->getDeclContext()->getRedeclContext()) { 10595 // If there's no previous declaration, AND this isn't attempting to cause 10596 // multiversioning, this isn't an error condition. 10597 if (MVType == MultiVersionKind::None) 10598 return false; 10599 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10600 } 10601 10602 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10603 10604 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10605 return false; 10606 10607 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10608 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10609 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10610 NewFD->setInvalidDecl(); 10611 return true; 10612 } 10613 10614 // Handle the target potentially causes multiversioning case. 10615 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10616 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10617 Redeclaration, OldDecl, 10618 MergeTypeWithPrevious, Previous); 10619 10620 // At this point, we have a multiversion function decl (in OldFD) AND an 10621 // appropriate attribute in the current function decl. Resolve that these are 10622 // still compatible with previous declarations. 10623 return CheckMultiVersionAdditionalDecl( 10624 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10625 OldDecl, MergeTypeWithPrevious, Previous); 10626 } 10627 10628 /// Perform semantic checking of a new function declaration. 10629 /// 10630 /// Performs semantic analysis of the new function declaration 10631 /// NewFD. This routine performs all semantic checking that does not 10632 /// require the actual declarator involved in the declaration, and is 10633 /// used both for the declaration of functions as they are parsed 10634 /// (called via ActOnDeclarator) and for the declaration of functions 10635 /// that have been instantiated via C++ template instantiation (called 10636 /// via InstantiateDecl). 10637 /// 10638 /// \param IsMemberSpecialization whether this new function declaration is 10639 /// a member specialization (that replaces any definition provided by the 10640 /// previous declaration). 10641 /// 10642 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10643 /// 10644 /// \returns true if the function declaration is a redeclaration. 10645 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10646 LookupResult &Previous, 10647 bool IsMemberSpecialization) { 10648 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10649 "Variably modified return types are not handled here"); 10650 10651 // Determine whether the type of this function should be merged with 10652 // a previous visible declaration. This never happens for functions in C++, 10653 // and always happens in C if the previous declaration was visible. 10654 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10655 !Previous.isShadowed(); 10656 10657 bool Redeclaration = false; 10658 NamedDecl *OldDecl = nullptr; 10659 bool MayNeedOverloadableChecks = false; 10660 10661 // Merge or overload the declaration with an existing declaration of 10662 // the same name, if appropriate. 10663 if (!Previous.empty()) { 10664 // Determine whether NewFD is an overload of PrevDecl or 10665 // a declaration that requires merging. If it's an overload, 10666 // there's no more work to do here; we'll just add the new 10667 // function to the scope. 10668 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10669 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10670 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10671 Redeclaration = true; 10672 OldDecl = Candidate; 10673 } 10674 } else { 10675 MayNeedOverloadableChecks = true; 10676 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10677 /*NewIsUsingDecl*/ false)) { 10678 case Ovl_Match: 10679 Redeclaration = true; 10680 break; 10681 10682 case Ovl_NonFunction: 10683 Redeclaration = true; 10684 break; 10685 10686 case Ovl_Overload: 10687 Redeclaration = false; 10688 break; 10689 } 10690 } 10691 } 10692 10693 // Check for a previous extern "C" declaration with this name. 10694 if (!Redeclaration && 10695 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10696 if (!Previous.empty()) { 10697 // This is an extern "C" declaration with the same name as a previous 10698 // declaration, and thus redeclares that entity... 10699 Redeclaration = true; 10700 OldDecl = Previous.getFoundDecl(); 10701 MergeTypeWithPrevious = false; 10702 10703 // ... except in the presence of __attribute__((overloadable)). 10704 if (OldDecl->hasAttr<OverloadableAttr>() || 10705 NewFD->hasAttr<OverloadableAttr>()) { 10706 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10707 MayNeedOverloadableChecks = true; 10708 Redeclaration = false; 10709 OldDecl = nullptr; 10710 } 10711 } 10712 } 10713 } 10714 10715 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10716 MergeTypeWithPrevious, Previous)) 10717 return Redeclaration; 10718 10719 // PPC MMA non-pointer types are not allowed as function return types. 10720 if (Context.getTargetInfo().getTriple().isPPC64() && 10721 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10722 NewFD->setInvalidDecl(); 10723 } 10724 10725 // C++11 [dcl.constexpr]p8: 10726 // A constexpr specifier for a non-static member function that is not 10727 // a constructor declares that member function to be const. 10728 // 10729 // This needs to be delayed until we know whether this is an out-of-line 10730 // definition of a static member function. 10731 // 10732 // This rule is not present in C++1y, so we produce a backwards 10733 // compatibility warning whenever it happens in C++11. 10734 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10735 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10736 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10737 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10738 CXXMethodDecl *OldMD = nullptr; 10739 if (OldDecl) 10740 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10741 if (!OldMD || !OldMD->isStatic()) { 10742 const FunctionProtoType *FPT = 10743 MD->getType()->castAs<FunctionProtoType>(); 10744 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10745 EPI.TypeQuals.addConst(); 10746 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10747 FPT->getParamTypes(), EPI)); 10748 10749 // Warn that we did this, if we're not performing template instantiation. 10750 // In that case, we'll have warned already when the template was defined. 10751 if (!inTemplateInstantiation()) { 10752 SourceLocation AddConstLoc; 10753 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10754 .IgnoreParens().getAs<FunctionTypeLoc>()) 10755 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10756 10757 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10758 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10759 } 10760 } 10761 } 10762 10763 if (Redeclaration) { 10764 // NewFD and OldDecl represent declarations that need to be 10765 // merged. 10766 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10767 NewFD->setInvalidDecl(); 10768 return Redeclaration; 10769 } 10770 10771 Previous.clear(); 10772 Previous.addDecl(OldDecl); 10773 10774 if (FunctionTemplateDecl *OldTemplateDecl = 10775 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10776 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10777 FunctionTemplateDecl *NewTemplateDecl 10778 = NewFD->getDescribedFunctionTemplate(); 10779 assert(NewTemplateDecl && "Template/non-template mismatch"); 10780 10781 // The call to MergeFunctionDecl above may have created some state in 10782 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10783 // can add it as a redeclaration. 10784 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10785 10786 NewFD->setPreviousDeclaration(OldFD); 10787 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10788 if (NewFD->isCXXClassMember()) { 10789 NewFD->setAccess(OldTemplateDecl->getAccess()); 10790 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10791 } 10792 10793 // If this is an explicit specialization of a member that is a function 10794 // template, mark it as a member specialization. 10795 if (IsMemberSpecialization && 10796 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10797 NewTemplateDecl->setMemberSpecialization(); 10798 assert(OldTemplateDecl->isMemberSpecialization()); 10799 // Explicit specializations of a member template do not inherit deleted 10800 // status from the parent member template that they are specializing. 10801 if (OldFD->isDeleted()) { 10802 // FIXME: This assert will not hold in the presence of modules. 10803 assert(OldFD->getCanonicalDecl() == OldFD); 10804 // FIXME: We need an update record for this AST mutation. 10805 OldFD->setDeletedAsWritten(false); 10806 } 10807 } 10808 10809 } else { 10810 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10811 auto *OldFD = cast<FunctionDecl>(OldDecl); 10812 // This needs to happen first so that 'inline' propagates. 10813 NewFD->setPreviousDeclaration(OldFD); 10814 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10815 if (NewFD->isCXXClassMember()) 10816 NewFD->setAccess(OldFD->getAccess()); 10817 } 10818 } 10819 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10820 !NewFD->getAttr<OverloadableAttr>()) { 10821 assert((Previous.empty() || 10822 llvm::any_of(Previous, 10823 [](const NamedDecl *ND) { 10824 return ND->hasAttr<OverloadableAttr>(); 10825 })) && 10826 "Non-redecls shouldn't happen without overloadable present"); 10827 10828 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10829 const auto *FD = dyn_cast<FunctionDecl>(ND); 10830 return FD && !FD->hasAttr<OverloadableAttr>(); 10831 }); 10832 10833 if (OtherUnmarkedIter != Previous.end()) { 10834 Diag(NewFD->getLocation(), 10835 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10836 Diag((*OtherUnmarkedIter)->getLocation(), 10837 diag::note_attribute_overloadable_prev_overload) 10838 << false; 10839 10840 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10841 } 10842 } 10843 10844 if (LangOpts.OpenMP) 10845 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10846 10847 // Semantic checking for this function declaration (in isolation). 10848 10849 if (getLangOpts().CPlusPlus) { 10850 // C++-specific checks. 10851 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10852 CheckConstructor(Constructor); 10853 } else if (CXXDestructorDecl *Destructor = 10854 dyn_cast<CXXDestructorDecl>(NewFD)) { 10855 CXXRecordDecl *Record = Destructor->getParent(); 10856 QualType ClassType = Context.getTypeDeclType(Record); 10857 10858 // FIXME: Shouldn't we be able to perform this check even when the class 10859 // type is dependent? Both gcc and edg can handle that. 10860 if (!ClassType->isDependentType()) { 10861 DeclarationName Name 10862 = Context.DeclarationNames.getCXXDestructorName( 10863 Context.getCanonicalType(ClassType)); 10864 if (NewFD->getDeclName() != Name) { 10865 Diag(NewFD->getLocation(), diag::err_destructor_name); 10866 NewFD->setInvalidDecl(); 10867 return Redeclaration; 10868 } 10869 } 10870 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10871 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10872 CheckDeductionGuideTemplate(TD); 10873 10874 // A deduction guide is not on the list of entities that can be 10875 // explicitly specialized. 10876 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10877 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10878 << /*explicit specialization*/ 1; 10879 } 10880 10881 // Find any virtual functions that this function overrides. 10882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10883 if (!Method->isFunctionTemplateSpecialization() && 10884 !Method->getDescribedFunctionTemplate() && 10885 Method->isCanonicalDecl()) { 10886 AddOverriddenMethods(Method->getParent(), Method); 10887 } 10888 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10889 // C++2a [class.virtual]p6 10890 // A virtual method shall not have a requires-clause. 10891 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10892 diag::err_constrained_virtual_method); 10893 10894 if (Method->isStatic()) 10895 checkThisInStaticMemberFunctionType(Method); 10896 } 10897 10898 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10899 ActOnConversionDeclarator(Conversion); 10900 10901 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10902 if (NewFD->isOverloadedOperator() && 10903 CheckOverloadedOperatorDeclaration(NewFD)) { 10904 NewFD->setInvalidDecl(); 10905 return Redeclaration; 10906 } 10907 10908 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10909 if (NewFD->getLiteralIdentifier() && 10910 CheckLiteralOperatorDeclaration(NewFD)) { 10911 NewFD->setInvalidDecl(); 10912 return Redeclaration; 10913 } 10914 10915 // In C++, check default arguments now that we have merged decls. Unless 10916 // the lexical context is the class, because in this case this is done 10917 // during delayed parsing anyway. 10918 if (!CurContext->isRecord()) 10919 CheckCXXDefaultArguments(NewFD); 10920 10921 // If this function declares a builtin function, check the type of this 10922 // declaration against the expected type for the builtin. 10923 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10924 ASTContext::GetBuiltinTypeError Error; 10925 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10926 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10927 // If the type of the builtin differs only in its exception 10928 // specification, that's OK. 10929 // FIXME: If the types do differ in this way, it would be better to 10930 // retain the 'noexcept' form of the type. 10931 if (!T.isNull() && 10932 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10933 NewFD->getType())) 10934 // The type of this function differs from the type of the builtin, 10935 // so forget about the builtin entirely. 10936 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10937 } 10938 10939 // If this function is declared as being extern "C", then check to see if 10940 // the function returns a UDT (class, struct, or union type) that is not C 10941 // compatible, and if it does, warn the user. 10942 // But, issue any diagnostic on the first declaration only. 10943 if (Previous.empty() && NewFD->isExternC()) { 10944 QualType R = NewFD->getReturnType(); 10945 if (R->isIncompleteType() && !R->isVoidType()) 10946 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10947 << NewFD << R; 10948 else if (!R.isPODType(Context) && !R->isVoidType() && 10949 !R->isObjCObjectPointerType()) 10950 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10951 } 10952 10953 // C++1z [dcl.fct]p6: 10954 // [...] whether the function has a non-throwing exception-specification 10955 // [is] part of the function type 10956 // 10957 // This results in an ABI break between C++14 and C++17 for functions whose 10958 // declared type includes an exception-specification in a parameter or 10959 // return type. (Exception specifications on the function itself are OK in 10960 // most cases, and exception specifications are not permitted in most other 10961 // contexts where they could make it into a mangling.) 10962 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10963 auto HasNoexcept = [&](QualType T) -> bool { 10964 // Strip off declarator chunks that could be between us and a function 10965 // type. We don't need to look far, exception specifications are very 10966 // restricted prior to C++17. 10967 if (auto *RT = T->getAs<ReferenceType>()) 10968 T = RT->getPointeeType(); 10969 else if (T->isAnyPointerType()) 10970 T = T->getPointeeType(); 10971 else if (auto *MPT = T->getAs<MemberPointerType>()) 10972 T = MPT->getPointeeType(); 10973 if (auto *FPT = T->getAs<FunctionProtoType>()) 10974 if (FPT->isNothrow()) 10975 return true; 10976 return false; 10977 }; 10978 10979 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10980 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10981 for (QualType T : FPT->param_types()) 10982 AnyNoexcept |= HasNoexcept(T); 10983 if (AnyNoexcept) 10984 Diag(NewFD->getLocation(), 10985 diag::warn_cxx17_compat_exception_spec_in_signature) 10986 << NewFD; 10987 } 10988 10989 if (!Redeclaration && LangOpts.CUDA) 10990 checkCUDATargetOverload(NewFD, Previous); 10991 } 10992 return Redeclaration; 10993 } 10994 10995 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10996 // C++11 [basic.start.main]p3: 10997 // A program that [...] declares main to be inline, static or 10998 // constexpr is ill-formed. 10999 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11000 // appear in a declaration of main. 11001 // static main is not an error under C99, but we should warn about it. 11002 // We accept _Noreturn main as an extension. 11003 if (FD->getStorageClass() == SC_Static) 11004 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11005 ? diag::err_static_main : diag::warn_static_main) 11006 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11007 if (FD->isInlineSpecified()) 11008 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11009 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11010 if (DS.isNoreturnSpecified()) { 11011 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11012 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11013 Diag(NoreturnLoc, diag::ext_noreturn_main); 11014 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11015 << FixItHint::CreateRemoval(NoreturnRange); 11016 } 11017 if (FD->isConstexpr()) { 11018 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11019 << FD->isConsteval() 11020 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11021 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11022 } 11023 11024 if (getLangOpts().OpenCL) { 11025 Diag(FD->getLocation(), diag::err_opencl_no_main) 11026 << FD->hasAttr<OpenCLKernelAttr>(); 11027 FD->setInvalidDecl(); 11028 return; 11029 } 11030 11031 QualType T = FD->getType(); 11032 assert(T->isFunctionType() && "function decl is not of function type"); 11033 const FunctionType* FT = T->castAs<FunctionType>(); 11034 11035 // Set default calling convention for main() 11036 if (FT->getCallConv() != CC_C) { 11037 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11038 FD->setType(QualType(FT, 0)); 11039 T = Context.getCanonicalType(FD->getType()); 11040 } 11041 11042 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11043 // In C with GNU extensions we allow main() to have non-integer return 11044 // type, but we should warn about the extension, and we disable the 11045 // implicit-return-zero rule. 11046 11047 // GCC in C mode accepts qualified 'int'. 11048 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11049 FD->setHasImplicitReturnZero(true); 11050 else { 11051 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11052 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11053 if (RTRange.isValid()) 11054 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11055 << FixItHint::CreateReplacement(RTRange, "int"); 11056 } 11057 } else { 11058 // In C and C++, main magically returns 0 if you fall off the end; 11059 // set the flag which tells us that. 11060 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11061 11062 // All the standards say that main() should return 'int'. 11063 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11064 FD->setHasImplicitReturnZero(true); 11065 else { 11066 // Otherwise, this is just a flat-out error. 11067 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11068 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11069 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11070 : FixItHint()); 11071 FD->setInvalidDecl(true); 11072 } 11073 } 11074 11075 // Treat protoless main() as nullary. 11076 if (isa<FunctionNoProtoType>(FT)) return; 11077 11078 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11079 unsigned nparams = FTP->getNumParams(); 11080 assert(FD->getNumParams() == nparams); 11081 11082 bool HasExtraParameters = (nparams > 3); 11083 11084 if (FTP->isVariadic()) { 11085 Diag(FD->getLocation(), diag::ext_variadic_main); 11086 // FIXME: if we had information about the location of the ellipsis, we 11087 // could add a FixIt hint to remove it as a parameter. 11088 } 11089 11090 // Darwin passes an undocumented fourth argument of type char**. If 11091 // other platforms start sprouting these, the logic below will start 11092 // getting shifty. 11093 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11094 HasExtraParameters = false; 11095 11096 if (HasExtraParameters) { 11097 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11098 FD->setInvalidDecl(true); 11099 nparams = 3; 11100 } 11101 11102 // FIXME: a lot of the following diagnostics would be improved 11103 // if we had some location information about types. 11104 11105 QualType CharPP = 11106 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11107 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11108 11109 for (unsigned i = 0; i < nparams; ++i) { 11110 QualType AT = FTP->getParamType(i); 11111 11112 bool mismatch = true; 11113 11114 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11115 mismatch = false; 11116 else if (Expected[i] == CharPP) { 11117 // As an extension, the following forms are okay: 11118 // char const ** 11119 // char const * const * 11120 // char * const * 11121 11122 QualifierCollector qs; 11123 const PointerType* PT; 11124 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11125 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11126 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11127 Context.CharTy)) { 11128 qs.removeConst(); 11129 mismatch = !qs.empty(); 11130 } 11131 } 11132 11133 if (mismatch) { 11134 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11135 // TODO: suggest replacing given type with expected type 11136 FD->setInvalidDecl(true); 11137 } 11138 } 11139 11140 if (nparams == 1 && !FD->isInvalidDecl()) { 11141 Diag(FD->getLocation(), diag::warn_main_one_arg); 11142 } 11143 11144 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11145 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11146 FD->setInvalidDecl(); 11147 } 11148 } 11149 11150 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11151 QualType T = FD->getType(); 11152 assert(T->isFunctionType() && "function decl is not of function type"); 11153 const FunctionType *FT = T->castAs<FunctionType>(); 11154 11155 // Set an implicit return of 'zero' if the function can return some integral, 11156 // enumeration, pointer or nullptr type. 11157 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11158 FT->getReturnType()->isAnyPointerType() || 11159 FT->getReturnType()->isNullPtrType()) 11160 // DllMain is exempt because a return value of zero means it failed. 11161 if (FD->getName() != "DllMain") 11162 FD->setHasImplicitReturnZero(true); 11163 11164 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11165 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11166 FD->setInvalidDecl(); 11167 } 11168 } 11169 11170 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11171 // FIXME: Need strict checking. In C89, we need to check for 11172 // any assignment, increment, decrement, function-calls, or 11173 // commas outside of a sizeof. In C99, it's the same list, 11174 // except that the aforementioned are allowed in unevaluated 11175 // expressions. Everything else falls under the 11176 // "may accept other forms of constant expressions" exception. 11177 // 11178 // Regular C++ code will not end up here (exceptions: language extensions, 11179 // OpenCL C++ etc), so the constant expression rules there don't matter. 11180 if (Init->isValueDependent()) { 11181 assert(Init->containsErrors() && 11182 "Dependent code should only occur in error-recovery path."); 11183 return true; 11184 } 11185 const Expr *Culprit; 11186 if (Init->isConstantInitializer(Context, false, &Culprit)) 11187 return false; 11188 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11189 << Culprit->getSourceRange(); 11190 return true; 11191 } 11192 11193 namespace { 11194 // Visits an initialization expression to see if OrigDecl is evaluated in 11195 // its own initialization and throws a warning if it does. 11196 class SelfReferenceChecker 11197 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11198 Sema &S; 11199 Decl *OrigDecl; 11200 bool isRecordType; 11201 bool isPODType; 11202 bool isReferenceType; 11203 11204 bool isInitList; 11205 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11206 11207 public: 11208 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11209 11210 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11211 S(S), OrigDecl(OrigDecl) { 11212 isPODType = false; 11213 isRecordType = false; 11214 isReferenceType = false; 11215 isInitList = false; 11216 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11217 isPODType = VD->getType().isPODType(S.Context); 11218 isRecordType = VD->getType()->isRecordType(); 11219 isReferenceType = VD->getType()->isReferenceType(); 11220 } 11221 } 11222 11223 // For most expressions, just call the visitor. For initializer lists, 11224 // track the index of the field being initialized since fields are 11225 // initialized in order allowing use of previously initialized fields. 11226 void CheckExpr(Expr *E) { 11227 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11228 if (!InitList) { 11229 Visit(E); 11230 return; 11231 } 11232 11233 // Track and increment the index here. 11234 isInitList = true; 11235 InitFieldIndex.push_back(0); 11236 for (auto Child : InitList->children()) { 11237 CheckExpr(cast<Expr>(Child)); 11238 ++InitFieldIndex.back(); 11239 } 11240 InitFieldIndex.pop_back(); 11241 } 11242 11243 // Returns true if MemberExpr is checked and no further checking is needed. 11244 // Returns false if additional checking is required. 11245 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11246 llvm::SmallVector<FieldDecl*, 4> Fields; 11247 Expr *Base = E; 11248 bool ReferenceField = false; 11249 11250 // Get the field members used. 11251 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11252 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11253 if (!FD) 11254 return false; 11255 Fields.push_back(FD); 11256 if (FD->getType()->isReferenceType()) 11257 ReferenceField = true; 11258 Base = ME->getBase()->IgnoreParenImpCasts(); 11259 } 11260 11261 // Keep checking only if the base Decl is the same. 11262 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11263 if (!DRE || DRE->getDecl() != OrigDecl) 11264 return false; 11265 11266 // A reference field can be bound to an unininitialized field. 11267 if (CheckReference && !ReferenceField) 11268 return true; 11269 11270 // Convert FieldDecls to their index number. 11271 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11272 for (const FieldDecl *I : llvm::reverse(Fields)) 11273 UsedFieldIndex.push_back(I->getFieldIndex()); 11274 11275 // See if a warning is needed by checking the first difference in index 11276 // numbers. If field being used has index less than the field being 11277 // initialized, then the use is safe. 11278 for (auto UsedIter = UsedFieldIndex.begin(), 11279 UsedEnd = UsedFieldIndex.end(), 11280 OrigIter = InitFieldIndex.begin(), 11281 OrigEnd = InitFieldIndex.end(); 11282 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11283 if (*UsedIter < *OrigIter) 11284 return true; 11285 if (*UsedIter > *OrigIter) 11286 break; 11287 } 11288 11289 // TODO: Add a different warning which will print the field names. 11290 HandleDeclRefExpr(DRE); 11291 return true; 11292 } 11293 11294 // For most expressions, the cast is directly above the DeclRefExpr. 11295 // For conditional operators, the cast can be outside the conditional 11296 // operator if both expressions are DeclRefExpr's. 11297 void HandleValue(Expr *E) { 11298 E = E->IgnoreParens(); 11299 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11300 HandleDeclRefExpr(DRE); 11301 return; 11302 } 11303 11304 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11305 Visit(CO->getCond()); 11306 HandleValue(CO->getTrueExpr()); 11307 HandleValue(CO->getFalseExpr()); 11308 return; 11309 } 11310 11311 if (BinaryConditionalOperator *BCO = 11312 dyn_cast<BinaryConditionalOperator>(E)) { 11313 Visit(BCO->getCond()); 11314 HandleValue(BCO->getFalseExpr()); 11315 return; 11316 } 11317 11318 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11319 HandleValue(OVE->getSourceExpr()); 11320 return; 11321 } 11322 11323 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11324 if (BO->getOpcode() == BO_Comma) { 11325 Visit(BO->getLHS()); 11326 HandleValue(BO->getRHS()); 11327 return; 11328 } 11329 } 11330 11331 if (isa<MemberExpr>(E)) { 11332 if (isInitList) { 11333 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11334 false /*CheckReference*/)) 11335 return; 11336 } 11337 11338 Expr *Base = E->IgnoreParenImpCasts(); 11339 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11340 // Check for static member variables and don't warn on them. 11341 if (!isa<FieldDecl>(ME->getMemberDecl())) 11342 return; 11343 Base = ME->getBase()->IgnoreParenImpCasts(); 11344 } 11345 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11346 HandleDeclRefExpr(DRE); 11347 return; 11348 } 11349 11350 Visit(E); 11351 } 11352 11353 // Reference types not handled in HandleValue are handled here since all 11354 // uses of references are bad, not just r-value uses. 11355 void VisitDeclRefExpr(DeclRefExpr *E) { 11356 if (isReferenceType) 11357 HandleDeclRefExpr(E); 11358 } 11359 11360 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11361 if (E->getCastKind() == CK_LValueToRValue) { 11362 HandleValue(E->getSubExpr()); 11363 return; 11364 } 11365 11366 Inherited::VisitImplicitCastExpr(E); 11367 } 11368 11369 void VisitMemberExpr(MemberExpr *E) { 11370 if (isInitList) { 11371 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11372 return; 11373 } 11374 11375 // Don't warn on arrays since they can be treated as pointers. 11376 if (E->getType()->canDecayToPointerType()) return; 11377 11378 // Warn when a non-static method call is followed by non-static member 11379 // field accesses, which is followed by a DeclRefExpr. 11380 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11381 bool Warn = (MD && !MD->isStatic()); 11382 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11383 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11384 if (!isa<FieldDecl>(ME->getMemberDecl())) 11385 Warn = false; 11386 Base = ME->getBase()->IgnoreParenImpCasts(); 11387 } 11388 11389 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11390 if (Warn) 11391 HandleDeclRefExpr(DRE); 11392 return; 11393 } 11394 11395 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11396 // Visit that expression. 11397 Visit(Base); 11398 } 11399 11400 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11401 Expr *Callee = E->getCallee(); 11402 11403 if (isa<UnresolvedLookupExpr>(Callee)) 11404 return Inherited::VisitCXXOperatorCallExpr(E); 11405 11406 Visit(Callee); 11407 for (auto Arg: E->arguments()) 11408 HandleValue(Arg->IgnoreParenImpCasts()); 11409 } 11410 11411 void VisitUnaryOperator(UnaryOperator *E) { 11412 // For POD record types, addresses of its own members are well-defined. 11413 if (E->getOpcode() == UO_AddrOf && isRecordType && 11414 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11415 if (!isPODType) 11416 HandleValue(E->getSubExpr()); 11417 return; 11418 } 11419 11420 if (E->isIncrementDecrementOp()) { 11421 HandleValue(E->getSubExpr()); 11422 return; 11423 } 11424 11425 Inherited::VisitUnaryOperator(E); 11426 } 11427 11428 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11429 11430 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11431 if (E->getConstructor()->isCopyConstructor()) { 11432 Expr *ArgExpr = E->getArg(0); 11433 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11434 if (ILE->getNumInits() == 1) 11435 ArgExpr = ILE->getInit(0); 11436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11437 if (ICE->getCastKind() == CK_NoOp) 11438 ArgExpr = ICE->getSubExpr(); 11439 HandleValue(ArgExpr); 11440 return; 11441 } 11442 Inherited::VisitCXXConstructExpr(E); 11443 } 11444 11445 void VisitCallExpr(CallExpr *E) { 11446 // Treat std::move as a use. 11447 if (E->isCallToStdMove()) { 11448 HandleValue(E->getArg(0)); 11449 return; 11450 } 11451 11452 Inherited::VisitCallExpr(E); 11453 } 11454 11455 void VisitBinaryOperator(BinaryOperator *E) { 11456 if (E->isCompoundAssignmentOp()) { 11457 HandleValue(E->getLHS()); 11458 Visit(E->getRHS()); 11459 return; 11460 } 11461 11462 Inherited::VisitBinaryOperator(E); 11463 } 11464 11465 // A custom visitor for BinaryConditionalOperator is needed because the 11466 // regular visitor would check the condition and true expression separately 11467 // but both point to the same place giving duplicate diagnostics. 11468 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11469 Visit(E->getCond()); 11470 Visit(E->getFalseExpr()); 11471 } 11472 11473 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11474 Decl* ReferenceDecl = DRE->getDecl(); 11475 if (OrigDecl != ReferenceDecl) return; 11476 unsigned diag; 11477 if (isReferenceType) { 11478 diag = diag::warn_uninit_self_reference_in_reference_init; 11479 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11480 diag = diag::warn_static_self_reference_in_init; 11481 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11482 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11483 DRE->getDecl()->getType()->isRecordType()) { 11484 diag = diag::warn_uninit_self_reference_in_init; 11485 } else { 11486 // Local variables will be handled by the CFG analysis. 11487 return; 11488 } 11489 11490 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11491 S.PDiag(diag) 11492 << DRE->getDecl() << OrigDecl->getLocation() 11493 << DRE->getSourceRange()); 11494 } 11495 }; 11496 11497 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11498 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11499 bool DirectInit) { 11500 // Parameters arguments are occassionially constructed with itself, 11501 // for instance, in recursive functions. Skip them. 11502 if (isa<ParmVarDecl>(OrigDecl)) 11503 return; 11504 11505 E = E->IgnoreParens(); 11506 11507 // Skip checking T a = a where T is not a record or reference type. 11508 // Doing so is a way to silence uninitialized warnings. 11509 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11510 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11511 if (ICE->getCastKind() == CK_LValueToRValue) 11512 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11513 if (DRE->getDecl() == OrigDecl) 11514 return; 11515 11516 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11517 } 11518 } // end anonymous namespace 11519 11520 namespace { 11521 // Simple wrapper to add the name of a variable or (if no variable is 11522 // available) a DeclarationName into a diagnostic. 11523 struct VarDeclOrName { 11524 VarDecl *VDecl; 11525 DeclarationName Name; 11526 11527 friend const Sema::SemaDiagnosticBuilder & 11528 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11529 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11530 } 11531 }; 11532 } // end anonymous namespace 11533 11534 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11535 DeclarationName Name, QualType Type, 11536 TypeSourceInfo *TSI, 11537 SourceRange Range, bool DirectInit, 11538 Expr *Init) { 11539 bool IsInitCapture = !VDecl; 11540 assert((!VDecl || !VDecl->isInitCapture()) && 11541 "init captures are expected to be deduced prior to initialization"); 11542 11543 VarDeclOrName VN{VDecl, Name}; 11544 11545 DeducedType *Deduced = Type->getContainedDeducedType(); 11546 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11547 11548 // C++11 [dcl.spec.auto]p3 11549 if (!Init) { 11550 assert(VDecl && "no init for init capture deduction?"); 11551 11552 // Except for class argument deduction, and then for an initializing 11553 // declaration only, i.e. no static at class scope or extern. 11554 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11555 VDecl->hasExternalStorage() || 11556 VDecl->isStaticDataMember()) { 11557 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11558 << VDecl->getDeclName() << Type; 11559 return QualType(); 11560 } 11561 } 11562 11563 ArrayRef<Expr*> DeduceInits; 11564 if (Init) 11565 DeduceInits = Init; 11566 11567 if (DirectInit) { 11568 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11569 DeduceInits = PL->exprs(); 11570 } 11571 11572 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11573 assert(VDecl && "non-auto type for init capture deduction?"); 11574 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11575 InitializationKind Kind = InitializationKind::CreateForInit( 11576 VDecl->getLocation(), DirectInit, Init); 11577 // FIXME: Initialization should not be taking a mutable list of inits. 11578 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11579 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11580 InitsCopy); 11581 } 11582 11583 if (DirectInit) { 11584 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11585 DeduceInits = IL->inits(); 11586 } 11587 11588 // Deduction only works if we have exactly one source expression. 11589 if (DeduceInits.empty()) { 11590 // It isn't possible to write this directly, but it is possible to 11591 // end up in this situation with "auto x(some_pack...);" 11592 Diag(Init->getBeginLoc(), IsInitCapture 11593 ? diag::err_init_capture_no_expression 11594 : diag::err_auto_var_init_no_expression) 11595 << VN << Type << Range; 11596 return QualType(); 11597 } 11598 11599 if (DeduceInits.size() > 1) { 11600 Diag(DeduceInits[1]->getBeginLoc(), 11601 IsInitCapture ? diag::err_init_capture_multiple_expressions 11602 : diag::err_auto_var_init_multiple_expressions) 11603 << VN << Type << Range; 11604 return QualType(); 11605 } 11606 11607 Expr *DeduceInit = DeduceInits[0]; 11608 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11609 Diag(Init->getBeginLoc(), IsInitCapture 11610 ? diag::err_init_capture_paren_braces 11611 : diag::err_auto_var_init_paren_braces) 11612 << isa<InitListExpr>(Init) << VN << Type << Range; 11613 return QualType(); 11614 } 11615 11616 // Expressions default to 'id' when we're in a debugger. 11617 bool DefaultedAnyToId = false; 11618 if (getLangOpts().DebuggerCastResultToId && 11619 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11620 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11621 if (Result.isInvalid()) { 11622 return QualType(); 11623 } 11624 Init = Result.get(); 11625 DefaultedAnyToId = true; 11626 } 11627 11628 // C++ [dcl.decomp]p1: 11629 // If the assignment-expression [...] has array type A and no ref-qualifier 11630 // is present, e has type cv A 11631 if (VDecl && isa<DecompositionDecl>(VDecl) && 11632 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11633 DeduceInit->getType()->isConstantArrayType()) 11634 return Context.getQualifiedType(DeduceInit->getType(), 11635 Type.getQualifiers()); 11636 11637 QualType DeducedType; 11638 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11639 if (!IsInitCapture) 11640 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11641 else if (isa<InitListExpr>(Init)) 11642 Diag(Range.getBegin(), 11643 diag::err_init_capture_deduction_failure_from_init_list) 11644 << VN 11645 << (DeduceInit->getType().isNull() ? TSI->getType() 11646 : DeduceInit->getType()) 11647 << DeduceInit->getSourceRange(); 11648 else 11649 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11650 << VN << TSI->getType() 11651 << (DeduceInit->getType().isNull() ? TSI->getType() 11652 : DeduceInit->getType()) 11653 << DeduceInit->getSourceRange(); 11654 } 11655 11656 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11657 // 'id' instead of a specific object type prevents most of our usual 11658 // checks. 11659 // We only want to warn outside of template instantiations, though: 11660 // inside a template, the 'id' could have come from a parameter. 11661 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11662 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11663 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11664 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11665 } 11666 11667 return DeducedType; 11668 } 11669 11670 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11671 Expr *Init) { 11672 assert(!Init || !Init->containsErrors()); 11673 QualType DeducedType = deduceVarTypeFromInitializer( 11674 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11675 VDecl->getSourceRange(), DirectInit, Init); 11676 if (DeducedType.isNull()) { 11677 VDecl->setInvalidDecl(); 11678 return true; 11679 } 11680 11681 VDecl->setType(DeducedType); 11682 assert(VDecl->isLinkageValid()); 11683 11684 // In ARC, infer lifetime. 11685 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11686 VDecl->setInvalidDecl(); 11687 11688 if (getLangOpts().OpenCL) 11689 deduceOpenCLAddressSpace(VDecl); 11690 11691 // If this is a redeclaration, check that the type we just deduced matches 11692 // the previously declared type. 11693 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11694 // We never need to merge the type, because we cannot form an incomplete 11695 // array of auto, nor deduce such a type. 11696 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11697 } 11698 11699 // Check the deduced type is valid for a variable declaration. 11700 CheckVariableDeclarationType(VDecl); 11701 return VDecl->isInvalidDecl(); 11702 } 11703 11704 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11705 SourceLocation Loc) { 11706 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11707 Init = EWC->getSubExpr(); 11708 11709 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11710 Init = CE->getSubExpr(); 11711 11712 QualType InitType = Init->getType(); 11713 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11714 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11715 "shouldn't be called if type doesn't have a non-trivial C struct"); 11716 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11717 for (auto I : ILE->inits()) { 11718 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11719 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11720 continue; 11721 SourceLocation SL = I->getExprLoc(); 11722 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11723 } 11724 return; 11725 } 11726 11727 if (isa<ImplicitValueInitExpr>(Init)) { 11728 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11729 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11730 NTCUK_Init); 11731 } else { 11732 // Assume all other explicit initializers involving copying some existing 11733 // object. 11734 // TODO: ignore any explicit initializers where we can guarantee 11735 // copy-elision. 11736 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11737 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11738 } 11739 } 11740 11741 namespace { 11742 11743 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11744 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11745 // in the source code or implicitly by the compiler if it is in a union 11746 // defined in a system header and has non-trivial ObjC ownership 11747 // qualifications. We don't want those fields to participate in determining 11748 // whether the containing union is non-trivial. 11749 return FD->hasAttr<UnavailableAttr>(); 11750 } 11751 11752 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11753 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11754 void> { 11755 using Super = 11756 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11757 void>; 11758 11759 DiagNonTrivalCUnionDefaultInitializeVisitor( 11760 QualType OrigTy, SourceLocation OrigLoc, 11761 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11762 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11763 11764 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11765 const FieldDecl *FD, bool InNonTrivialUnion) { 11766 if (const auto *AT = S.Context.getAsArrayType(QT)) 11767 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11768 InNonTrivialUnion); 11769 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11770 } 11771 11772 void visitARCStrong(QualType QT, const FieldDecl *FD, 11773 bool InNonTrivialUnion) { 11774 if (InNonTrivialUnion) 11775 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11776 << 1 << 0 << QT << FD->getName(); 11777 } 11778 11779 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11780 if (InNonTrivialUnion) 11781 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11782 << 1 << 0 << QT << FD->getName(); 11783 } 11784 11785 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11786 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11787 if (RD->isUnion()) { 11788 if (OrigLoc.isValid()) { 11789 bool IsUnion = false; 11790 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11791 IsUnion = OrigRD->isUnion(); 11792 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11793 << 0 << OrigTy << IsUnion << UseContext; 11794 // Reset OrigLoc so that this diagnostic is emitted only once. 11795 OrigLoc = SourceLocation(); 11796 } 11797 InNonTrivialUnion = true; 11798 } 11799 11800 if (InNonTrivialUnion) 11801 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11802 << 0 << 0 << QT.getUnqualifiedType() << ""; 11803 11804 for (const FieldDecl *FD : RD->fields()) 11805 if (!shouldIgnoreForRecordTriviality(FD)) 11806 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11807 } 11808 11809 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11810 11811 // The non-trivial C union type or the struct/union type that contains a 11812 // non-trivial C union. 11813 QualType OrigTy; 11814 SourceLocation OrigLoc; 11815 Sema::NonTrivialCUnionContext UseContext; 11816 Sema &S; 11817 }; 11818 11819 struct DiagNonTrivalCUnionDestructedTypeVisitor 11820 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11821 using Super = 11822 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11823 11824 DiagNonTrivalCUnionDestructedTypeVisitor( 11825 QualType OrigTy, SourceLocation OrigLoc, 11826 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11827 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11828 11829 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11830 const FieldDecl *FD, bool InNonTrivialUnion) { 11831 if (const auto *AT = S.Context.getAsArrayType(QT)) 11832 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11833 InNonTrivialUnion); 11834 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11835 } 11836 11837 void visitARCStrong(QualType QT, const FieldDecl *FD, 11838 bool InNonTrivialUnion) { 11839 if (InNonTrivialUnion) 11840 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11841 << 1 << 1 << QT << FD->getName(); 11842 } 11843 11844 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11845 if (InNonTrivialUnion) 11846 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11847 << 1 << 1 << QT << FD->getName(); 11848 } 11849 11850 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11851 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11852 if (RD->isUnion()) { 11853 if (OrigLoc.isValid()) { 11854 bool IsUnion = false; 11855 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11856 IsUnion = OrigRD->isUnion(); 11857 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11858 << 1 << OrigTy << IsUnion << UseContext; 11859 // Reset OrigLoc so that this diagnostic is emitted only once. 11860 OrigLoc = SourceLocation(); 11861 } 11862 InNonTrivialUnion = true; 11863 } 11864 11865 if (InNonTrivialUnion) 11866 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11867 << 0 << 1 << QT.getUnqualifiedType() << ""; 11868 11869 for (const FieldDecl *FD : RD->fields()) 11870 if (!shouldIgnoreForRecordTriviality(FD)) 11871 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11872 } 11873 11874 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11875 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11876 bool InNonTrivialUnion) {} 11877 11878 // The non-trivial C union type or the struct/union type that contains a 11879 // non-trivial C union. 11880 QualType OrigTy; 11881 SourceLocation OrigLoc; 11882 Sema::NonTrivialCUnionContext UseContext; 11883 Sema &S; 11884 }; 11885 11886 struct DiagNonTrivalCUnionCopyVisitor 11887 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11888 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11889 11890 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11891 Sema::NonTrivialCUnionContext UseContext, 11892 Sema &S) 11893 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11894 11895 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11896 const FieldDecl *FD, bool InNonTrivialUnion) { 11897 if (const auto *AT = S.Context.getAsArrayType(QT)) 11898 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11899 InNonTrivialUnion); 11900 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11901 } 11902 11903 void visitARCStrong(QualType QT, const FieldDecl *FD, 11904 bool InNonTrivialUnion) { 11905 if (InNonTrivialUnion) 11906 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11907 << 1 << 2 << QT << FD->getName(); 11908 } 11909 11910 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11911 if (InNonTrivialUnion) 11912 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11913 << 1 << 2 << QT << FD->getName(); 11914 } 11915 11916 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11917 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11918 if (RD->isUnion()) { 11919 if (OrigLoc.isValid()) { 11920 bool IsUnion = false; 11921 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11922 IsUnion = OrigRD->isUnion(); 11923 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11924 << 2 << OrigTy << IsUnion << UseContext; 11925 // Reset OrigLoc so that this diagnostic is emitted only once. 11926 OrigLoc = SourceLocation(); 11927 } 11928 InNonTrivialUnion = true; 11929 } 11930 11931 if (InNonTrivialUnion) 11932 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11933 << 0 << 2 << QT.getUnqualifiedType() << ""; 11934 11935 for (const FieldDecl *FD : RD->fields()) 11936 if (!shouldIgnoreForRecordTriviality(FD)) 11937 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11938 } 11939 11940 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11941 const FieldDecl *FD, bool InNonTrivialUnion) {} 11942 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11943 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11944 bool InNonTrivialUnion) {} 11945 11946 // The non-trivial C union type or the struct/union type that contains a 11947 // non-trivial C union. 11948 QualType OrigTy; 11949 SourceLocation OrigLoc; 11950 Sema::NonTrivialCUnionContext UseContext; 11951 Sema &S; 11952 }; 11953 11954 } // namespace 11955 11956 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11957 NonTrivialCUnionContext UseContext, 11958 unsigned NonTrivialKind) { 11959 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11960 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11961 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11962 "shouldn't be called if type doesn't have a non-trivial C union"); 11963 11964 if ((NonTrivialKind & NTCUK_Init) && 11965 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11966 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11967 .visit(QT, nullptr, false); 11968 if ((NonTrivialKind & NTCUK_Destruct) && 11969 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11970 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11971 .visit(QT, nullptr, false); 11972 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11973 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11974 .visit(QT, nullptr, false); 11975 } 11976 11977 /// AddInitializerToDecl - Adds the initializer Init to the 11978 /// declaration dcl. If DirectInit is true, this is C++ direct 11979 /// initialization rather than copy initialization. 11980 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11981 // If there is no declaration, there was an error parsing it. Just ignore 11982 // the initializer. 11983 if (!RealDecl || RealDecl->isInvalidDecl()) { 11984 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11985 return; 11986 } 11987 11988 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11989 // Pure-specifiers are handled in ActOnPureSpecifier. 11990 Diag(Method->getLocation(), diag::err_member_function_initialization) 11991 << Method->getDeclName() << Init->getSourceRange(); 11992 Method->setInvalidDecl(); 11993 return; 11994 } 11995 11996 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11997 if (!VDecl) { 11998 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11999 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12000 RealDecl->setInvalidDecl(); 12001 return; 12002 } 12003 12004 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12005 if (VDecl->getType()->isUndeducedType()) { 12006 // Attempt typo correction early so that the type of the init expression can 12007 // be deduced based on the chosen correction if the original init contains a 12008 // TypoExpr. 12009 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12010 if (!Res.isUsable()) { 12011 // There are unresolved typos in Init, just drop them. 12012 // FIXME: improve the recovery strategy to preserve the Init. 12013 RealDecl->setInvalidDecl(); 12014 return; 12015 } 12016 if (Res.get()->containsErrors()) { 12017 // Invalidate the decl as we don't know the type for recovery-expr yet. 12018 RealDecl->setInvalidDecl(); 12019 VDecl->setInit(Res.get()); 12020 return; 12021 } 12022 Init = Res.get(); 12023 12024 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12025 return; 12026 } 12027 12028 // dllimport cannot be used on variable definitions. 12029 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12030 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12031 VDecl->setInvalidDecl(); 12032 return; 12033 } 12034 12035 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12036 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12037 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12038 VDecl->setInvalidDecl(); 12039 return; 12040 } 12041 12042 if (!VDecl->getType()->isDependentType()) { 12043 // A definition must end up with a complete type, which means it must be 12044 // complete with the restriction that an array type might be completed by 12045 // the initializer; note that later code assumes this restriction. 12046 QualType BaseDeclType = VDecl->getType(); 12047 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12048 BaseDeclType = Array->getElementType(); 12049 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12050 diag::err_typecheck_decl_incomplete_type)) { 12051 RealDecl->setInvalidDecl(); 12052 return; 12053 } 12054 12055 // The variable can not have an abstract class type. 12056 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12057 diag::err_abstract_type_in_decl, 12058 AbstractVariableType)) 12059 VDecl->setInvalidDecl(); 12060 } 12061 12062 // If adding the initializer will turn this declaration into a definition, 12063 // and we already have a definition for this variable, diagnose or otherwise 12064 // handle the situation. 12065 VarDecl *Def; 12066 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12067 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12068 !VDecl->isThisDeclarationADemotedDefinition() && 12069 checkVarDeclRedefinition(Def, VDecl)) 12070 return; 12071 12072 if (getLangOpts().CPlusPlus) { 12073 // C++ [class.static.data]p4 12074 // If a static data member is of const integral or const 12075 // enumeration type, its declaration in the class definition can 12076 // specify a constant-initializer which shall be an integral 12077 // constant expression (5.19). In that case, the member can appear 12078 // in integral constant expressions. The member shall still be 12079 // defined in a namespace scope if it is used in the program and the 12080 // namespace scope definition shall not contain an initializer. 12081 // 12082 // We already performed a redefinition check above, but for static 12083 // data members we also need to check whether there was an in-class 12084 // declaration with an initializer. 12085 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12086 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12087 << VDecl->getDeclName(); 12088 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12089 diag::note_previous_initializer) 12090 << 0; 12091 return; 12092 } 12093 12094 if (VDecl->hasLocalStorage()) 12095 setFunctionHasBranchProtectedScope(); 12096 12097 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12098 VDecl->setInvalidDecl(); 12099 return; 12100 } 12101 } 12102 12103 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12104 // a kernel function cannot be initialized." 12105 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12106 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12107 VDecl->setInvalidDecl(); 12108 return; 12109 } 12110 12111 // The LoaderUninitialized attribute acts as a definition (of undef). 12112 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12113 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12114 VDecl->setInvalidDecl(); 12115 return; 12116 } 12117 12118 // Get the decls type and save a reference for later, since 12119 // CheckInitializerTypes may change it. 12120 QualType DclT = VDecl->getType(), SavT = DclT; 12121 12122 // Expressions default to 'id' when we're in a debugger 12123 // and we are assigning it to a variable of Objective-C pointer type. 12124 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12125 Init->getType() == Context.UnknownAnyTy) { 12126 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12127 if (Result.isInvalid()) { 12128 VDecl->setInvalidDecl(); 12129 return; 12130 } 12131 Init = Result.get(); 12132 } 12133 12134 // Perform the initialization. 12135 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12136 if (!VDecl->isInvalidDecl()) { 12137 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12138 InitializationKind Kind = InitializationKind::CreateForInit( 12139 VDecl->getLocation(), DirectInit, Init); 12140 12141 MultiExprArg Args = Init; 12142 if (CXXDirectInit) 12143 Args = MultiExprArg(CXXDirectInit->getExprs(), 12144 CXXDirectInit->getNumExprs()); 12145 12146 // Try to correct any TypoExprs in the initialization arguments. 12147 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12148 ExprResult Res = CorrectDelayedTyposInExpr( 12149 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12150 [this, Entity, Kind](Expr *E) { 12151 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12152 return Init.Failed() ? ExprError() : E; 12153 }); 12154 if (Res.isInvalid()) { 12155 VDecl->setInvalidDecl(); 12156 } else if (Res.get() != Args[Idx]) { 12157 Args[Idx] = Res.get(); 12158 } 12159 } 12160 if (VDecl->isInvalidDecl()) 12161 return; 12162 12163 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12164 /*TopLevelOfInitList=*/false, 12165 /*TreatUnavailableAsInvalid=*/false); 12166 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12167 if (Result.isInvalid()) { 12168 // If the provied initializer fails to initialize the var decl, 12169 // we attach a recovery expr for better recovery. 12170 auto RecoveryExpr = 12171 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12172 if (RecoveryExpr.get()) 12173 VDecl->setInit(RecoveryExpr.get()); 12174 return; 12175 } 12176 12177 Init = Result.getAs<Expr>(); 12178 } 12179 12180 // Check for self-references within variable initializers. 12181 // Variables declared within a function/method body (except for references) 12182 // are handled by a dataflow analysis. 12183 // This is undefined behavior in C++, but valid in C. 12184 if (getLangOpts().CPlusPlus) { 12185 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12186 VDecl->getType()->isReferenceType()) { 12187 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12188 } 12189 } 12190 12191 // If the type changed, it means we had an incomplete type that was 12192 // completed by the initializer. For example: 12193 // int ary[] = { 1, 3, 5 }; 12194 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12195 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12196 VDecl->setType(DclT); 12197 12198 if (!VDecl->isInvalidDecl()) { 12199 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12200 12201 if (VDecl->hasAttr<BlocksAttr>()) 12202 checkRetainCycles(VDecl, Init); 12203 12204 // It is safe to assign a weak reference into a strong variable. 12205 // Although this code can still have problems: 12206 // id x = self.weakProp; 12207 // id y = self.weakProp; 12208 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12209 // paths through the function. This should be revisited if 12210 // -Wrepeated-use-of-weak is made flow-sensitive. 12211 if (FunctionScopeInfo *FSI = getCurFunction()) 12212 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12213 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12214 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12215 Init->getBeginLoc())) 12216 FSI->markSafeWeakUse(Init); 12217 } 12218 12219 // The initialization is usually a full-expression. 12220 // 12221 // FIXME: If this is a braced initialization of an aggregate, it is not 12222 // an expression, and each individual field initializer is a separate 12223 // full-expression. For instance, in: 12224 // 12225 // struct Temp { ~Temp(); }; 12226 // struct S { S(Temp); }; 12227 // struct T { S a, b; } t = { Temp(), Temp() } 12228 // 12229 // we should destroy the first Temp before constructing the second. 12230 ExprResult Result = 12231 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12232 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12233 if (Result.isInvalid()) { 12234 VDecl->setInvalidDecl(); 12235 return; 12236 } 12237 Init = Result.get(); 12238 12239 // Attach the initializer to the decl. 12240 VDecl->setInit(Init); 12241 12242 if (VDecl->isLocalVarDecl()) { 12243 // Don't check the initializer if the declaration is malformed. 12244 if (VDecl->isInvalidDecl()) { 12245 // do nothing 12246 12247 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12248 // This is true even in C++ for OpenCL. 12249 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12250 CheckForConstantInitializer(Init, DclT); 12251 12252 // Otherwise, C++ does not restrict the initializer. 12253 } else if (getLangOpts().CPlusPlus) { 12254 // do nothing 12255 12256 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12257 // static storage duration shall be constant expressions or string literals. 12258 } else if (VDecl->getStorageClass() == SC_Static) { 12259 CheckForConstantInitializer(Init, DclT); 12260 12261 // C89 is stricter than C99 for aggregate initializers. 12262 // C89 6.5.7p3: All the expressions [...] in an initializer list 12263 // for an object that has aggregate or union type shall be 12264 // constant expressions. 12265 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12266 isa<InitListExpr>(Init)) { 12267 const Expr *Culprit; 12268 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12269 Diag(Culprit->getExprLoc(), 12270 diag::ext_aggregate_init_not_constant) 12271 << Culprit->getSourceRange(); 12272 } 12273 } 12274 12275 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12276 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12277 if (VDecl->hasLocalStorage()) 12278 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12279 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12280 VDecl->getLexicalDeclContext()->isRecord()) { 12281 // This is an in-class initialization for a static data member, e.g., 12282 // 12283 // struct S { 12284 // static const int value = 17; 12285 // }; 12286 12287 // C++ [class.mem]p4: 12288 // A member-declarator can contain a constant-initializer only 12289 // if it declares a static member (9.4) of const integral or 12290 // const enumeration type, see 9.4.2. 12291 // 12292 // C++11 [class.static.data]p3: 12293 // If a non-volatile non-inline const static data member is of integral 12294 // or enumeration type, its declaration in the class definition can 12295 // specify a brace-or-equal-initializer in which every initializer-clause 12296 // that is an assignment-expression is a constant expression. A static 12297 // data member of literal type can be declared in the class definition 12298 // with the constexpr specifier; if so, its declaration shall specify a 12299 // brace-or-equal-initializer in which every initializer-clause that is 12300 // an assignment-expression is a constant expression. 12301 12302 // Do nothing on dependent types. 12303 if (DclT->isDependentType()) { 12304 12305 // Allow any 'static constexpr' members, whether or not they are of literal 12306 // type. We separately check that every constexpr variable is of literal 12307 // type. 12308 } else if (VDecl->isConstexpr()) { 12309 12310 // Require constness. 12311 } else if (!DclT.isConstQualified()) { 12312 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12313 << Init->getSourceRange(); 12314 VDecl->setInvalidDecl(); 12315 12316 // We allow integer constant expressions in all cases. 12317 } else if (DclT->isIntegralOrEnumerationType()) { 12318 // Check whether the expression is a constant expression. 12319 SourceLocation Loc; 12320 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12321 // In C++11, a non-constexpr const static data member with an 12322 // in-class initializer cannot be volatile. 12323 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12324 else if (Init->isValueDependent()) 12325 ; // Nothing to check. 12326 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12327 ; // Ok, it's an ICE! 12328 else if (Init->getType()->isScopedEnumeralType() && 12329 Init->isCXX11ConstantExpr(Context)) 12330 ; // Ok, it is a scoped-enum constant expression. 12331 else if (Init->isEvaluatable(Context)) { 12332 // If we can constant fold the initializer through heroics, accept it, 12333 // but report this as a use of an extension for -pedantic. 12334 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12335 << Init->getSourceRange(); 12336 } else { 12337 // Otherwise, this is some crazy unknown case. Report the issue at the 12338 // location provided by the isIntegerConstantExpr failed check. 12339 Diag(Loc, diag::err_in_class_initializer_non_constant) 12340 << Init->getSourceRange(); 12341 VDecl->setInvalidDecl(); 12342 } 12343 12344 // We allow foldable floating-point constants as an extension. 12345 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12346 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12347 // it anyway and provide a fixit to add the 'constexpr'. 12348 if (getLangOpts().CPlusPlus11) { 12349 Diag(VDecl->getLocation(), 12350 diag::ext_in_class_initializer_float_type_cxx11) 12351 << DclT << Init->getSourceRange(); 12352 Diag(VDecl->getBeginLoc(), 12353 diag::note_in_class_initializer_float_type_cxx11) 12354 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12355 } else { 12356 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12357 << DclT << Init->getSourceRange(); 12358 12359 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12360 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12361 << Init->getSourceRange(); 12362 VDecl->setInvalidDecl(); 12363 } 12364 } 12365 12366 // Suggest adding 'constexpr' in C++11 for literal types. 12367 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12368 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12369 << DclT << Init->getSourceRange() 12370 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12371 VDecl->setConstexpr(true); 12372 12373 } else { 12374 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12375 << DclT << Init->getSourceRange(); 12376 VDecl->setInvalidDecl(); 12377 } 12378 } else if (VDecl->isFileVarDecl()) { 12379 // In C, extern is typically used to avoid tentative definitions when 12380 // declaring variables in headers, but adding an intializer makes it a 12381 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12382 // In C++, extern is often used to give implictly static const variables 12383 // external linkage, so don't warn in that case. If selectany is present, 12384 // this might be header code intended for C and C++ inclusion, so apply the 12385 // C++ rules. 12386 if (VDecl->getStorageClass() == SC_Extern && 12387 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12388 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12389 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12390 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12391 Diag(VDecl->getLocation(), diag::warn_extern_init); 12392 12393 // In Microsoft C++ mode, a const variable defined in namespace scope has 12394 // external linkage by default if the variable is declared with 12395 // __declspec(dllexport). 12396 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12397 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12398 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12399 VDecl->setStorageClass(SC_Extern); 12400 12401 // C99 6.7.8p4. All file scoped initializers need to be constant. 12402 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12403 CheckForConstantInitializer(Init, DclT); 12404 } 12405 12406 QualType InitType = Init->getType(); 12407 if (!InitType.isNull() && 12408 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12409 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12410 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12411 12412 // We will represent direct-initialization similarly to copy-initialization: 12413 // int x(1); -as-> int x = 1; 12414 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12415 // 12416 // Clients that want to distinguish between the two forms, can check for 12417 // direct initializer using VarDecl::getInitStyle(). 12418 // A major benefit is that clients that don't particularly care about which 12419 // exactly form was it (like the CodeGen) can handle both cases without 12420 // special case code. 12421 12422 // C++ 8.5p11: 12423 // The form of initialization (using parentheses or '=') is generally 12424 // insignificant, but does matter when the entity being initialized has a 12425 // class type. 12426 if (CXXDirectInit) { 12427 assert(DirectInit && "Call-style initializer must be direct init."); 12428 VDecl->setInitStyle(VarDecl::CallInit); 12429 } else if (DirectInit) { 12430 // This must be list-initialization. No other way is direct-initialization. 12431 VDecl->setInitStyle(VarDecl::ListInit); 12432 } 12433 12434 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12435 DeclsToCheckForDeferredDiags.push_back(VDecl); 12436 CheckCompleteVariableDeclaration(VDecl); 12437 } 12438 12439 /// ActOnInitializerError - Given that there was an error parsing an 12440 /// initializer for the given declaration, try to return to some form 12441 /// of sanity. 12442 void Sema::ActOnInitializerError(Decl *D) { 12443 // Our main concern here is re-establishing invariants like "a 12444 // variable's type is either dependent or complete". 12445 if (!D || D->isInvalidDecl()) return; 12446 12447 VarDecl *VD = dyn_cast<VarDecl>(D); 12448 if (!VD) return; 12449 12450 // Bindings are not usable if we can't make sense of the initializer. 12451 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12452 for (auto *BD : DD->bindings()) 12453 BD->setInvalidDecl(); 12454 12455 // Auto types are meaningless if we can't make sense of the initializer. 12456 if (VD->getType()->isUndeducedType()) { 12457 D->setInvalidDecl(); 12458 return; 12459 } 12460 12461 QualType Ty = VD->getType(); 12462 if (Ty->isDependentType()) return; 12463 12464 // Require a complete type. 12465 if (RequireCompleteType(VD->getLocation(), 12466 Context.getBaseElementType(Ty), 12467 diag::err_typecheck_decl_incomplete_type)) { 12468 VD->setInvalidDecl(); 12469 return; 12470 } 12471 12472 // Require a non-abstract type. 12473 if (RequireNonAbstractType(VD->getLocation(), Ty, 12474 diag::err_abstract_type_in_decl, 12475 AbstractVariableType)) { 12476 VD->setInvalidDecl(); 12477 return; 12478 } 12479 12480 // Don't bother complaining about constructors or destructors, 12481 // though. 12482 } 12483 12484 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12485 // If there is no declaration, there was an error parsing it. Just ignore it. 12486 if (!RealDecl) 12487 return; 12488 12489 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12490 QualType Type = Var->getType(); 12491 12492 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12493 if (isa<DecompositionDecl>(RealDecl)) { 12494 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12495 Var->setInvalidDecl(); 12496 return; 12497 } 12498 12499 if (Type->isUndeducedType() && 12500 DeduceVariableDeclarationType(Var, false, nullptr)) 12501 return; 12502 12503 // C++11 [class.static.data]p3: A static data member can be declared with 12504 // the constexpr specifier; if so, its declaration shall specify 12505 // a brace-or-equal-initializer. 12506 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12507 // the definition of a variable [...] or the declaration of a static data 12508 // member. 12509 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12510 !Var->isThisDeclarationADemotedDefinition()) { 12511 if (Var->isStaticDataMember()) { 12512 // C++1z removes the relevant rule; the in-class declaration is always 12513 // a definition there. 12514 if (!getLangOpts().CPlusPlus17 && 12515 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12516 Diag(Var->getLocation(), 12517 diag::err_constexpr_static_mem_var_requires_init) 12518 << Var; 12519 Var->setInvalidDecl(); 12520 return; 12521 } 12522 } else { 12523 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12524 Var->setInvalidDecl(); 12525 return; 12526 } 12527 } 12528 12529 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12530 // be initialized. 12531 if (!Var->isInvalidDecl() && 12532 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12533 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12534 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12535 Var->setInvalidDecl(); 12536 return; 12537 } 12538 12539 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12540 if (Var->getStorageClass() == SC_Extern) { 12541 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12542 << Var; 12543 Var->setInvalidDecl(); 12544 return; 12545 } 12546 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12547 diag::err_typecheck_decl_incomplete_type)) { 12548 Var->setInvalidDecl(); 12549 return; 12550 } 12551 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12552 if (!RD->hasTrivialDefaultConstructor()) { 12553 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12554 Var->setInvalidDecl(); 12555 return; 12556 } 12557 } 12558 } 12559 12560 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12561 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12562 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12563 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12564 NTCUC_DefaultInitializedObject, NTCUK_Init); 12565 12566 12567 switch (DefKind) { 12568 case VarDecl::Definition: 12569 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12570 break; 12571 12572 // We have an out-of-line definition of a static data member 12573 // that has an in-class initializer, so we type-check this like 12574 // a declaration. 12575 // 12576 LLVM_FALLTHROUGH; 12577 12578 case VarDecl::DeclarationOnly: 12579 // It's only a declaration. 12580 12581 // Block scope. C99 6.7p7: If an identifier for an object is 12582 // declared with no linkage (C99 6.2.2p6), the type for the 12583 // object shall be complete. 12584 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12585 !Var->hasLinkage() && !Var->isInvalidDecl() && 12586 RequireCompleteType(Var->getLocation(), Type, 12587 diag::err_typecheck_decl_incomplete_type)) 12588 Var->setInvalidDecl(); 12589 12590 // Make sure that the type is not abstract. 12591 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12592 RequireNonAbstractType(Var->getLocation(), Type, 12593 diag::err_abstract_type_in_decl, 12594 AbstractVariableType)) 12595 Var->setInvalidDecl(); 12596 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12597 Var->getStorageClass() == SC_PrivateExtern) { 12598 Diag(Var->getLocation(), diag::warn_private_extern); 12599 Diag(Var->getLocation(), diag::note_private_extern); 12600 } 12601 12602 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12603 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12604 ExternalDeclarations.push_back(Var); 12605 12606 return; 12607 12608 case VarDecl::TentativeDefinition: 12609 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12610 // object that has file scope without an initializer, and without a 12611 // storage-class specifier or with the storage-class specifier "static", 12612 // constitutes a tentative definition. Note: A tentative definition with 12613 // external linkage is valid (C99 6.2.2p5). 12614 if (!Var->isInvalidDecl()) { 12615 if (const IncompleteArrayType *ArrayT 12616 = Context.getAsIncompleteArrayType(Type)) { 12617 if (RequireCompleteSizedType( 12618 Var->getLocation(), ArrayT->getElementType(), 12619 diag::err_array_incomplete_or_sizeless_type)) 12620 Var->setInvalidDecl(); 12621 } else if (Var->getStorageClass() == SC_Static) { 12622 // C99 6.9.2p3: If the declaration of an identifier for an object is 12623 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12624 // declared type shall not be an incomplete type. 12625 // NOTE: code such as the following 12626 // static struct s; 12627 // struct s { int a; }; 12628 // is accepted by gcc. Hence here we issue a warning instead of 12629 // an error and we do not invalidate the static declaration. 12630 // NOTE: to avoid multiple warnings, only check the first declaration. 12631 if (Var->isFirstDecl()) 12632 RequireCompleteType(Var->getLocation(), Type, 12633 diag::ext_typecheck_decl_incomplete_type); 12634 } 12635 } 12636 12637 // Record the tentative definition; we're done. 12638 if (!Var->isInvalidDecl()) 12639 TentativeDefinitions.push_back(Var); 12640 return; 12641 } 12642 12643 // Provide a specific diagnostic for uninitialized variable 12644 // definitions with incomplete array type. 12645 if (Type->isIncompleteArrayType()) { 12646 Diag(Var->getLocation(), 12647 diag::err_typecheck_incomplete_array_needs_initializer); 12648 Var->setInvalidDecl(); 12649 return; 12650 } 12651 12652 // Provide a specific diagnostic for uninitialized variable 12653 // definitions with reference type. 12654 if (Type->isReferenceType()) { 12655 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12656 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12657 Var->setInvalidDecl(); 12658 return; 12659 } 12660 12661 // Do not attempt to type-check the default initializer for a 12662 // variable with dependent type. 12663 if (Type->isDependentType()) 12664 return; 12665 12666 if (Var->isInvalidDecl()) 12667 return; 12668 12669 if (!Var->hasAttr<AliasAttr>()) { 12670 if (RequireCompleteType(Var->getLocation(), 12671 Context.getBaseElementType(Type), 12672 diag::err_typecheck_decl_incomplete_type)) { 12673 Var->setInvalidDecl(); 12674 return; 12675 } 12676 } else { 12677 return; 12678 } 12679 12680 // The variable can not have an abstract class type. 12681 if (RequireNonAbstractType(Var->getLocation(), Type, 12682 diag::err_abstract_type_in_decl, 12683 AbstractVariableType)) { 12684 Var->setInvalidDecl(); 12685 return; 12686 } 12687 12688 // Check for jumps past the implicit initializer. C++0x 12689 // clarifies that this applies to a "variable with automatic 12690 // storage duration", not a "local variable". 12691 // C++11 [stmt.dcl]p3 12692 // A program that jumps from a point where a variable with automatic 12693 // storage duration is not in scope to a point where it is in scope is 12694 // ill-formed unless the variable has scalar type, class type with a 12695 // trivial default constructor and a trivial destructor, a cv-qualified 12696 // version of one of these types, or an array of one of the preceding 12697 // types and is declared without an initializer. 12698 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12699 if (const RecordType *Record 12700 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12701 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12702 // Mark the function (if we're in one) for further checking even if the 12703 // looser rules of C++11 do not require such checks, so that we can 12704 // diagnose incompatibilities with C++98. 12705 if (!CXXRecord->isPOD()) 12706 setFunctionHasBranchProtectedScope(); 12707 } 12708 } 12709 // In OpenCL, we can't initialize objects in the __local address space, 12710 // even implicitly, so don't synthesize an implicit initializer. 12711 if (getLangOpts().OpenCL && 12712 Var->getType().getAddressSpace() == LangAS::opencl_local) 12713 return; 12714 // C++03 [dcl.init]p9: 12715 // If no initializer is specified for an object, and the 12716 // object is of (possibly cv-qualified) non-POD class type (or 12717 // array thereof), the object shall be default-initialized; if 12718 // the object is of const-qualified type, the underlying class 12719 // type shall have a user-declared default 12720 // constructor. Otherwise, if no initializer is specified for 12721 // a non- static object, the object and its subobjects, if 12722 // any, have an indeterminate initial value); if the object 12723 // or any of its subobjects are of const-qualified type, the 12724 // program is ill-formed. 12725 // C++0x [dcl.init]p11: 12726 // If no initializer is specified for an object, the object is 12727 // default-initialized; [...]. 12728 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12729 InitializationKind Kind 12730 = InitializationKind::CreateDefault(Var->getLocation()); 12731 12732 InitializationSequence InitSeq(*this, Entity, Kind, None); 12733 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12734 12735 if (Init.get()) { 12736 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12737 // This is important for template substitution. 12738 Var->setInitStyle(VarDecl::CallInit); 12739 } else if (Init.isInvalid()) { 12740 // If default-init fails, attach a recovery-expr initializer to track 12741 // that initialization was attempted and failed. 12742 auto RecoveryExpr = 12743 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12744 if (RecoveryExpr.get()) 12745 Var->setInit(RecoveryExpr.get()); 12746 } 12747 12748 CheckCompleteVariableDeclaration(Var); 12749 } 12750 } 12751 12752 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12753 // If there is no declaration, there was an error parsing it. Ignore it. 12754 if (!D) 12755 return; 12756 12757 VarDecl *VD = dyn_cast<VarDecl>(D); 12758 if (!VD) { 12759 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12760 D->setInvalidDecl(); 12761 return; 12762 } 12763 12764 VD->setCXXForRangeDecl(true); 12765 12766 // for-range-declaration cannot be given a storage class specifier. 12767 int Error = -1; 12768 switch (VD->getStorageClass()) { 12769 case SC_None: 12770 break; 12771 case SC_Extern: 12772 Error = 0; 12773 break; 12774 case SC_Static: 12775 Error = 1; 12776 break; 12777 case SC_PrivateExtern: 12778 Error = 2; 12779 break; 12780 case SC_Auto: 12781 Error = 3; 12782 break; 12783 case SC_Register: 12784 Error = 4; 12785 break; 12786 } 12787 12788 // for-range-declaration cannot be given a storage class specifier con't. 12789 switch (VD->getTSCSpec()) { 12790 case TSCS_thread_local: 12791 Error = 6; 12792 break; 12793 case TSCS___thread: 12794 case TSCS__Thread_local: 12795 case TSCS_unspecified: 12796 break; 12797 } 12798 12799 if (Error != -1) { 12800 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12801 << VD << Error; 12802 D->setInvalidDecl(); 12803 } 12804 } 12805 12806 StmtResult 12807 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12808 IdentifierInfo *Ident, 12809 ParsedAttributes &Attrs, 12810 SourceLocation AttrEnd) { 12811 // C++1y [stmt.iter]p1: 12812 // A range-based for statement of the form 12813 // for ( for-range-identifier : for-range-initializer ) statement 12814 // is equivalent to 12815 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12816 DeclSpec DS(Attrs.getPool().getFactory()); 12817 12818 const char *PrevSpec; 12819 unsigned DiagID; 12820 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12821 getPrintingPolicy()); 12822 12823 Declarator D(DS, DeclaratorContext::ForInit); 12824 D.SetIdentifier(Ident, IdentLoc); 12825 D.takeAttributes(Attrs, AttrEnd); 12826 12827 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12828 IdentLoc); 12829 Decl *Var = ActOnDeclarator(S, D); 12830 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12831 FinalizeDeclaration(Var); 12832 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12833 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12834 } 12835 12836 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12837 if (var->isInvalidDecl()) return; 12838 12839 if (getLangOpts().OpenCL) { 12840 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12841 // initialiser 12842 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12843 !var->hasInit()) { 12844 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12845 << 1 /*Init*/; 12846 var->setInvalidDecl(); 12847 return; 12848 } 12849 } 12850 12851 // In Objective-C, don't allow jumps past the implicit initialization of a 12852 // local retaining variable. 12853 if (getLangOpts().ObjC && 12854 var->hasLocalStorage()) { 12855 switch (var->getType().getObjCLifetime()) { 12856 case Qualifiers::OCL_None: 12857 case Qualifiers::OCL_ExplicitNone: 12858 case Qualifiers::OCL_Autoreleasing: 12859 break; 12860 12861 case Qualifiers::OCL_Weak: 12862 case Qualifiers::OCL_Strong: 12863 setFunctionHasBranchProtectedScope(); 12864 break; 12865 } 12866 } 12867 12868 if (var->hasLocalStorage() && 12869 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12870 setFunctionHasBranchProtectedScope(); 12871 12872 // Warn about externally-visible variables being defined without a 12873 // prior declaration. We only want to do this for global 12874 // declarations, but we also specifically need to avoid doing it for 12875 // class members because the linkage of an anonymous class can 12876 // change if it's later given a typedef name. 12877 if (var->isThisDeclarationADefinition() && 12878 var->getDeclContext()->getRedeclContext()->isFileContext() && 12879 var->isExternallyVisible() && var->hasLinkage() && 12880 !var->isInline() && !var->getDescribedVarTemplate() && 12881 !isa<VarTemplatePartialSpecializationDecl>(var) && 12882 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12883 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12884 var->getLocation())) { 12885 // Find a previous declaration that's not a definition. 12886 VarDecl *prev = var->getPreviousDecl(); 12887 while (prev && prev->isThisDeclarationADefinition()) 12888 prev = prev->getPreviousDecl(); 12889 12890 if (!prev) { 12891 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12892 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12893 << /* variable */ 0; 12894 } 12895 } 12896 12897 // Cache the result of checking for constant initialization. 12898 Optional<bool> CacheHasConstInit; 12899 const Expr *CacheCulprit = nullptr; 12900 auto checkConstInit = [&]() mutable { 12901 if (!CacheHasConstInit) 12902 CacheHasConstInit = var->getInit()->isConstantInitializer( 12903 Context, var->getType()->isReferenceType(), &CacheCulprit); 12904 return *CacheHasConstInit; 12905 }; 12906 12907 if (var->getTLSKind() == VarDecl::TLS_Static) { 12908 if (var->getType().isDestructedType()) { 12909 // GNU C++98 edits for __thread, [basic.start.term]p3: 12910 // The type of an object with thread storage duration shall not 12911 // have a non-trivial destructor. 12912 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12913 if (getLangOpts().CPlusPlus11) 12914 Diag(var->getLocation(), diag::note_use_thread_local); 12915 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12916 if (!checkConstInit()) { 12917 // GNU C++98 edits for __thread, [basic.start.init]p4: 12918 // An object of thread storage duration shall not require dynamic 12919 // initialization. 12920 // FIXME: Need strict checking here. 12921 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12922 << CacheCulprit->getSourceRange(); 12923 if (getLangOpts().CPlusPlus11) 12924 Diag(var->getLocation(), diag::note_use_thread_local); 12925 } 12926 } 12927 } 12928 12929 // Apply section attributes and pragmas to global variables. 12930 bool GlobalStorage = var->hasGlobalStorage(); 12931 if (GlobalStorage && var->isThisDeclarationADefinition() && 12932 !inTemplateInstantiation()) { 12933 PragmaStack<StringLiteral *> *Stack = nullptr; 12934 int SectionFlags = ASTContext::PSF_Read; 12935 if (var->getType().isConstQualified()) 12936 Stack = &ConstSegStack; 12937 else if (!var->getInit()) { 12938 Stack = &BSSSegStack; 12939 SectionFlags |= ASTContext::PSF_Write; 12940 } else { 12941 Stack = &DataSegStack; 12942 SectionFlags |= ASTContext::PSF_Write; 12943 } 12944 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12945 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12946 SectionFlags |= ASTContext::PSF_Implicit; 12947 UnifySection(SA->getName(), SectionFlags, var); 12948 } else if (Stack->CurrentValue) { 12949 SectionFlags |= ASTContext::PSF_Implicit; 12950 auto SectionName = Stack->CurrentValue->getString(); 12951 var->addAttr(SectionAttr::CreateImplicit( 12952 Context, SectionName, Stack->CurrentPragmaLocation, 12953 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12954 if (UnifySection(SectionName, SectionFlags, var)) 12955 var->dropAttr<SectionAttr>(); 12956 } 12957 12958 // Apply the init_seg attribute if this has an initializer. If the 12959 // initializer turns out to not be dynamic, we'll end up ignoring this 12960 // attribute. 12961 if (CurInitSeg && var->getInit()) 12962 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12963 CurInitSegLoc, 12964 AttributeCommonInfo::AS_Pragma)); 12965 } 12966 12967 if (!var->getType()->isStructureType() && var->hasInit() && 12968 isa<InitListExpr>(var->getInit())) { 12969 const auto *ILE = cast<InitListExpr>(var->getInit()); 12970 unsigned NumInits = ILE->getNumInits(); 12971 if (NumInits > 2) 12972 for (unsigned I = 0; I < NumInits; ++I) { 12973 const auto *Init = ILE->getInit(I); 12974 if (!Init) 12975 break; 12976 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12977 if (!SL) 12978 break; 12979 12980 unsigned NumConcat = SL->getNumConcatenated(); 12981 // Diagnose missing comma in string array initialization. 12982 // Do not warn when all the elements in the initializer are concatenated 12983 // together. Do not warn for macros too. 12984 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12985 bool OnlyOneMissingComma = true; 12986 for (unsigned J = I + 1; J < NumInits; ++J) { 12987 const auto *Init = ILE->getInit(J); 12988 if (!Init) 12989 break; 12990 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12991 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12992 OnlyOneMissingComma = false; 12993 break; 12994 } 12995 } 12996 12997 if (OnlyOneMissingComma) { 12998 SmallVector<FixItHint, 1> Hints; 12999 for (unsigned i = 0; i < NumConcat - 1; ++i) 13000 Hints.push_back(FixItHint::CreateInsertion( 13001 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13002 13003 Diag(SL->getStrTokenLoc(1), 13004 diag::warn_concatenated_literal_array_init) 13005 << Hints; 13006 Diag(SL->getBeginLoc(), 13007 diag::note_concatenated_string_literal_silence); 13008 } 13009 // In any case, stop now. 13010 break; 13011 } 13012 } 13013 } 13014 13015 // All the following checks are C++ only. 13016 if (!getLangOpts().CPlusPlus) { 13017 // If this variable must be emitted, add it as an initializer for the 13018 // current module. 13019 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13020 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13021 return; 13022 } 13023 13024 QualType type = var->getType(); 13025 13026 if (var->hasAttr<BlocksAttr>()) 13027 getCurFunction()->addByrefBlockVar(var); 13028 13029 Expr *Init = var->getInit(); 13030 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13031 QualType baseType = Context.getBaseElementType(type); 13032 13033 // Check whether the initializer is sufficiently constant. 13034 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13035 (GlobalStorage || var->isConstexpr() || 13036 var->mightBeUsableInConstantExpressions(Context))) { 13037 // If this variable might have a constant initializer or might be usable in 13038 // constant expressions, check whether or not it actually is now. We can't 13039 // do this lazily, because the result might depend on things that change 13040 // later, such as which constexpr functions happen to be defined. 13041 SmallVector<PartialDiagnosticAt, 8> Notes; 13042 bool HasConstInit; 13043 if (!getLangOpts().CPlusPlus11) { 13044 // Prior to C++11, in contexts where a constant initializer is required, 13045 // the set of valid constant initializers is described by syntactic rules 13046 // in [expr.const]p2-6. 13047 // FIXME: Stricter checking for these rules would be useful for constinit / 13048 // -Wglobal-constructors. 13049 HasConstInit = checkConstInit(); 13050 13051 // Compute and cache the constant value, and remember that we have a 13052 // constant initializer. 13053 if (HasConstInit) { 13054 (void)var->checkForConstantInitialization(Notes); 13055 Notes.clear(); 13056 } else if (CacheCulprit) { 13057 Notes.emplace_back(CacheCulprit->getExprLoc(), 13058 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13059 Notes.back().second << CacheCulprit->getSourceRange(); 13060 } 13061 } else { 13062 // Evaluate the initializer to see if it's a constant initializer. 13063 HasConstInit = var->checkForConstantInitialization(Notes); 13064 } 13065 13066 if (HasConstInit) { 13067 // FIXME: Consider replacing the initializer with a ConstantExpr. 13068 } else if (var->isConstexpr()) { 13069 SourceLocation DiagLoc = var->getLocation(); 13070 // If the note doesn't add any useful information other than a source 13071 // location, fold it into the primary diagnostic. 13072 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13073 diag::note_invalid_subexpr_in_const_expr) { 13074 DiagLoc = Notes[0].first; 13075 Notes.clear(); 13076 } 13077 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13078 << var << Init->getSourceRange(); 13079 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13080 Diag(Notes[I].first, Notes[I].second); 13081 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13082 auto *Attr = var->getAttr<ConstInitAttr>(); 13083 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13084 << Init->getSourceRange(); 13085 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13086 << Attr->getRange() << Attr->isConstinit(); 13087 for (auto &it : Notes) 13088 Diag(it.first, it.second); 13089 } else if (IsGlobal && 13090 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13091 var->getLocation())) { 13092 // Warn about globals which don't have a constant initializer. Don't 13093 // warn about globals with a non-trivial destructor because we already 13094 // warned about them. 13095 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13096 if (!(RD && !RD->hasTrivialDestructor())) { 13097 // checkConstInit() here permits trivial default initialization even in 13098 // C++11 onwards, where such an initializer is not a constant initializer 13099 // but nonetheless doesn't require a global constructor. 13100 if (!checkConstInit()) 13101 Diag(var->getLocation(), diag::warn_global_constructor) 13102 << Init->getSourceRange(); 13103 } 13104 } 13105 } 13106 13107 // Require the destructor. 13108 if (!type->isDependentType()) 13109 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13110 FinalizeVarWithDestructor(var, recordType); 13111 13112 // If this variable must be emitted, add it as an initializer for the current 13113 // module. 13114 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13115 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13116 13117 // Build the bindings if this is a structured binding declaration. 13118 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13119 CheckCompleteDecompositionDeclaration(DD); 13120 } 13121 13122 /// Determines if a variable's alignment is dependent. 13123 static bool hasDependentAlignment(VarDecl *VD) { 13124 if (VD->getType()->isDependentType()) 13125 return true; 13126 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13127 if (I->isAlignmentDependent()) 13128 return true; 13129 return false; 13130 } 13131 13132 /// Check if VD needs to be dllexport/dllimport due to being in a 13133 /// dllexport/import function. 13134 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13135 assert(VD->isStaticLocal()); 13136 13137 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13138 13139 // Find outermost function when VD is in lambda function. 13140 while (FD && !getDLLAttr(FD) && 13141 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13142 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13143 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13144 } 13145 13146 if (!FD) 13147 return; 13148 13149 // Static locals inherit dll attributes from their function. 13150 if (Attr *A = getDLLAttr(FD)) { 13151 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13152 NewAttr->setInherited(true); 13153 VD->addAttr(NewAttr); 13154 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13155 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13156 NewAttr->setInherited(true); 13157 VD->addAttr(NewAttr); 13158 13159 // Export this function to enforce exporting this static variable even 13160 // if it is not used in this compilation unit. 13161 if (!FD->hasAttr<DLLExportAttr>()) 13162 FD->addAttr(NewAttr); 13163 13164 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13165 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13166 NewAttr->setInherited(true); 13167 VD->addAttr(NewAttr); 13168 } 13169 } 13170 13171 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13172 /// any semantic actions necessary after any initializer has been attached. 13173 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13174 // Note that we are no longer parsing the initializer for this declaration. 13175 ParsingInitForAutoVars.erase(ThisDecl); 13176 13177 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13178 if (!VD) 13179 return; 13180 13181 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13182 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13183 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13184 if (PragmaClangBSSSection.Valid) 13185 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13186 Context, PragmaClangBSSSection.SectionName, 13187 PragmaClangBSSSection.PragmaLocation, 13188 AttributeCommonInfo::AS_Pragma)); 13189 if (PragmaClangDataSection.Valid) 13190 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13191 Context, PragmaClangDataSection.SectionName, 13192 PragmaClangDataSection.PragmaLocation, 13193 AttributeCommonInfo::AS_Pragma)); 13194 if (PragmaClangRodataSection.Valid) 13195 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13196 Context, PragmaClangRodataSection.SectionName, 13197 PragmaClangRodataSection.PragmaLocation, 13198 AttributeCommonInfo::AS_Pragma)); 13199 if (PragmaClangRelroSection.Valid) 13200 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13201 Context, PragmaClangRelroSection.SectionName, 13202 PragmaClangRelroSection.PragmaLocation, 13203 AttributeCommonInfo::AS_Pragma)); 13204 } 13205 13206 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13207 for (auto *BD : DD->bindings()) { 13208 FinalizeDeclaration(BD); 13209 } 13210 } 13211 13212 checkAttributesAfterMerging(*this, *VD); 13213 13214 // Perform TLS alignment check here after attributes attached to the variable 13215 // which may affect the alignment have been processed. Only perform the check 13216 // if the target has a maximum TLS alignment (zero means no constraints). 13217 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13218 // Protect the check so that it's not performed on dependent types and 13219 // dependent alignments (we can't determine the alignment in that case). 13220 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13221 !VD->isInvalidDecl()) { 13222 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13223 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13224 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13225 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13226 << (unsigned)MaxAlignChars.getQuantity(); 13227 } 13228 } 13229 } 13230 13231 if (VD->isStaticLocal()) 13232 CheckStaticLocalForDllExport(VD); 13233 13234 // Perform check for initializers of device-side global variables. 13235 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13236 // 7.5). We must also apply the same checks to all __shared__ 13237 // variables whether they are local or not. CUDA also allows 13238 // constant initializers for __constant__ and __device__ variables. 13239 if (getLangOpts().CUDA) 13240 checkAllowedCUDAInitializer(VD); 13241 13242 // Grab the dllimport or dllexport attribute off of the VarDecl. 13243 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13244 13245 // Imported static data members cannot be defined out-of-line. 13246 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13247 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13248 VD->isThisDeclarationADefinition()) { 13249 // We allow definitions of dllimport class template static data members 13250 // with a warning. 13251 CXXRecordDecl *Context = 13252 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13253 bool IsClassTemplateMember = 13254 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13255 Context->getDescribedClassTemplate(); 13256 13257 Diag(VD->getLocation(), 13258 IsClassTemplateMember 13259 ? diag::warn_attribute_dllimport_static_field_definition 13260 : diag::err_attribute_dllimport_static_field_definition); 13261 Diag(IA->getLocation(), diag::note_attribute); 13262 if (!IsClassTemplateMember) 13263 VD->setInvalidDecl(); 13264 } 13265 } 13266 13267 // dllimport/dllexport variables cannot be thread local, their TLS index 13268 // isn't exported with the variable. 13269 if (DLLAttr && VD->getTLSKind()) { 13270 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13271 if (F && getDLLAttr(F)) { 13272 assert(VD->isStaticLocal()); 13273 // But if this is a static local in a dlimport/dllexport function, the 13274 // function will never be inlined, which means the var would never be 13275 // imported, so having it marked import/export is safe. 13276 } else { 13277 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13278 << DLLAttr; 13279 VD->setInvalidDecl(); 13280 } 13281 } 13282 13283 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13284 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13285 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13286 VD->dropAttr<UsedAttr>(); 13287 } 13288 } 13289 13290 const DeclContext *DC = VD->getDeclContext(); 13291 // If there's a #pragma GCC visibility in scope, and this isn't a class 13292 // member, set the visibility of this variable. 13293 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13294 AddPushedVisibilityAttribute(VD); 13295 13296 // FIXME: Warn on unused var template partial specializations. 13297 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13298 MarkUnusedFileScopedDecl(VD); 13299 13300 // Now we have parsed the initializer and can update the table of magic 13301 // tag values. 13302 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13303 !VD->getType()->isIntegralOrEnumerationType()) 13304 return; 13305 13306 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13307 const Expr *MagicValueExpr = VD->getInit(); 13308 if (!MagicValueExpr) { 13309 continue; 13310 } 13311 Optional<llvm::APSInt> MagicValueInt; 13312 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13313 Diag(I->getRange().getBegin(), 13314 diag::err_type_tag_for_datatype_not_ice) 13315 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13316 continue; 13317 } 13318 if (MagicValueInt->getActiveBits() > 64) { 13319 Diag(I->getRange().getBegin(), 13320 diag::err_type_tag_for_datatype_too_large) 13321 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13322 continue; 13323 } 13324 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13325 RegisterTypeTagForDatatype(I->getArgumentKind(), 13326 MagicValue, 13327 I->getMatchingCType(), 13328 I->getLayoutCompatible(), 13329 I->getMustBeNull()); 13330 } 13331 } 13332 13333 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13334 auto *VD = dyn_cast<VarDecl>(DD); 13335 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13336 } 13337 13338 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13339 ArrayRef<Decl *> Group) { 13340 SmallVector<Decl*, 8> Decls; 13341 13342 if (DS.isTypeSpecOwned()) 13343 Decls.push_back(DS.getRepAsDecl()); 13344 13345 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13346 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13347 bool DiagnosedMultipleDecomps = false; 13348 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13349 bool DiagnosedNonDeducedAuto = false; 13350 13351 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13352 if (Decl *D = Group[i]) { 13353 // For declarators, there are some additional syntactic-ish checks we need 13354 // to perform. 13355 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13356 if (!FirstDeclaratorInGroup) 13357 FirstDeclaratorInGroup = DD; 13358 if (!FirstDecompDeclaratorInGroup) 13359 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13360 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13361 !hasDeducedAuto(DD)) 13362 FirstNonDeducedAutoInGroup = DD; 13363 13364 if (FirstDeclaratorInGroup != DD) { 13365 // A decomposition declaration cannot be combined with any other 13366 // declaration in the same group. 13367 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13368 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13369 diag::err_decomp_decl_not_alone) 13370 << FirstDeclaratorInGroup->getSourceRange() 13371 << DD->getSourceRange(); 13372 DiagnosedMultipleDecomps = true; 13373 } 13374 13375 // A declarator that uses 'auto' in any way other than to declare a 13376 // variable with a deduced type cannot be combined with any other 13377 // declarator in the same group. 13378 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13379 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13380 diag::err_auto_non_deduced_not_alone) 13381 << FirstNonDeducedAutoInGroup->getType() 13382 ->hasAutoForTrailingReturnType() 13383 << FirstDeclaratorInGroup->getSourceRange() 13384 << DD->getSourceRange(); 13385 DiagnosedNonDeducedAuto = true; 13386 } 13387 } 13388 } 13389 13390 Decls.push_back(D); 13391 } 13392 } 13393 13394 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13395 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13396 handleTagNumbering(Tag, S); 13397 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13398 getLangOpts().CPlusPlus) 13399 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13400 } 13401 } 13402 13403 return BuildDeclaratorGroup(Decls); 13404 } 13405 13406 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13407 /// group, performing any necessary semantic checking. 13408 Sema::DeclGroupPtrTy 13409 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13410 // C++14 [dcl.spec.auto]p7: (DR1347) 13411 // If the type that replaces the placeholder type is not the same in each 13412 // deduction, the program is ill-formed. 13413 if (Group.size() > 1) { 13414 QualType Deduced; 13415 VarDecl *DeducedDecl = nullptr; 13416 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13417 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13418 if (!D || D->isInvalidDecl()) 13419 break; 13420 DeducedType *DT = D->getType()->getContainedDeducedType(); 13421 if (!DT || DT->getDeducedType().isNull()) 13422 continue; 13423 if (Deduced.isNull()) { 13424 Deduced = DT->getDeducedType(); 13425 DeducedDecl = D; 13426 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13427 auto *AT = dyn_cast<AutoType>(DT); 13428 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13429 diag::err_auto_different_deductions) 13430 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13431 << DeducedDecl->getDeclName() << DT->getDeducedType() 13432 << D->getDeclName(); 13433 if (DeducedDecl->hasInit()) 13434 Dia << DeducedDecl->getInit()->getSourceRange(); 13435 if (D->getInit()) 13436 Dia << D->getInit()->getSourceRange(); 13437 D->setInvalidDecl(); 13438 break; 13439 } 13440 } 13441 } 13442 13443 ActOnDocumentableDecls(Group); 13444 13445 return DeclGroupPtrTy::make( 13446 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13447 } 13448 13449 void Sema::ActOnDocumentableDecl(Decl *D) { 13450 ActOnDocumentableDecls(D); 13451 } 13452 13453 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13454 // Don't parse the comment if Doxygen diagnostics are ignored. 13455 if (Group.empty() || !Group[0]) 13456 return; 13457 13458 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13459 Group[0]->getLocation()) && 13460 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13461 Group[0]->getLocation())) 13462 return; 13463 13464 if (Group.size() >= 2) { 13465 // This is a decl group. Normally it will contain only declarations 13466 // produced from declarator list. But in case we have any definitions or 13467 // additional declaration references: 13468 // 'typedef struct S {} S;' 13469 // 'typedef struct S *S;' 13470 // 'struct S *pS;' 13471 // FinalizeDeclaratorGroup adds these as separate declarations. 13472 Decl *MaybeTagDecl = Group[0]; 13473 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13474 Group = Group.slice(1); 13475 } 13476 } 13477 13478 // FIMXE: We assume every Decl in the group is in the same file. 13479 // This is false when preprocessor constructs the group from decls in 13480 // different files (e. g. macros or #include). 13481 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13482 } 13483 13484 /// Common checks for a parameter-declaration that should apply to both function 13485 /// parameters and non-type template parameters. 13486 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13487 // Check that there are no default arguments inside the type of this 13488 // parameter. 13489 if (getLangOpts().CPlusPlus) 13490 CheckExtraCXXDefaultArguments(D); 13491 13492 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13493 if (D.getCXXScopeSpec().isSet()) { 13494 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13495 << D.getCXXScopeSpec().getRange(); 13496 } 13497 13498 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13499 // simple identifier except [...irrelevant cases...]. 13500 switch (D.getName().getKind()) { 13501 case UnqualifiedIdKind::IK_Identifier: 13502 break; 13503 13504 case UnqualifiedIdKind::IK_OperatorFunctionId: 13505 case UnqualifiedIdKind::IK_ConversionFunctionId: 13506 case UnqualifiedIdKind::IK_LiteralOperatorId: 13507 case UnqualifiedIdKind::IK_ConstructorName: 13508 case UnqualifiedIdKind::IK_DestructorName: 13509 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13510 case UnqualifiedIdKind::IK_DeductionGuideName: 13511 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13512 << GetNameForDeclarator(D).getName(); 13513 break; 13514 13515 case UnqualifiedIdKind::IK_TemplateId: 13516 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13517 // GetNameForDeclarator would not produce a useful name in this case. 13518 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13519 break; 13520 } 13521 } 13522 13523 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13524 /// to introduce parameters into function prototype scope. 13525 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13526 const DeclSpec &DS = D.getDeclSpec(); 13527 13528 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13529 13530 // C++03 [dcl.stc]p2 also permits 'auto'. 13531 StorageClass SC = SC_None; 13532 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13533 SC = SC_Register; 13534 // In C++11, the 'register' storage class specifier is deprecated. 13535 // In C++17, it is not allowed, but we tolerate it as an extension. 13536 if (getLangOpts().CPlusPlus11) { 13537 Diag(DS.getStorageClassSpecLoc(), 13538 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13539 : diag::warn_deprecated_register) 13540 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13541 } 13542 } else if (getLangOpts().CPlusPlus && 13543 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13544 SC = SC_Auto; 13545 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13546 Diag(DS.getStorageClassSpecLoc(), 13547 diag::err_invalid_storage_class_in_func_decl); 13548 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13549 } 13550 13551 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13552 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13553 << DeclSpec::getSpecifierName(TSCS); 13554 if (DS.isInlineSpecified()) 13555 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13556 << getLangOpts().CPlusPlus17; 13557 if (DS.hasConstexprSpecifier()) 13558 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13559 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13560 13561 DiagnoseFunctionSpecifiers(DS); 13562 13563 CheckFunctionOrTemplateParamDeclarator(S, D); 13564 13565 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13566 QualType parmDeclType = TInfo->getType(); 13567 13568 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13569 IdentifierInfo *II = D.getIdentifier(); 13570 if (II) { 13571 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13572 ForVisibleRedeclaration); 13573 LookupName(R, S); 13574 if (R.isSingleResult()) { 13575 NamedDecl *PrevDecl = R.getFoundDecl(); 13576 if (PrevDecl->isTemplateParameter()) { 13577 // Maybe we will complain about the shadowed template parameter. 13578 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13579 // Just pretend that we didn't see the previous declaration. 13580 PrevDecl = nullptr; 13581 } else if (S->isDeclScope(PrevDecl)) { 13582 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13583 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13584 13585 // Recover by removing the name 13586 II = nullptr; 13587 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13588 D.setInvalidType(true); 13589 } 13590 } 13591 } 13592 13593 // Temporarily put parameter variables in the translation unit, not 13594 // the enclosing context. This prevents them from accidentally 13595 // looking like class members in C++. 13596 ParmVarDecl *New = 13597 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13598 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13599 13600 if (D.isInvalidType()) 13601 New->setInvalidDecl(); 13602 13603 assert(S->isFunctionPrototypeScope()); 13604 assert(S->getFunctionPrototypeDepth() >= 1); 13605 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13606 S->getNextFunctionPrototypeIndex()); 13607 13608 // Add the parameter declaration into this scope. 13609 S->AddDecl(New); 13610 if (II) 13611 IdResolver.AddDecl(New); 13612 13613 ProcessDeclAttributes(S, New, D); 13614 13615 if (D.getDeclSpec().isModulePrivateSpecified()) 13616 Diag(New->getLocation(), diag::err_module_private_local) 13617 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13618 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13619 13620 if (New->hasAttr<BlocksAttr>()) { 13621 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13622 } 13623 13624 if (getLangOpts().OpenCL) 13625 deduceOpenCLAddressSpace(New); 13626 13627 return New; 13628 } 13629 13630 /// Synthesizes a variable for a parameter arising from a 13631 /// typedef. 13632 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13633 SourceLocation Loc, 13634 QualType T) { 13635 /* FIXME: setting StartLoc == Loc. 13636 Would it be worth to modify callers so as to provide proper source 13637 location for the unnamed parameters, embedding the parameter's type? */ 13638 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13639 T, Context.getTrivialTypeSourceInfo(T, Loc), 13640 SC_None, nullptr); 13641 Param->setImplicit(); 13642 return Param; 13643 } 13644 13645 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13646 // Don't diagnose unused-parameter errors in template instantiations; we 13647 // will already have done so in the template itself. 13648 if (inTemplateInstantiation()) 13649 return; 13650 13651 for (const ParmVarDecl *Parameter : Parameters) { 13652 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13653 !Parameter->hasAttr<UnusedAttr>()) { 13654 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13655 << Parameter->getDeclName(); 13656 } 13657 } 13658 } 13659 13660 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13661 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13662 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13663 return; 13664 13665 // Warn if the return value is pass-by-value and larger than the specified 13666 // threshold. 13667 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13668 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13669 if (Size > LangOpts.NumLargeByValueCopy) 13670 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13671 } 13672 13673 // Warn if any parameter is pass-by-value and larger than the specified 13674 // threshold. 13675 for (const ParmVarDecl *Parameter : Parameters) { 13676 QualType T = Parameter->getType(); 13677 if (T->isDependentType() || !T.isPODType(Context)) 13678 continue; 13679 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13680 if (Size > LangOpts.NumLargeByValueCopy) 13681 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13682 << Parameter << Size; 13683 } 13684 } 13685 13686 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13687 SourceLocation NameLoc, IdentifierInfo *Name, 13688 QualType T, TypeSourceInfo *TSInfo, 13689 StorageClass SC) { 13690 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13691 if (getLangOpts().ObjCAutoRefCount && 13692 T.getObjCLifetime() == Qualifiers::OCL_None && 13693 T->isObjCLifetimeType()) { 13694 13695 Qualifiers::ObjCLifetime lifetime; 13696 13697 // Special cases for arrays: 13698 // - if it's const, use __unsafe_unretained 13699 // - otherwise, it's an error 13700 if (T->isArrayType()) { 13701 if (!T.isConstQualified()) { 13702 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13703 DelayedDiagnostics.add( 13704 sema::DelayedDiagnostic::makeForbiddenType( 13705 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13706 else 13707 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13708 << TSInfo->getTypeLoc().getSourceRange(); 13709 } 13710 lifetime = Qualifiers::OCL_ExplicitNone; 13711 } else { 13712 lifetime = T->getObjCARCImplicitLifetime(); 13713 } 13714 T = Context.getLifetimeQualifiedType(T, lifetime); 13715 } 13716 13717 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13718 Context.getAdjustedParameterType(T), 13719 TSInfo, SC, nullptr); 13720 13721 // Make a note if we created a new pack in the scope of a lambda, so that 13722 // we know that references to that pack must also be expanded within the 13723 // lambda scope. 13724 if (New->isParameterPack()) 13725 if (auto *LSI = getEnclosingLambda()) 13726 LSI->LocalPacks.push_back(New); 13727 13728 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13729 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13730 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13731 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13732 13733 // Parameters can not be abstract class types. 13734 // For record types, this is done by the AbstractClassUsageDiagnoser once 13735 // the class has been completely parsed. 13736 if (!CurContext->isRecord() && 13737 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13738 AbstractParamType)) 13739 New->setInvalidDecl(); 13740 13741 // Parameter declarators cannot be interface types. All ObjC objects are 13742 // passed by reference. 13743 if (T->isObjCObjectType()) { 13744 SourceLocation TypeEndLoc = 13745 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13746 Diag(NameLoc, 13747 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13748 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13749 T = Context.getObjCObjectPointerType(T); 13750 New->setType(T); 13751 } 13752 13753 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13754 // duration shall not be qualified by an address-space qualifier." 13755 // Since all parameters have automatic store duration, they can not have 13756 // an address space. 13757 if (T.getAddressSpace() != LangAS::Default && 13758 // OpenCL allows function arguments declared to be an array of a type 13759 // to be qualified with an address space. 13760 !(getLangOpts().OpenCL && 13761 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13762 Diag(NameLoc, diag::err_arg_with_address_space); 13763 New->setInvalidDecl(); 13764 } 13765 13766 // PPC MMA non-pointer types are not allowed as function argument types. 13767 if (Context.getTargetInfo().getTriple().isPPC64() && 13768 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13769 New->setInvalidDecl(); 13770 } 13771 13772 return New; 13773 } 13774 13775 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13776 SourceLocation LocAfterDecls) { 13777 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13778 13779 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13780 // for a K&R function. 13781 if (!FTI.hasPrototype) { 13782 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13783 --i; 13784 if (FTI.Params[i].Param == nullptr) { 13785 SmallString<256> Code; 13786 llvm::raw_svector_ostream(Code) 13787 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13788 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13789 << FTI.Params[i].Ident 13790 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13791 13792 // Implicitly declare the argument as type 'int' for lack of a better 13793 // type. 13794 AttributeFactory attrs; 13795 DeclSpec DS(attrs); 13796 const char* PrevSpec; // unused 13797 unsigned DiagID; // unused 13798 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13799 DiagID, Context.getPrintingPolicy()); 13800 // Use the identifier location for the type source range. 13801 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13802 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13803 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13804 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13805 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13806 } 13807 } 13808 } 13809 } 13810 13811 Decl * 13812 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13813 MultiTemplateParamsArg TemplateParameterLists, 13814 SkipBodyInfo *SkipBody) { 13815 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13816 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13817 Scope *ParentScope = FnBodyScope->getParent(); 13818 13819 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13820 // we define a non-templated function definition, we will create a declaration 13821 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13822 // The base function declaration will have the equivalent of an `omp declare 13823 // variant` annotation which specifies the mangled definition as a 13824 // specialization function under the OpenMP context defined as part of the 13825 // `omp begin declare variant`. 13826 SmallVector<FunctionDecl *, 4> Bases; 13827 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13828 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13829 ParentScope, D, TemplateParameterLists, Bases); 13830 13831 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13832 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13833 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13834 13835 if (!Bases.empty()) 13836 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13837 13838 return Dcl; 13839 } 13840 13841 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13842 Consumer.HandleInlineFunctionDefinition(D); 13843 } 13844 13845 static bool 13846 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13847 const FunctionDecl *&PossiblePrototype) { 13848 // Don't warn about invalid declarations. 13849 if (FD->isInvalidDecl()) 13850 return false; 13851 13852 // Or declarations that aren't global. 13853 if (!FD->isGlobal()) 13854 return false; 13855 13856 // Don't warn about C++ member functions. 13857 if (isa<CXXMethodDecl>(FD)) 13858 return false; 13859 13860 // Don't warn about 'main'. 13861 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13862 if (IdentifierInfo *II = FD->getIdentifier()) 13863 if (II->isStr("main")) 13864 return false; 13865 13866 // Don't warn about inline functions. 13867 if (FD->isInlined()) 13868 return false; 13869 13870 // Don't warn about function templates. 13871 if (FD->getDescribedFunctionTemplate()) 13872 return false; 13873 13874 // Don't warn about function template specializations. 13875 if (FD->isFunctionTemplateSpecialization()) 13876 return false; 13877 13878 // Don't warn for OpenCL kernels. 13879 if (FD->hasAttr<OpenCLKernelAttr>()) 13880 return false; 13881 13882 // Don't warn on explicitly deleted functions. 13883 if (FD->isDeleted()) 13884 return false; 13885 13886 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13887 Prev; Prev = Prev->getPreviousDecl()) { 13888 // Ignore any declarations that occur in function or method 13889 // scope, because they aren't visible from the header. 13890 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13891 continue; 13892 13893 PossiblePrototype = Prev; 13894 return Prev->getType()->isFunctionNoProtoType(); 13895 } 13896 13897 return true; 13898 } 13899 13900 void 13901 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13902 const FunctionDecl *EffectiveDefinition, 13903 SkipBodyInfo *SkipBody) { 13904 const FunctionDecl *Definition = EffectiveDefinition; 13905 if (!Definition && 13906 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13907 return; 13908 13909 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13910 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13911 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13912 // A merged copy of the same function, instantiated as a member of 13913 // the same class, is OK. 13914 if (declaresSameEntity(OrigFD, OrigDef) && 13915 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13916 cast<Decl>(FD->getLexicalDeclContext()))) 13917 return; 13918 } 13919 } 13920 } 13921 13922 if (canRedefineFunction(Definition, getLangOpts())) 13923 return; 13924 13925 // Don't emit an error when this is redefinition of a typo-corrected 13926 // definition. 13927 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13928 return; 13929 13930 // If we don't have a visible definition of the function, and it's inline or 13931 // a template, skip the new definition. 13932 if (SkipBody && !hasVisibleDefinition(Definition) && 13933 (Definition->getFormalLinkage() == InternalLinkage || 13934 Definition->isInlined() || 13935 Definition->getDescribedFunctionTemplate() || 13936 Definition->getNumTemplateParameterLists())) { 13937 SkipBody->ShouldSkip = true; 13938 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13939 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13940 makeMergedDefinitionVisible(TD); 13941 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13942 return; 13943 } 13944 13945 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13946 Definition->getStorageClass() == SC_Extern) 13947 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13948 << FD << getLangOpts().CPlusPlus; 13949 else 13950 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13951 13952 Diag(Definition->getLocation(), diag::note_previous_definition); 13953 FD->setInvalidDecl(); 13954 } 13955 13956 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13957 Sema &S) { 13958 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13959 13960 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13961 LSI->CallOperator = CallOperator; 13962 LSI->Lambda = LambdaClass; 13963 LSI->ReturnType = CallOperator->getReturnType(); 13964 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13965 13966 if (LCD == LCD_None) 13967 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13968 else if (LCD == LCD_ByCopy) 13969 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13970 else if (LCD == LCD_ByRef) 13971 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13972 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13973 13974 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13975 LSI->Mutable = !CallOperator->isConst(); 13976 13977 // Add the captures to the LSI so they can be noted as already 13978 // captured within tryCaptureVar. 13979 auto I = LambdaClass->field_begin(); 13980 for (const auto &C : LambdaClass->captures()) { 13981 if (C.capturesVariable()) { 13982 VarDecl *VD = C.getCapturedVar(); 13983 if (VD->isInitCapture()) 13984 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13985 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13986 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13987 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13988 /*EllipsisLoc*/C.isPackExpansion() 13989 ? C.getEllipsisLoc() : SourceLocation(), 13990 I->getType(), /*Invalid*/false); 13991 13992 } else if (C.capturesThis()) { 13993 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13994 C.getCaptureKind() == LCK_StarThis); 13995 } else { 13996 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13997 I->getType()); 13998 } 13999 ++I; 14000 } 14001 } 14002 14003 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14004 SkipBodyInfo *SkipBody) { 14005 if (!D) { 14006 // Parsing the function declaration failed in some way. Push on a fake scope 14007 // anyway so we can try to parse the function body. 14008 PushFunctionScope(); 14009 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14010 return D; 14011 } 14012 14013 FunctionDecl *FD = nullptr; 14014 14015 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14016 FD = FunTmpl->getTemplatedDecl(); 14017 else 14018 FD = cast<FunctionDecl>(D); 14019 14020 // Do not push if it is a lambda because one is already pushed when building 14021 // the lambda in ActOnStartOfLambdaDefinition(). 14022 if (!isLambdaCallOperator(FD)) 14023 PushExpressionEvaluationContext( 14024 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14025 : ExprEvalContexts.back().Context); 14026 14027 // Check for defining attributes before the check for redefinition. 14028 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14029 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14030 FD->dropAttr<AliasAttr>(); 14031 FD->setInvalidDecl(); 14032 } 14033 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14034 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14035 FD->dropAttr<IFuncAttr>(); 14036 FD->setInvalidDecl(); 14037 } 14038 14039 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14040 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14041 Ctor->isDefaultConstructor() && 14042 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14043 // If this is an MS ABI dllexport default constructor, instantiate any 14044 // default arguments. 14045 InstantiateDefaultCtorDefaultArgs(Ctor); 14046 } 14047 } 14048 14049 // See if this is a redefinition. If 'will have body' (or similar) is already 14050 // set, then these checks were already performed when it was set. 14051 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14052 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14053 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14054 14055 // If we're skipping the body, we're done. Don't enter the scope. 14056 if (SkipBody && SkipBody->ShouldSkip) 14057 return D; 14058 } 14059 14060 // Mark this function as "will have a body eventually". This lets users to 14061 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14062 // this function. 14063 FD->setWillHaveBody(); 14064 14065 // If we are instantiating a generic lambda call operator, push 14066 // a LambdaScopeInfo onto the function stack. But use the information 14067 // that's already been calculated (ActOnLambdaExpr) to prime the current 14068 // LambdaScopeInfo. 14069 // When the template operator is being specialized, the LambdaScopeInfo, 14070 // has to be properly restored so that tryCaptureVariable doesn't try 14071 // and capture any new variables. In addition when calculating potential 14072 // captures during transformation of nested lambdas, it is necessary to 14073 // have the LSI properly restored. 14074 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14075 assert(inTemplateInstantiation() && 14076 "There should be an active template instantiation on the stack " 14077 "when instantiating a generic lambda!"); 14078 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14079 } else { 14080 // Enter a new function scope 14081 PushFunctionScope(); 14082 } 14083 14084 // Builtin functions cannot be defined. 14085 if (unsigned BuiltinID = FD->getBuiltinID()) { 14086 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14087 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14088 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14089 FD->setInvalidDecl(); 14090 } 14091 } 14092 14093 // The return type of a function definition must be complete 14094 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14095 QualType ResultType = FD->getReturnType(); 14096 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14097 !FD->isInvalidDecl() && 14098 RequireCompleteType(FD->getLocation(), ResultType, 14099 diag::err_func_def_incomplete_result)) 14100 FD->setInvalidDecl(); 14101 14102 if (FnBodyScope) 14103 PushDeclContext(FnBodyScope, FD); 14104 14105 // Check the validity of our function parameters 14106 CheckParmsForFunctionDef(FD->parameters(), 14107 /*CheckParameterNames=*/true); 14108 14109 // Add non-parameter declarations already in the function to the current 14110 // scope. 14111 if (FnBodyScope) { 14112 for (Decl *NPD : FD->decls()) { 14113 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14114 if (!NonParmDecl) 14115 continue; 14116 assert(!isa<ParmVarDecl>(NonParmDecl) && 14117 "parameters should not be in newly created FD yet"); 14118 14119 // If the decl has a name, make it accessible in the current scope. 14120 if (NonParmDecl->getDeclName()) 14121 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14122 14123 // Similarly, dive into enums and fish their constants out, making them 14124 // accessible in this scope. 14125 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14126 for (auto *EI : ED->enumerators()) 14127 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14128 } 14129 } 14130 } 14131 14132 // Introduce our parameters into the function scope 14133 for (auto Param : FD->parameters()) { 14134 Param->setOwningFunction(FD); 14135 14136 // If this has an identifier, add it to the scope stack. 14137 if (Param->getIdentifier() && FnBodyScope) { 14138 CheckShadow(FnBodyScope, Param); 14139 14140 PushOnScopeChains(Param, FnBodyScope); 14141 } 14142 } 14143 14144 // Ensure that the function's exception specification is instantiated. 14145 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14146 ResolveExceptionSpec(D->getLocation(), FPT); 14147 14148 // dllimport cannot be applied to non-inline function definitions. 14149 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14150 !FD->isTemplateInstantiation()) { 14151 assert(!FD->hasAttr<DLLExportAttr>()); 14152 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14153 FD->setInvalidDecl(); 14154 return D; 14155 } 14156 // We want to attach documentation to original Decl (which might be 14157 // a function template). 14158 ActOnDocumentableDecl(D); 14159 if (getCurLexicalContext()->isObjCContainer() && 14160 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14161 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14162 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14163 14164 return D; 14165 } 14166 14167 /// Given the set of return statements within a function body, 14168 /// compute the variables that are subject to the named return value 14169 /// optimization. 14170 /// 14171 /// Each of the variables that is subject to the named return value 14172 /// optimization will be marked as NRVO variables in the AST, and any 14173 /// return statement that has a marked NRVO variable as its NRVO candidate can 14174 /// use the named return value optimization. 14175 /// 14176 /// This function applies a very simplistic algorithm for NRVO: if every return 14177 /// statement in the scope of a variable has the same NRVO candidate, that 14178 /// candidate is an NRVO variable. 14179 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14180 ReturnStmt **Returns = Scope->Returns.data(); 14181 14182 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14183 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14184 if (!NRVOCandidate->isNRVOVariable()) 14185 Returns[I]->setNRVOCandidate(nullptr); 14186 } 14187 } 14188 } 14189 14190 bool Sema::canDelayFunctionBody(const Declarator &D) { 14191 // We can't delay parsing the body of a constexpr function template (yet). 14192 if (D.getDeclSpec().hasConstexprSpecifier()) 14193 return false; 14194 14195 // We can't delay parsing the body of a function template with a deduced 14196 // return type (yet). 14197 if (D.getDeclSpec().hasAutoTypeSpec()) { 14198 // If the placeholder introduces a non-deduced trailing return type, 14199 // we can still delay parsing it. 14200 if (D.getNumTypeObjects()) { 14201 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14202 if (Outer.Kind == DeclaratorChunk::Function && 14203 Outer.Fun.hasTrailingReturnType()) { 14204 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14205 return Ty.isNull() || !Ty->isUndeducedType(); 14206 } 14207 } 14208 return false; 14209 } 14210 14211 return true; 14212 } 14213 14214 bool Sema::canSkipFunctionBody(Decl *D) { 14215 // We cannot skip the body of a function (or function template) which is 14216 // constexpr, since we may need to evaluate its body in order to parse the 14217 // rest of the file. 14218 // We cannot skip the body of a function with an undeduced return type, 14219 // because any callers of that function need to know the type. 14220 if (const FunctionDecl *FD = D->getAsFunction()) { 14221 if (FD->isConstexpr()) 14222 return false; 14223 // We can't simply call Type::isUndeducedType here, because inside template 14224 // auto can be deduced to a dependent type, which is not considered 14225 // "undeduced". 14226 if (FD->getReturnType()->getContainedDeducedType()) 14227 return false; 14228 } 14229 return Consumer.shouldSkipFunctionBody(D); 14230 } 14231 14232 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14233 if (!Decl) 14234 return nullptr; 14235 if (FunctionDecl *FD = Decl->getAsFunction()) 14236 FD->setHasSkippedBody(); 14237 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14238 MD->setHasSkippedBody(); 14239 return Decl; 14240 } 14241 14242 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14243 return ActOnFinishFunctionBody(D, BodyArg, false); 14244 } 14245 14246 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14247 /// body. 14248 class ExitFunctionBodyRAII { 14249 public: 14250 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14251 ~ExitFunctionBodyRAII() { 14252 if (!IsLambda) 14253 S.PopExpressionEvaluationContext(); 14254 } 14255 14256 private: 14257 Sema &S; 14258 bool IsLambda = false; 14259 }; 14260 14261 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14262 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14263 14264 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14265 if (EscapeInfo.count(BD)) 14266 return EscapeInfo[BD]; 14267 14268 bool R = false; 14269 const BlockDecl *CurBD = BD; 14270 14271 do { 14272 R = !CurBD->doesNotEscape(); 14273 if (R) 14274 break; 14275 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14276 } while (CurBD); 14277 14278 return EscapeInfo[BD] = R; 14279 }; 14280 14281 // If the location where 'self' is implicitly retained is inside a escaping 14282 // block, emit a diagnostic. 14283 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14284 S.ImplicitlyRetainedSelfLocs) 14285 if (IsOrNestedInEscapingBlock(P.second)) 14286 S.Diag(P.first, diag::warn_implicitly_retains_self) 14287 << FixItHint::CreateInsertion(P.first, "self->"); 14288 } 14289 14290 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14291 bool IsInstantiation) { 14292 FunctionScopeInfo *FSI = getCurFunction(); 14293 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14294 14295 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14296 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14297 14298 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14299 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14300 14301 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14302 CheckCompletedCoroutineBody(FD, Body); 14303 14304 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14305 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14306 // meant to pop the context added in ActOnStartOfFunctionDef(). 14307 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14308 14309 if (FD) { 14310 FD->setBody(Body); 14311 FD->setWillHaveBody(false); 14312 14313 if (getLangOpts().CPlusPlus14) { 14314 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14315 FD->getReturnType()->isUndeducedType()) { 14316 // If the function has a deduced result type but contains no 'return' 14317 // statements, the result type as written must be exactly 'auto', and 14318 // the deduced result type is 'void'. 14319 if (!FD->getReturnType()->getAs<AutoType>()) { 14320 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14321 << FD->getReturnType(); 14322 FD->setInvalidDecl(); 14323 } else { 14324 // Substitute 'void' for the 'auto' in the type. 14325 TypeLoc ResultType = getReturnTypeLoc(FD); 14326 Context.adjustDeducedFunctionResultType( 14327 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14328 } 14329 } 14330 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14331 // In C++11, we don't use 'auto' deduction rules for lambda call 14332 // operators because we don't support return type deduction. 14333 auto *LSI = getCurLambda(); 14334 if (LSI->HasImplicitReturnType) { 14335 deduceClosureReturnType(*LSI); 14336 14337 // C++11 [expr.prim.lambda]p4: 14338 // [...] if there are no return statements in the compound-statement 14339 // [the deduced type is] the type void 14340 QualType RetType = 14341 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14342 14343 // Update the return type to the deduced type. 14344 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14345 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14346 Proto->getExtProtoInfo())); 14347 } 14348 } 14349 14350 // If the function implicitly returns zero (like 'main') or is naked, 14351 // don't complain about missing return statements. 14352 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14353 WP.disableCheckFallThrough(); 14354 14355 // MSVC permits the use of pure specifier (=0) on function definition, 14356 // defined at class scope, warn about this non-standard construct. 14357 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14358 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14359 14360 if (!FD->isInvalidDecl()) { 14361 // Don't diagnose unused parameters of defaulted or deleted functions. 14362 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14363 DiagnoseUnusedParameters(FD->parameters()); 14364 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14365 FD->getReturnType(), FD); 14366 14367 // If this is a structor, we need a vtable. 14368 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14369 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14370 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14371 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14372 14373 // Try to apply the named return value optimization. We have to check 14374 // if we can do this here because lambdas keep return statements around 14375 // to deduce an implicit return type. 14376 if (FD->getReturnType()->isRecordType() && 14377 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14378 computeNRVO(Body, FSI); 14379 } 14380 14381 // GNU warning -Wmissing-prototypes: 14382 // Warn if a global function is defined without a previous 14383 // prototype declaration. This warning is issued even if the 14384 // definition itself provides a prototype. The aim is to detect 14385 // global functions that fail to be declared in header files. 14386 const FunctionDecl *PossiblePrototype = nullptr; 14387 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14388 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14389 14390 if (PossiblePrototype) { 14391 // We found a declaration that is not a prototype, 14392 // but that could be a zero-parameter prototype 14393 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14394 TypeLoc TL = TI->getTypeLoc(); 14395 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14396 Diag(PossiblePrototype->getLocation(), 14397 diag::note_declaration_not_a_prototype) 14398 << (FD->getNumParams() != 0) 14399 << (FD->getNumParams() == 0 14400 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14401 : FixItHint{}); 14402 } 14403 } else { 14404 // Returns true if the token beginning at this Loc is `const`. 14405 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14406 const LangOptions &LangOpts) { 14407 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14408 if (LocInfo.first.isInvalid()) 14409 return false; 14410 14411 bool Invalid = false; 14412 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14413 if (Invalid) 14414 return false; 14415 14416 if (LocInfo.second > Buffer.size()) 14417 return false; 14418 14419 const char *LexStart = Buffer.data() + LocInfo.second; 14420 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14421 14422 return StartTok.consume_front("const") && 14423 (StartTok.empty() || isWhitespace(StartTok[0]) || 14424 StartTok.startswith("/*") || StartTok.startswith("//")); 14425 }; 14426 14427 auto findBeginLoc = [&]() { 14428 // If the return type has `const` qualifier, we want to insert 14429 // `static` before `const` (and not before the typename). 14430 if ((FD->getReturnType()->isAnyPointerType() && 14431 FD->getReturnType()->getPointeeType().isConstQualified()) || 14432 FD->getReturnType().isConstQualified()) { 14433 // But only do this if we can determine where the `const` is. 14434 14435 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14436 getLangOpts())) 14437 14438 return FD->getBeginLoc(); 14439 } 14440 return FD->getTypeSpecStartLoc(); 14441 }; 14442 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14443 << /* function */ 1 14444 << (FD->getStorageClass() == SC_None 14445 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14446 : FixItHint{}); 14447 } 14448 14449 // GNU warning -Wstrict-prototypes 14450 // Warn if K&R function is defined without a previous declaration. 14451 // This warning is issued only if the definition itself does not provide 14452 // a prototype. Only K&R definitions do not provide a prototype. 14453 if (!FD->hasWrittenPrototype()) { 14454 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14455 TypeLoc TL = TI->getTypeLoc(); 14456 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14457 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14458 } 14459 } 14460 14461 // Warn on CPUDispatch with an actual body. 14462 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14463 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14464 if (!CmpndBody->body_empty()) 14465 Diag(CmpndBody->body_front()->getBeginLoc(), 14466 diag::warn_dispatch_body_ignored); 14467 14468 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14469 const CXXMethodDecl *KeyFunction; 14470 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14471 MD->isVirtual() && 14472 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14473 MD == KeyFunction->getCanonicalDecl()) { 14474 // Update the key-function state if necessary for this ABI. 14475 if (FD->isInlined() && 14476 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14477 Context.setNonKeyFunction(MD); 14478 14479 // If the newly-chosen key function is already defined, then we 14480 // need to mark the vtable as used retroactively. 14481 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14482 const FunctionDecl *Definition; 14483 if (KeyFunction && KeyFunction->isDefined(Definition)) 14484 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14485 } else { 14486 // We just defined they key function; mark the vtable as used. 14487 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14488 } 14489 } 14490 } 14491 14492 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14493 "Function parsing confused"); 14494 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14495 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14496 MD->setBody(Body); 14497 if (!MD->isInvalidDecl()) { 14498 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14499 MD->getReturnType(), MD); 14500 14501 if (Body) 14502 computeNRVO(Body, FSI); 14503 } 14504 if (FSI->ObjCShouldCallSuper) { 14505 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14506 << MD->getSelector().getAsString(); 14507 FSI->ObjCShouldCallSuper = false; 14508 } 14509 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14510 const ObjCMethodDecl *InitMethod = nullptr; 14511 bool isDesignated = 14512 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14513 assert(isDesignated && InitMethod); 14514 (void)isDesignated; 14515 14516 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14517 auto IFace = MD->getClassInterface(); 14518 if (!IFace) 14519 return false; 14520 auto SuperD = IFace->getSuperClass(); 14521 if (!SuperD) 14522 return false; 14523 return SuperD->getIdentifier() == 14524 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14525 }; 14526 // Don't issue this warning for unavailable inits or direct subclasses 14527 // of NSObject. 14528 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14529 Diag(MD->getLocation(), 14530 diag::warn_objc_designated_init_missing_super_call); 14531 Diag(InitMethod->getLocation(), 14532 diag::note_objc_designated_init_marked_here); 14533 } 14534 FSI->ObjCWarnForNoDesignatedInitChain = false; 14535 } 14536 if (FSI->ObjCWarnForNoInitDelegation) { 14537 // Don't issue this warning for unavaialable inits. 14538 if (!MD->isUnavailable()) 14539 Diag(MD->getLocation(), 14540 diag::warn_objc_secondary_init_missing_init_call); 14541 FSI->ObjCWarnForNoInitDelegation = false; 14542 } 14543 14544 diagnoseImplicitlyRetainedSelf(*this); 14545 } else { 14546 // Parsing the function declaration failed in some way. Pop the fake scope 14547 // we pushed on. 14548 PopFunctionScopeInfo(ActivePolicy, dcl); 14549 return nullptr; 14550 } 14551 14552 if (Body && FSI->HasPotentialAvailabilityViolations) 14553 DiagnoseUnguardedAvailabilityViolations(dcl); 14554 14555 assert(!FSI->ObjCShouldCallSuper && 14556 "This should only be set for ObjC methods, which should have been " 14557 "handled in the block above."); 14558 14559 // Verify and clean out per-function state. 14560 if (Body && (!FD || !FD->isDefaulted())) { 14561 // C++ constructors that have function-try-blocks can't have return 14562 // statements in the handlers of that block. (C++ [except.handle]p14) 14563 // Verify this. 14564 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14565 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14566 14567 // Verify that gotos and switch cases don't jump into scopes illegally. 14568 if (FSI->NeedsScopeChecking() && 14569 !PP.isCodeCompletionEnabled()) 14570 DiagnoseInvalidJumps(Body); 14571 14572 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14573 if (!Destructor->getParent()->isDependentType()) 14574 CheckDestructor(Destructor); 14575 14576 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14577 Destructor->getParent()); 14578 } 14579 14580 // If any errors have occurred, clear out any temporaries that may have 14581 // been leftover. This ensures that these temporaries won't be picked up for 14582 // deletion in some later function. 14583 if (hasUncompilableErrorOccurred() || 14584 getDiagnostics().getSuppressAllDiagnostics()) { 14585 DiscardCleanupsInEvaluationContext(); 14586 } 14587 if (!hasUncompilableErrorOccurred() && 14588 !isa<FunctionTemplateDecl>(dcl)) { 14589 // Since the body is valid, issue any analysis-based warnings that are 14590 // enabled. 14591 ActivePolicy = &WP; 14592 } 14593 14594 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14595 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14596 FD->setInvalidDecl(); 14597 14598 if (FD && FD->hasAttr<NakedAttr>()) { 14599 for (const Stmt *S : Body->children()) { 14600 // Allow local register variables without initializer as they don't 14601 // require prologue. 14602 bool RegisterVariables = false; 14603 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14604 for (const auto *Decl : DS->decls()) { 14605 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14606 RegisterVariables = 14607 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14608 if (!RegisterVariables) 14609 break; 14610 } 14611 } 14612 } 14613 if (RegisterVariables) 14614 continue; 14615 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14616 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14617 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14618 FD->setInvalidDecl(); 14619 break; 14620 } 14621 } 14622 } 14623 14624 assert(ExprCleanupObjects.size() == 14625 ExprEvalContexts.back().NumCleanupObjects && 14626 "Leftover temporaries in function"); 14627 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14628 assert(MaybeODRUseExprs.empty() && 14629 "Leftover expressions for odr-use checking"); 14630 } 14631 14632 if (!IsInstantiation) 14633 PopDeclContext(); 14634 14635 PopFunctionScopeInfo(ActivePolicy, dcl); 14636 // If any errors have occurred, clear out any temporaries that may have 14637 // been leftover. This ensures that these temporaries won't be picked up for 14638 // deletion in some later function. 14639 if (hasUncompilableErrorOccurred()) { 14640 DiscardCleanupsInEvaluationContext(); 14641 } 14642 14643 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14644 auto ES = getEmissionStatus(FD); 14645 if (ES == Sema::FunctionEmissionStatus::Emitted || 14646 ES == Sema::FunctionEmissionStatus::Unknown) 14647 DeclsToCheckForDeferredDiags.push_back(FD); 14648 } 14649 14650 return dcl; 14651 } 14652 14653 /// When we finish delayed parsing of an attribute, we must attach it to the 14654 /// relevant Decl. 14655 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14656 ParsedAttributes &Attrs) { 14657 // Always attach attributes to the underlying decl. 14658 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14659 D = TD->getTemplatedDecl(); 14660 ProcessDeclAttributeList(S, D, Attrs); 14661 14662 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14663 if (Method->isStatic()) 14664 checkThisInStaticMemberFunctionAttributes(Method); 14665 } 14666 14667 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14668 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14669 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14670 IdentifierInfo &II, Scope *S) { 14671 // Find the scope in which the identifier is injected and the corresponding 14672 // DeclContext. 14673 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14674 // In that case, we inject the declaration into the translation unit scope 14675 // instead. 14676 Scope *BlockScope = S; 14677 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14678 BlockScope = BlockScope->getParent(); 14679 14680 Scope *ContextScope = BlockScope; 14681 while (!ContextScope->getEntity()) 14682 ContextScope = ContextScope->getParent(); 14683 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14684 14685 // Before we produce a declaration for an implicitly defined 14686 // function, see whether there was a locally-scoped declaration of 14687 // this name as a function or variable. If so, use that 14688 // (non-visible) declaration, and complain about it. 14689 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14690 if (ExternCPrev) { 14691 // We still need to inject the function into the enclosing block scope so 14692 // that later (non-call) uses can see it. 14693 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14694 14695 // C89 footnote 38: 14696 // If in fact it is not defined as having type "function returning int", 14697 // the behavior is undefined. 14698 if (!isa<FunctionDecl>(ExternCPrev) || 14699 !Context.typesAreCompatible( 14700 cast<FunctionDecl>(ExternCPrev)->getType(), 14701 Context.getFunctionNoProtoType(Context.IntTy))) { 14702 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14703 << ExternCPrev << !getLangOpts().C99; 14704 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14705 return ExternCPrev; 14706 } 14707 } 14708 14709 // Extension in C99. Legal in C90, but warn about it. 14710 unsigned diag_id; 14711 if (II.getName().startswith("__builtin_")) 14712 diag_id = diag::warn_builtin_unknown; 14713 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14714 else if (getLangOpts().OpenCL) 14715 diag_id = diag::err_opencl_implicit_function_decl; 14716 else if (getLangOpts().C99) 14717 diag_id = diag::ext_implicit_function_decl; 14718 else 14719 diag_id = diag::warn_implicit_function_decl; 14720 Diag(Loc, diag_id) << &II; 14721 14722 // If we found a prior declaration of this function, don't bother building 14723 // another one. We've already pushed that one into scope, so there's nothing 14724 // more to do. 14725 if (ExternCPrev) 14726 return ExternCPrev; 14727 14728 // Because typo correction is expensive, only do it if the implicit 14729 // function declaration is going to be treated as an error. 14730 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14731 TypoCorrection Corrected; 14732 DeclFilterCCC<FunctionDecl> CCC{}; 14733 if (S && (Corrected = 14734 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14735 S, nullptr, CCC, CTK_NonError))) 14736 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14737 /*ErrorRecovery*/false); 14738 } 14739 14740 // Set a Declarator for the implicit definition: int foo(); 14741 const char *Dummy; 14742 AttributeFactory attrFactory; 14743 DeclSpec DS(attrFactory); 14744 unsigned DiagID; 14745 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14746 Context.getPrintingPolicy()); 14747 (void)Error; // Silence warning. 14748 assert(!Error && "Error setting up implicit decl!"); 14749 SourceLocation NoLoc; 14750 Declarator D(DS, DeclaratorContext::Block); 14751 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14752 /*IsAmbiguous=*/false, 14753 /*LParenLoc=*/NoLoc, 14754 /*Params=*/nullptr, 14755 /*NumParams=*/0, 14756 /*EllipsisLoc=*/NoLoc, 14757 /*RParenLoc=*/NoLoc, 14758 /*RefQualifierIsLvalueRef=*/true, 14759 /*RefQualifierLoc=*/NoLoc, 14760 /*MutableLoc=*/NoLoc, EST_None, 14761 /*ESpecRange=*/SourceRange(), 14762 /*Exceptions=*/nullptr, 14763 /*ExceptionRanges=*/nullptr, 14764 /*NumExceptions=*/0, 14765 /*NoexceptExpr=*/nullptr, 14766 /*ExceptionSpecTokens=*/nullptr, 14767 /*DeclsInPrototype=*/None, Loc, 14768 Loc, D), 14769 std::move(DS.getAttributes()), SourceLocation()); 14770 D.SetIdentifier(&II, Loc); 14771 14772 // Insert this function into the enclosing block scope. 14773 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14774 FD->setImplicit(); 14775 14776 AddKnownFunctionAttributes(FD); 14777 14778 return FD; 14779 } 14780 14781 /// If this function is a C++ replaceable global allocation function 14782 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14783 /// adds any function attributes that we know a priori based on the standard. 14784 /// 14785 /// We need to check for duplicate attributes both here and where user-written 14786 /// attributes are applied to declarations. 14787 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14788 FunctionDecl *FD) { 14789 if (FD->isInvalidDecl()) 14790 return; 14791 14792 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14793 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14794 return; 14795 14796 Optional<unsigned> AlignmentParam; 14797 bool IsNothrow = false; 14798 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14799 return; 14800 14801 // C++2a [basic.stc.dynamic.allocation]p4: 14802 // An allocation function that has a non-throwing exception specification 14803 // indicates failure by returning a null pointer value. Any other allocation 14804 // function never returns a null pointer value and indicates failure only by 14805 // throwing an exception [...] 14806 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14807 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14808 14809 // C++2a [basic.stc.dynamic.allocation]p2: 14810 // An allocation function attempts to allocate the requested amount of 14811 // storage. [...] If the request succeeds, the value returned by a 14812 // replaceable allocation function is a [...] pointer value p0 different 14813 // from any previously returned value p1 [...] 14814 // 14815 // However, this particular information is being added in codegen, 14816 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14817 14818 // C++2a [basic.stc.dynamic.allocation]p2: 14819 // An allocation function attempts to allocate the requested amount of 14820 // storage. If it is successful, it returns the address of the start of a 14821 // block of storage whose length in bytes is at least as large as the 14822 // requested size. 14823 if (!FD->hasAttr<AllocSizeAttr>()) { 14824 FD->addAttr(AllocSizeAttr::CreateImplicit( 14825 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14826 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14827 } 14828 14829 // C++2a [basic.stc.dynamic.allocation]p3: 14830 // For an allocation function [...], the pointer returned on a successful 14831 // call shall represent the address of storage that is aligned as follows: 14832 // (3.1) If the allocation function takes an argument of type 14833 // std::align_val_t, the storage will have the alignment 14834 // specified by the value of this argument. 14835 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14836 FD->addAttr(AllocAlignAttr::CreateImplicit( 14837 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14838 } 14839 14840 // FIXME: 14841 // C++2a [basic.stc.dynamic.allocation]p3: 14842 // For an allocation function [...], the pointer returned on a successful 14843 // call shall represent the address of storage that is aligned as follows: 14844 // (3.2) Otherwise, if the allocation function is named operator new[], 14845 // the storage is aligned for any object that does not have 14846 // new-extended alignment ([basic.align]) and is no larger than the 14847 // requested size. 14848 // (3.3) Otherwise, the storage is aligned for any object that does not 14849 // have new-extended alignment and is of the requested size. 14850 } 14851 14852 /// Adds any function attributes that we know a priori based on 14853 /// the declaration of this function. 14854 /// 14855 /// These attributes can apply both to implicitly-declared builtins 14856 /// (like __builtin___printf_chk) or to library-declared functions 14857 /// like NSLog or printf. 14858 /// 14859 /// We need to check for duplicate attributes both here and where user-written 14860 /// attributes are applied to declarations. 14861 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14862 if (FD->isInvalidDecl()) 14863 return; 14864 14865 // If this is a built-in function, map its builtin attributes to 14866 // actual attributes. 14867 if (unsigned BuiltinID = FD->getBuiltinID()) { 14868 // Handle printf-formatting attributes. 14869 unsigned FormatIdx; 14870 bool HasVAListArg; 14871 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14872 if (!FD->hasAttr<FormatAttr>()) { 14873 const char *fmt = "printf"; 14874 unsigned int NumParams = FD->getNumParams(); 14875 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14876 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14877 fmt = "NSString"; 14878 FD->addAttr(FormatAttr::CreateImplicit(Context, 14879 &Context.Idents.get(fmt), 14880 FormatIdx+1, 14881 HasVAListArg ? 0 : FormatIdx+2, 14882 FD->getLocation())); 14883 } 14884 } 14885 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14886 HasVAListArg)) { 14887 if (!FD->hasAttr<FormatAttr>()) 14888 FD->addAttr(FormatAttr::CreateImplicit(Context, 14889 &Context.Idents.get("scanf"), 14890 FormatIdx+1, 14891 HasVAListArg ? 0 : FormatIdx+2, 14892 FD->getLocation())); 14893 } 14894 14895 // Handle automatically recognized callbacks. 14896 SmallVector<int, 4> Encoding; 14897 if (!FD->hasAttr<CallbackAttr>() && 14898 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14899 FD->addAttr(CallbackAttr::CreateImplicit( 14900 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14901 14902 // Mark const if we don't care about errno and that is the only thing 14903 // preventing the function from being const. This allows IRgen to use LLVM 14904 // intrinsics for such functions. 14905 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14906 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14907 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14908 14909 // We make "fma" on some platforms const because we know it does not set 14910 // errno in those environments even though it could set errno based on the 14911 // C standard. 14912 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14913 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14914 !FD->hasAttr<ConstAttr>()) { 14915 switch (BuiltinID) { 14916 case Builtin::BI__builtin_fma: 14917 case Builtin::BI__builtin_fmaf: 14918 case Builtin::BI__builtin_fmal: 14919 case Builtin::BIfma: 14920 case Builtin::BIfmaf: 14921 case Builtin::BIfmal: 14922 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14923 break; 14924 default: 14925 break; 14926 } 14927 } 14928 14929 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14930 !FD->hasAttr<ReturnsTwiceAttr>()) 14931 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14932 FD->getLocation())); 14933 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14934 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14935 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14936 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14937 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14938 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14939 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14940 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14941 // Add the appropriate attribute, depending on the CUDA compilation mode 14942 // and which target the builtin belongs to. For example, during host 14943 // compilation, aux builtins are __device__, while the rest are __host__. 14944 if (getLangOpts().CUDAIsDevice != 14945 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14946 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14947 else 14948 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14949 } 14950 } 14951 14952 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14953 14954 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14955 // throw, add an implicit nothrow attribute to any extern "C" function we come 14956 // across. 14957 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14958 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14959 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14960 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14961 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14962 } 14963 14964 IdentifierInfo *Name = FD->getIdentifier(); 14965 if (!Name) 14966 return; 14967 if ((!getLangOpts().CPlusPlus && 14968 FD->getDeclContext()->isTranslationUnit()) || 14969 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14970 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14971 LinkageSpecDecl::lang_c)) { 14972 // Okay: this could be a libc/libm/Objective-C function we know 14973 // about. 14974 } else 14975 return; 14976 14977 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14978 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14979 // target-specific builtins, perhaps? 14980 if (!FD->hasAttr<FormatAttr>()) 14981 FD->addAttr(FormatAttr::CreateImplicit(Context, 14982 &Context.Idents.get("printf"), 2, 14983 Name->isStr("vasprintf") ? 0 : 3, 14984 FD->getLocation())); 14985 } 14986 14987 if (Name->isStr("__CFStringMakeConstantString")) { 14988 // We already have a __builtin___CFStringMakeConstantString, 14989 // but builds that use -fno-constant-cfstrings don't go through that. 14990 if (!FD->hasAttr<FormatArgAttr>()) 14991 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14992 FD->getLocation())); 14993 } 14994 } 14995 14996 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14997 TypeSourceInfo *TInfo) { 14998 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14999 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15000 15001 if (!TInfo) { 15002 assert(D.isInvalidType() && "no declarator info for valid type"); 15003 TInfo = Context.getTrivialTypeSourceInfo(T); 15004 } 15005 15006 // Scope manipulation handled by caller. 15007 TypedefDecl *NewTD = 15008 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15009 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15010 15011 // Bail out immediately if we have an invalid declaration. 15012 if (D.isInvalidType()) { 15013 NewTD->setInvalidDecl(); 15014 return NewTD; 15015 } 15016 15017 if (D.getDeclSpec().isModulePrivateSpecified()) { 15018 if (CurContext->isFunctionOrMethod()) 15019 Diag(NewTD->getLocation(), diag::err_module_private_local) 15020 << 2 << NewTD 15021 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15022 << FixItHint::CreateRemoval( 15023 D.getDeclSpec().getModulePrivateSpecLoc()); 15024 else 15025 NewTD->setModulePrivate(); 15026 } 15027 15028 // C++ [dcl.typedef]p8: 15029 // If the typedef declaration defines an unnamed class (or 15030 // enum), the first typedef-name declared by the declaration 15031 // to be that class type (or enum type) is used to denote the 15032 // class type (or enum type) for linkage purposes only. 15033 // We need to check whether the type was declared in the declaration. 15034 switch (D.getDeclSpec().getTypeSpecType()) { 15035 case TST_enum: 15036 case TST_struct: 15037 case TST_interface: 15038 case TST_union: 15039 case TST_class: { 15040 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15041 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15042 break; 15043 } 15044 15045 default: 15046 break; 15047 } 15048 15049 return NewTD; 15050 } 15051 15052 /// Check that this is a valid underlying type for an enum declaration. 15053 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15054 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15055 QualType T = TI->getType(); 15056 15057 if (T->isDependentType()) 15058 return false; 15059 15060 // This doesn't use 'isIntegralType' despite the error message mentioning 15061 // integral type because isIntegralType would also allow enum types in C. 15062 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15063 if (BT->isInteger()) 15064 return false; 15065 15066 if (T->isExtIntType()) 15067 return false; 15068 15069 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15070 } 15071 15072 /// Check whether this is a valid redeclaration of a previous enumeration. 15073 /// \return true if the redeclaration was invalid. 15074 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15075 QualType EnumUnderlyingTy, bool IsFixed, 15076 const EnumDecl *Prev) { 15077 if (IsScoped != Prev->isScoped()) { 15078 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15079 << Prev->isScoped(); 15080 Diag(Prev->getLocation(), diag::note_previous_declaration); 15081 return true; 15082 } 15083 15084 if (IsFixed && Prev->isFixed()) { 15085 if (!EnumUnderlyingTy->isDependentType() && 15086 !Prev->getIntegerType()->isDependentType() && 15087 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15088 Prev->getIntegerType())) { 15089 // TODO: Highlight the underlying type of the redeclaration. 15090 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15091 << EnumUnderlyingTy << Prev->getIntegerType(); 15092 Diag(Prev->getLocation(), diag::note_previous_declaration) 15093 << Prev->getIntegerTypeRange(); 15094 return true; 15095 } 15096 } else if (IsFixed != Prev->isFixed()) { 15097 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15098 << Prev->isFixed(); 15099 Diag(Prev->getLocation(), diag::note_previous_declaration); 15100 return true; 15101 } 15102 15103 return false; 15104 } 15105 15106 /// Get diagnostic %select index for tag kind for 15107 /// redeclaration diagnostic message. 15108 /// WARNING: Indexes apply to particular diagnostics only! 15109 /// 15110 /// \returns diagnostic %select index. 15111 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15112 switch (Tag) { 15113 case TTK_Struct: return 0; 15114 case TTK_Interface: return 1; 15115 case TTK_Class: return 2; 15116 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15117 } 15118 } 15119 15120 /// Determine if tag kind is a class-key compatible with 15121 /// class for redeclaration (class, struct, or __interface). 15122 /// 15123 /// \returns true iff the tag kind is compatible. 15124 static bool isClassCompatTagKind(TagTypeKind Tag) 15125 { 15126 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15127 } 15128 15129 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15130 TagTypeKind TTK) { 15131 if (isa<TypedefDecl>(PrevDecl)) 15132 return NTK_Typedef; 15133 else if (isa<TypeAliasDecl>(PrevDecl)) 15134 return NTK_TypeAlias; 15135 else if (isa<ClassTemplateDecl>(PrevDecl)) 15136 return NTK_Template; 15137 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15138 return NTK_TypeAliasTemplate; 15139 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15140 return NTK_TemplateTemplateArgument; 15141 switch (TTK) { 15142 case TTK_Struct: 15143 case TTK_Interface: 15144 case TTK_Class: 15145 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15146 case TTK_Union: 15147 return NTK_NonUnion; 15148 case TTK_Enum: 15149 return NTK_NonEnum; 15150 } 15151 llvm_unreachable("invalid TTK"); 15152 } 15153 15154 /// Determine whether a tag with a given kind is acceptable 15155 /// as a redeclaration of the given tag declaration. 15156 /// 15157 /// \returns true if the new tag kind is acceptable, false otherwise. 15158 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15159 TagTypeKind NewTag, bool isDefinition, 15160 SourceLocation NewTagLoc, 15161 const IdentifierInfo *Name) { 15162 // C++ [dcl.type.elab]p3: 15163 // The class-key or enum keyword present in the 15164 // elaborated-type-specifier shall agree in kind with the 15165 // declaration to which the name in the elaborated-type-specifier 15166 // refers. This rule also applies to the form of 15167 // elaborated-type-specifier that declares a class-name or 15168 // friend class since it can be construed as referring to the 15169 // definition of the class. Thus, in any 15170 // elaborated-type-specifier, the enum keyword shall be used to 15171 // refer to an enumeration (7.2), the union class-key shall be 15172 // used to refer to a union (clause 9), and either the class or 15173 // struct class-key shall be used to refer to a class (clause 9) 15174 // declared using the class or struct class-key. 15175 TagTypeKind OldTag = Previous->getTagKind(); 15176 if (OldTag != NewTag && 15177 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15178 return false; 15179 15180 // Tags are compatible, but we might still want to warn on mismatched tags. 15181 // Non-class tags can't be mismatched at this point. 15182 if (!isClassCompatTagKind(NewTag)) 15183 return true; 15184 15185 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15186 // by our warning analysis. We don't want to warn about mismatches with (eg) 15187 // declarations in system headers that are designed to be specialized, but if 15188 // a user asks us to warn, we should warn if their code contains mismatched 15189 // declarations. 15190 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15191 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15192 Loc); 15193 }; 15194 if (IsIgnoredLoc(NewTagLoc)) 15195 return true; 15196 15197 auto IsIgnored = [&](const TagDecl *Tag) { 15198 return IsIgnoredLoc(Tag->getLocation()); 15199 }; 15200 while (IsIgnored(Previous)) { 15201 Previous = Previous->getPreviousDecl(); 15202 if (!Previous) 15203 return true; 15204 OldTag = Previous->getTagKind(); 15205 } 15206 15207 bool isTemplate = false; 15208 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15209 isTemplate = Record->getDescribedClassTemplate(); 15210 15211 if (inTemplateInstantiation()) { 15212 if (OldTag != NewTag) { 15213 // In a template instantiation, do not offer fix-its for tag mismatches 15214 // since they usually mess up the template instead of fixing the problem. 15215 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15216 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15217 << getRedeclDiagFromTagKind(OldTag); 15218 // FIXME: Note previous location? 15219 } 15220 return true; 15221 } 15222 15223 if (isDefinition) { 15224 // On definitions, check all previous tags and issue a fix-it for each 15225 // one that doesn't match the current tag. 15226 if (Previous->getDefinition()) { 15227 // Don't suggest fix-its for redefinitions. 15228 return true; 15229 } 15230 15231 bool previousMismatch = false; 15232 for (const TagDecl *I : Previous->redecls()) { 15233 if (I->getTagKind() != NewTag) { 15234 // Ignore previous declarations for which the warning was disabled. 15235 if (IsIgnored(I)) 15236 continue; 15237 15238 if (!previousMismatch) { 15239 previousMismatch = true; 15240 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15241 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15242 << getRedeclDiagFromTagKind(I->getTagKind()); 15243 } 15244 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15245 << getRedeclDiagFromTagKind(NewTag) 15246 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15247 TypeWithKeyword::getTagTypeKindName(NewTag)); 15248 } 15249 } 15250 return true; 15251 } 15252 15253 // Identify the prevailing tag kind: this is the kind of the definition (if 15254 // there is a non-ignored definition), or otherwise the kind of the prior 15255 // (non-ignored) declaration. 15256 const TagDecl *PrevDef = Previous->getDefinition(); 15257 if (PrevDef && IsIgnored(PrevDef)) 15258 PrevDef = nullptr; 15259 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15260 if (Redecl->getTagKind() != NewTag) { 15261 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15262 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15263 << getRedeclDiagFromTagKind(OldTag); 15264 Diag(Redecl->getLocation(), diag::note_previous_use); 15265 15266 // If there is a previous definition, suggest a fix-it. 15267 if (PrevDef) { 15268 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15269 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15270 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15271 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15272 } 15273 } 15274 15275 return true; 15276 } 15277 15278 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15279 /// from an outer enclosing namespace or file scope inside a friend declaration. 15280 /// This should provide the commented out code in the following snippet: 15281 /// namespace N { 15282 /// struct X; 15283 /// namespace M { 15284 /// struct Y { friend struct /*N::*/ X; }; 15285 /// } 15286 /// } 15287 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15288 SourceLocation NameLoc) { 15289 // While the decl is in a namespace, do repeated lookup of that name and see 15290 // if we get the same namespace back. If we do not, continue until 15291 // translation unit scope, at which point we have a fully qualified NNS. 15292 SmallVector<IdentifierInfo *, 4> Namespaces; 15293 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15294 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15295 // This tag should be declared in a namespace, which can only be enclosed by 15296 // other namespaces. Bail if there's an anonymous namespace in the chain. 15297 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15298 if (!Namespace || Namespace->isAnonymousNamespace()) 15299 return FixItHint(); 15300 IdentifierInfo *II = Namespace->getIdentifier(); 15301 Namespaces.push_back(II); 15302 NamedDecl *Lookup = SemaRef.LookupSingleName( 15303 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15304 if (Lookup == Namespace) 15305 break; 15306 } 15307 15308 // Once we have all the namespaces, reverse them to go outermost first, and 15309 // build an NNS. 15310 SmallString<64> Insertion; 15311 llvm::raw_svector_ostream OS(Insertion); 15312 if (DC->isTranslationUnit()) 15313 OS << "::"; 15314 std::reverse(Namespaces.begin(), Namespaces.end()); 15315 for (auto *II : Namespaces) 15316 OS << II->getName() << "::"; 15317 return FixItHint::CreateInsertion(NameLoc, Insertion); 15318 } 15319 15320 /// Determine whether a tag originally declared in context \p OldDC can 15321 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15322 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15323 /// using-declaration). 15324 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15325 DeclContext *NewDC) { 15326 OldDC = OldDC->getRedeclContext(); 15327 NewDC = NewDC->getRedeclContext(); 15328 15329 if (OldDC->Equals(NewDC)) 15330 return true; 15331 15332 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15333 // encloses the other). 15334 if (S.getLangOpts().MSVCCompat && 15335 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15336 return true; 15337 15338 return false; 15339 } 15340 15341 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15342 /// former case, Name will be non-null. In the later case, Name will be null. 15343 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15344 /// reference/declaration/definition of a tag. 15345 /// 15346 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15347 /// trailing-type-specifier) other than one in an alias-declaration. 15348 /// 15349 /// \param SkipBody If non-null, will be set to indicate if the caller should 15350 /// skip the definition of this tag and treat it as if it were a declaration. 15351 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15352 SourceLocation KWLoc, CXXScopeSpec &SS, 15353 IdentifierInfo *Name, SourceLocation NameLoc, 15354 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15355 SourceLocation ModulePrivateLoc, 15356 MultiTemplateParamsArg TemplateParameterLists, 15357 bool &OwnedDecl, bool &IsDependent, 15358 SourceLocation ScopedEnumKWLoc, 15359 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15360 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15361 SkipBodyInfo *SkipBody) { 15362 // If this is not a definition, it must have a name. 15363 IdentifierInfo *OrigName = Name; 15364 assert((Name != nullptr || TUK == TUK_Definition) && 15365 "Nameless record must be a definition!"); 15366 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15367 15368 OwnedDecl = false; 15369 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15370 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15371 15372 // FIXME: Check member specializations more carefully. 15373 bool isMemberSpecialization = false; 15374 bool Invalid = false; 15375 15376 // We only need to do this matching if we have template parameters 15377 // or a scope specifier, which also conveniently avoids this work 15378 // for non-C++ cases. 15379 if (TemplateParameterLists.size() > 0 || 15380 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15381 if (TemplateParameterList *TemplateParams = 15382 MatchTemplateParametersToScopeSpecifier( 15383 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15384 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15385 if (Kind == TTK_Enum) { 15386 Diag(KWLoc, diag::err_enum_template); 15387 return nullptr; 15388 } 15389 15390 if (TemplateParams->size() > 0) { 15391 // This is a declaration or definition of a class template (which may 15392 // be a member of another template). 15393 15394 if (Invalid) 15395 return nullptr; 15396 15397 OwnedDecl = false; 15398 DeclResult Result = CheckClassTemplate( 15399 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15400 AS, ModulePrivateLoc, 15401 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15402 TemplateParameterLists.data(), SkipBody); 15403 return Result.get(); 15404 } else { 15405 // The "template<>" header is extraneous. 15406 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15407 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15408 isMemberSpecialization = true; 15409 } 15410 } 15411 15412 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15413 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15414 return nullptr; 15415 } 15416 15417 // Figure out the underlying type if this a enum declaration. We need to do 15418 // this early, because it's needed to detect if this is an incompatible 15419 // redeclaration. 15420 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15421 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15422 15423 if (Kind == TTK_Enum) { 15424 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15425 // No underlying type explicitly specified, or we failed to parse the 15426 // type, default to int. 15427 EnumUnderlying = Context.IntTy.getTypePtr(); 15428 } else if (UnderlyingType.get()) { 15429 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15430 // integral type; any cv-qualification is ignored. 15431 TypeSourceInfo *TI = nullptr; 15432 GetTypeFromParser(UnderlyingType.get(), &TI); 15433 EnumUnderlying = TI; 15434 15435 if (CheckEnumUnderlyingType(TI)) 15436 // Recover by falling back to int. 15437 EnumUnderlying = Context.IntTy.getTypePtr(); 15438 15439 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15440 UPPC_FixedUnderlyingType)) 15441 EnumUnderlying = Context.IntTy.getTypePtr(); 15442 15443 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15444 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15445 // of 'int'. However, if this is an unfixed forward declaration, don't set 15446 // the underlying type unless the user enables -fms-compatibility. This 15447 // makes unfixed forward declared enums incomplete and is more conforming. 15448 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15449 EnumUnderlying = Context.IntTy.getTypePtr(); 15450 } 15451 } 15452 15453 DeclContext *SearchDC = CurContext; 15454 DeclContext *DC = CurContext; 15455 bool isStdBadAlloc = false; 15456 bool isStdAlignValT = false; 15457 15458 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15459 if (TUK == TUK_Friend || TUK == TUK_Reference) 15460 Redecl = NotForRedeclaration; 15461 15462 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15463 /// implemented asks for structural equivalence checking, the returned decl 15464 /// here is passed back to the parser, allowing the tag body to be parsed. 15465 auto createTagFromNewDecl = [&]() -> TagDecl * { 15466 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15467 // If there is an identifier, use the location of the identifier as the 15468 // location of the decl, otherwise use the location of the struct/union 15469 // keyword. 15470 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15471 TagDecl *New = nullptr; 15472 15473 if (Kind == TTK_Enum) { 15474 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15475 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15476 // If this is an undefined enum, bail. 15477 if (TUK != TUK_Definition && !Invalid) 15478 return nullptr; 15479 if (EnumUnderlying) { 15480 EnumDecl *ED = cast<EnumDecl>(New); 15481 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15482 ED->setIntegerTypeSourceInfo(TI); 15483 else 15484 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15485 ED->setPromotionType(ED->getIntegerType()); 15486 } 15487 } else { // struct/union 15488 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15489 nullptr); 15490 } 15491 15492 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15493 // Add alignment attributes if necessary; these attributes are checked 15494 // when the ASTContext lays out the structure. 15495 // 15496 // It is important for implementing the correct semantics that this 15497 // happen here (in ActOnTag). The #pragma pack stack is 15498 // maintained as a result of parser callbacks which can occur at 15499 // many points during the parsing of a struct declaration (because 15500 // the #pragma tokens are effectively skipped over during the 15501 // parsing of the struct). 15502 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15503 AddAlignmentAttributesForRecord(RD); 15504 AddMsStructLayoutForRecord(RD); 15505 } 15506 } 15507 New->setLexicalDeclContext(CurContext); 15508 return New; 15509 }; 15510 15511 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15512 if (Name && SS.isNotEmpty()) { 15513 // We have a nested-name tag ('struct foo::bar'). 15514 15515 // Check for invalid 'foo::'. 15516 if (SS.isInvalid()) { 15517 Name = nullptr; 15518 goto CreateNewDecl; 15519 } 15520 15521 // If this is a friend or a reference to a class in a dependent 15522 // context, don't try to make a decl for it. 15523 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15524 DC = computeDeclContext(SS, false); 15525 if (!DC) { 15526 IsDependent = true; 15527 return nullptr; 15528 } 15529 } else { 15530 DC = computeDeclContext(SS, true); 15531 if (!DC) { 15532 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15533 << SS.getRange(); 15534 return nullptr; 15535 } 15536 } 15537 15538 if (RequireCompleteDeclContext(SS, DC)) 15539 return nullptr; 15540 15541 SearchDC = DC; 15542 // Look-up name inside 'foo::'. 15543 LookupQualifiedName(Previous, DC); 15544 15545 if (Previous.isAmbiguous()) 15546 return nullptr; 15547 15548 if (Previous.empty()) { 15549 // Name lookup did not find anything. However, if the 15550 // nested-name-specifier refers to the current instantiation, 15551 // and that current instantiation has any dependent base 15552 // classes, we might find something at instantiation time: treat 15553 // this as a dependent elaborated-type-specifier. 15554 // But this only makes any sense for reference-like lookups. 15555 if (Previous.wasNotFoundInCurrentInstantiation() && 15556 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15557 IsDependent = true; 15558 return nullptr; 15559 } 15560 15561 // A tag 'foo::bar' must already exist. 15562 Diag(NameLoc, diag::err_not_tag_in_scope) 15563 << Kind << Name << DC << SS.getRange(); 15564 Name = nullptr; 15565 Invalid = true; 15566 goto CreateNewDecl; 15567 } 15568 } else if (Name) { 15569 // C++14 [class.mem]p14: 15570 // If T is the name of a class, then each of the following shall have a 15571 // name different from T: 15572 // -- every member of class T that is itself a type 15573 if (TUK != TUK_Reference && TUK != TUK_Friend && 15574 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15575 return nullptr; 15576 15577 // If this is a named struct, check to see if there was a previous forward 15578 // declaration or definition. 15579 // FIXME: We're looking into outer scopes here, even when we 15580 // shouldn't be. Doing so can result in ambiguities that we 15581 // shouldn't be diagnosing. 15582 LookupName(Previous, S); 15583 15584 // When declaring or defining a tag, ignore ambiguities introduced 15585 // by types using'ed into this scope. 15586 if (Previous.isAmbiguous() && 15587 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15588 LookupResult::Filter F = Previous.makeFilter(); 15589 while (F.hasNext()) { 15590 NamedDecl *ND = F.next(); 15591 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15592 SearchDC->getRedeclContext())) 15593 F.erase(); 15594 } 15595 F.done(); 15596 } 15597 15598 // C++11 [namespace.memdef]p3: 15599 // If the name in a friend declaration is neither qualified nor 15600 // a template-id and the declaration is a function or an 15601 // elaborated-type-specifier, the lookup to determine whether 15602 // the entity has been previously declared shall not consider 15603 // any scopes outside the innermost enclosing namespace. 15604 // 15605 // MSVC doesn't implement the above rule for types, so a friend tag 15606 // declaration may be a redeclaration of a type declared in an enclosing 15607 // scope. They do implement this rule for friend functions. 15608 // 15609 // Does it matter that this should be by scope instead of by 15610 // semantic context? 15611 if (!Previous.empty() && TUK == TUK_Friend) { 15612 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15613 LookupResult::Filter F = Previous.makeFilter(); 15614 bool FriendSawTagOutsideEnclosingNamespace = false; 15615 while (F.hasNext()) { 15616 NamedDecl *ND = F.next(); 15617 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15618 if (DC->isFileContext() && 15619 !EnclosingNS->Encloses(ND->getDeclContext())) { 15620 if (getLangOpts().MSVCCompat) 15621 FriendSawTagOutsideEnclosingNamespace = true; 15622 else 15623 F.erase(); 15624 } 15625 } 15626 F.done(); 15627 15628 // Diagnose this MSVC extension in the easy case where lookup would have 15629 // unambiguously found something outside the enclosing namespace. 15630 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15631 NamedDecl *ND = Previous.getFoundDecl(); 15632 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15633 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15634 } 15635 } 15636 15637 // Note: there used to be some attempt at recovery here. 15638 if (Previous.isAmbiguous()) 15639 return nullptr; 15640 15641 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15642 // FIXME: This makes sure that we ignore the contexts associated 15643 // with C structs, unions, and enums when looking for a matching 15644 // tag declaration or definition. See the similar lookup tweak 15645 // in Sema::LookupName; is there a better way to deal with this? 15646 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15647 SearchDC = SearchDC->getParent(); 15648 } 15649 } 15650 15651 if (Previous.isSingleResult() && 15652 Previous.getFoundDecl()->isTemplateParameter()) { 15653 // Maybe we will complain about the shadowed template parameter. 15654 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15655 // Just pretend that we didn't see the previous declaration. 15656 Previous.clear(); 15657 } 15658 15659 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15660 DC->Equals(getStdNamespace())) { 15661 if (Name->isStr("bad_alloc")) { 15662 // This is a declaration of or a reference to "std::bad_alloc". 15663 isStdBadAlloc = true; 15664 15665 // If std::bad_alloc has been implicitly declared (but made invisible to 15666 // name lookup), fill in this implicit declaration as the previous 15667 // declaration, so that the declarations get chained appropriately. 15668 if (Previous.empty() && StdBadAlloc) 15669 Previous.addDecl(getStdBadAlloc()); 15670 } else if (Name->isStr("align_val_t")) { 15671 isStdAlignValT = true; 15672 if (Previous.empty() && StdAlignValT) 15673 Previous.addDecl(getStdAlignValT()); 15674 } 15675 } 15676 15677 // If we didn't find a previous declaration, and this is a reference 15678 // (or friend reference), move to the correct scope. In C++, we 15679 // also need to do a redeclaration lookup there, just in case 15680 // there's a shadow friend decl. 15681 if (Name && Previous.empty() && 15682 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15683 if (Invalid) goto CreateNewDecl; 15684 assert(SS.isEmpty()); 15685 15686 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15687 // C++ [basic.scope.pdecl]p5: 15688 // -- for an elaborated-type-specifier of the form 15689 // 15690 // class-key identifier 15691 // 15692 // if the elaborated-type-specifier is used in the 15693 // decl-specifier-seq or parameter-declaration-clause of a 15694 // function defined in namespace scope, the identifier is 15695 // declared as a class-name in the namespace that contains 15696 // the declaration; otherwise, except as a friend 15697 // declaration, the identifier is declared in the smallest 15698 // non-class, non-function-prototype scope that contains the 15699 // declaration. 15700 // 15701 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15702 // C structs and unions. 15703 // 15704 // It is an error in C++ to declare (rather than define) an enum 15705 // type, including via an elaborated type specifier. We'll 15706 // diagnose that later; for now, declare the enum in the same 15707 // scope as we would have picked for any other tag type. 15708 // 15709 // GNU C also supports this behavior as part of its incomplete 15710 // enum types extension, while GNU C++ does not. 15711 // 15712 // Find the context where we'll be declaring the tag. 15713 // FIXME: We would like to maintain the current DeclContext as the 15714 // lexical context, 15715 SearchDC = getTagInjectionContext(SearchDC); 15716 15717 // Find the scope where we'll be declaring the tag. 15718 S = getTagInjectionScope(S, getLangOpts()); 15719 } else { 15720 assert(TUK == TUK_Friend); 15721 // C++ [namespace.memdef]p3: 15722 // If a friend declaration in a non-local class first declares a 15723 // class or function, the friend class or function is a member of 15724 // the innermost enclosing namespace. 15725 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15726 } 15727 15728 // In C++, we need to do a redeclaration lookup to properly 15729 // diagnose some problems. 15730 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15731 // hidden declaration so that we don't get ambiguity errors when using a 15732 // type declared by an elaborated-type-specifier. In C that is not correct 15733 // and we should instead merge compatible types found by lookup. 15734 if (getLangOpts().CPlusPlus) { 15735 // FIXME: This can perform qualified lookups into function contexts, 15736 // which are meaningless. 15737 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15738 LookupQualifiedName(Previous, SearchDC); 15739 } else { 15740 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15741 LookupName(Previous, S); 15742 } 15743 } 15744 15745 // If we have a known previous declaration to use, then use it. 15746 if (Previous.empty() && SkipBody && SkipBody->Previous) 15747 Previous.addDecl(SkipBody->Previous); 15748 15749 if (!Previous.empty()) { 15750 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15751 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15752 15753 // It's okay to have a tag decl in the same scope as a typedef 15754 // which hides a tag decl in the same scope. Finding this 15755 // insanity with a redeclaration lookup can only actually happen 15756 // in C++. 15757 // 15758 // This is also okay for elaborated-type-specifiers, which is 15759 // technically forbidden by the current standard but which is 15760 // okay according to the likely resolution of an open issue; 15761 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15762 if (getLangOpts().CPlusPlus) { 15763 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15764 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15765 TagDecl *Tag = TT->getDecl(); 15766 if (Tag->getDeclName() == Name && 15767 Tag->getDeclContext()->getRedeclContext() 15768 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15769 PrevDecl = Tag; 15770 Previous.clear(); 15771 Previous.addDecl(Tag); 15772 Previous.resolveKind(); 15773 } 15774 } 15775 } 15776 } 15777 15778 // If this is a redeclaration of a using shadow declaration, it must 15779 // declare a tag in the same context. In MSVC mode, we allow a 15780 // redefinition if either context is within the other. 15781 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15782 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15783 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15784 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15785 !(OldTag && isAcceptableTagRedeclContext( 15786 *this, OldTag->getDeclContext(), SearchDC))) { 15787 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15788 Diag(Shadow->getTargetDecl()->getLocation(), 15789 diag::note_using_decl_target); 15790 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15791 << 0; 15792 // Recover by ignoring the old declaration. 15793 Previous.clear(); 15794 goto CreateNewDecl; 15795 } 15796 } 15797 15798 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15799 // If this is a use of a previous tag, or if the tag is already declared 15800 // in the same scope (so that the definition/declaration completes or 15801 // rementions the tag), reuse the decl. 15802 if (TUK == TUK_Reference || TUK == TUK_Friend || 15803 isDeclInScope(DirectPrevDecl, SearchDC, S, 15804 SS.isNotEmpty() || isMemberSpecialization)) { 15805 // Make sure that this wasn't declared as an enum and now used as a 15806 // struct or something similar. 15807 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15808 TUK == TUK_Definition, KWLoc, 15809 Name)) { 15810 bool SafeToContinue 15811 = (PrevTagDecl->getTagKind() != TTK_Enum && 15812 Kind != TTK_Enum); 15813 if (SafeToContinue) 15814 Diag(KWLoc, diag::err_use_with_wrong_tag) 15815 << Name 15816 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15817 PrevTagDecl->getKindName()); 15818 else 15819 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15820 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15821 15822 if (SafeToContinue) 15823 Kind = PrevTagDecl->getTagKind(); 15824 else { 15825 // Recover by making this an anonymous redefinition. 15826 Name = nullptr; 15827 Previous.clear(); 15828 Invalid = true; 15829 } 15830 } 15831 15832 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15833 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15834 if (TUK == TUK_Reference || TUK == TUK_Friend) 15835 return PrevTagDecl; 15836 15837 QualType EnumUnderlyingTy; 15838 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15839 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15840 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15841 EnumUnderlyingTy = QualType(T, 0); 15842 15843 // All conflicts with previous declarations are recovered by 15844 // returning the previous declaration, unless this is a definition, 15845 // in which case we want the caller to bail out. 15846 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15847 ScopedEnum, EnumUnderlyingTy, 15848 IsFixed, PrevEnum)) 15849 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15850 } 15851 15852 // C++11 [class.mem]p1: 15853 // A member shall not be declared twice in the member-specification, 15854 // except that a nested class or member class template can be declared 15855 // and then later defined. 15856 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15857 S->isDeclScope(PrevDecl)) { 15858 Diag(NameLoc, diag::ext_member_redeclared); 15859 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15860 } 15861 15862 if (!Invalid) { 15863 // If this is a use, just return the declaration we found, unless 15864 // we have attributes. 15865 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15866 if (!Attrs.empty()) { 15867 // FIXME: Diagnose these attributes. For now, we create a new 15868 // declaration to hold them. 15869 } else if (TUK == TUK_Reference && 15870 (PrevTagDecl->getFriendObjectKind() == 15871 Decl::FOK_Undeclared || 15872 PrevDecl->getOwningModule() != getCurrentModule()) && 15873 SS.isEmpty()) { 15874 // This declaration is a reference to an existing entity, but 15875 // has different visibility from that entity: it either makes 15876 // a friend visible or it makes a type visible in a new module. 15877 // In either case, create a new declaration. We only do this if 15878 // the declaration would have meant the same thing if no prior 15879 // declaration were found, that is, if it was found in the same 15880 // scope where we would have injected a declaration. 15881 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15882 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15883 return PrevTagDecl; 15884 // This is in the injected scope, create a new declaration in 15885 // that scope. 15886 S = getTagInjectionScope(S, getLangOpts()); 15887 } else { 15888 return PrevTagDecl; 15889 } 15890 } 15891 15892 // Diagnose attempts to redefine a tag. 15893 if (TUK == TUK_Definition) { 15894 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15895 // If we're defining a specialization and the previous definition 15896 // is from an implicit instantiation, don't emit an error 15897 // here; we'll catch this in the general case below. 15898 bool IsExplicitSpecializationAfterInstantiation = false; 15899 if (isMemberSpecialization) { 15900 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15901 IsExplicitSpecializationAfterInstantiation = 15902 RD->getTemplateSpecializationKind() != 15903 TSK_ExplicitSpecialization; 15904 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15905 IsExplicitSpecializationAfterInstantiation = 15906 ED->getTemplateSpecializationKind() != 15907 TSK_ExplicitSpecialization; 15908 } 15909 15910 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15911 // not keep more that one definition around (merge them). However, 15912 // ensure the decl passes the structural compatibility check in 15913 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15914 NamedDecl *Hidden = nullptr; 15915 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15916 // There is a definition of this tag, but it is not visible. We 15917 // explicitly make use of C++'s one definition rule here, and 15918 // assume that this definition is identical to the hidden one 15919 // we already have. Make the existing definition visible and 15920 // use it in place of this one. 15921 if (!getLangOpts().CPlusPlus) { 15922 // Postpone making the old definition visible until after we 15923 // complete parsing the new one and do the structural 15924 // comparison. 15925 SkipBody->CheckSameAsPrevious = true; 15926 SkipBody->New = createTagFromNewDecl(); 15927 SkipBody->Previous = Def; 15928 return Def; 15929 } else { 15930 SkipBody->ShouldSkip = true; 15931 SkipBody->Previous = Def; 15932 makeMergedDefinitionVisible(Hidden); 15933 // Carry on and handle it like a normal definition. We'll 15934 // skip starting the definitiion later. 15935 } 15936 } else if (!IsExplicitSpecializationAfterInstantiation) { 15937 // A redeclaration in function prototype scope in C isn't 15938 // visible elsewhere, so merely issue a warning. 15939 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15940 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15941 else 15942 Diag(NameLoc, diag::err_redefinition) << Name; 15943 notePreviousDefinition(Def, 15944 NameLoc.isValid() ? NameLoc : KWLoc); 15945 // If this is a redefinition, recover by making this 15946 // struct be anonymous, which will make any later 15947 // references get the previous definition. 15948 Name = nullptr; 15949 Previous.clear(); 15950 Invalid = true; 15951 } 15952 } else { 15953 // If the type is currently being defined, complain 15954 // about a nested redefinition. 15955 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15956 if (TD->isBeingDefined()) { 15957 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15958 Diag(PrevTagDecl->getLocation(), 15959 diag::note_previous_definition); 15960 Name = nullptr; 15961 Previous.clear(); 15962 Invalid = true; 15963 } 15964 } 15965 15966 // Okay, this is definition of a previously declared or referenced 15967 // tag. We're going to create a new Decl for it. 15968 } 15969 15970 // Okay, we're going to make a redeclaration. If this is some kind 15971 // of reference, make sure we build the redeclaration in the same DC 15972 // as the original, and ignore the current access specifier. 15973 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15974 SearchDC = PrevTagDecl->getDeclContext(); 15975 AS = AS_none; 15976 } 15977 } 15978 // If we get here we have (another) forward declaration or we 15979 // have a definition. Just create a new decl. 15980 15981 } else { 15982 // If we get here, this is a definition of a new tag type in a nested 15983 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15984 // new decl/type. We set PrevDecl to NULL so that the entities 15985 // have distinct types. 15986 Previous.clear(); 15987 } 15988 // If we get here, we're going to create a new Decl. If PrevDecl 15989 // is non-NULL, it's a definition of the tag declared by 15990 // PrevDecl. If it's NULL, we have a new definition. 15991 15992 // Otherwise, PrevDecl is not a tag, but was found with tag 15993 // lookup. This is only actually possible in C++, where a few 15994 // things like templates still live in the tag namespace. 15995 } else { 15996 // Use a better diagnostic if an elaborated-type-specifier 15997 // found the wrong kind of type on the first 15998 // (non-redeclaration) lookup. 15999 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16000 !Previous.isForRedeclaration()) { 16001 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16002 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16003 << Kind; 16004 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16005 Invalid = true; 16006 16007 // Otherwise, only diagnose if the declaration is in scope. 16008 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16009 SS.isNotEmpty() || isMemberSpecialization)) { 16010 // do nothing 16011 16012 // Diagnose implicit declarations introduced by elaborated types. 16013 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16014 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16015 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16016 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16017 Invalid = true; 16018 16019 // Otherwise it's a declaration. Call out a particularly common 16020 // case here. 16021 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16022 unsigned Kind = 0; 16023 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16024 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16025 << Name << Kind << TND->getUnderlyingType(); 16026 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16027 Invalid = true; 16028 16029 // Otherwise, diagnose. 16030 } else { 16031 // The tag name clashes with something else in the target scope, 16032 // issue an error and recover by making this tag be anonymous. 16033 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16034 notePreviousDefinition(PrevDecl, NameLoc); 16035 Name = nullptr; 16036 Invalid = true; 16037 } 16038 16039 // The existing declaration isn't relevant to us; we're in a 16040 // new scope, so clear out the previous declaration. 16041 Previous.clear(); 16042 } 16043 } 16044 16045 CreateNewDecl: 16046 16047 TagDecl *PrevDecl = nullptr; 16048 if (Previous.isSingleResult()) 16049 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16050 16051 // If there is an identifier, use the location of the identifier as the 16052 // location of the decl, otherwise use the location of the struct/union 16053 // keyword. 16054 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16055 16056 // Otherwise, create a new declaration. If there is a previous 16057 // declaration of the same entity, the two will be linked via 16058 // PrevDecl. 16059 TagDecl *New; 16060 16061 if (Kind == TTK_Enum) { 16062 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16063 // enum X { A, B, C } D; D should chain to X. 16064 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16065 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16066 ScopedEnumUsesClassTag, IsFixed); 16067 16068 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16069 StdAlignValT = cast<EnumDecl>(New); 16070 16071 // If this is an undefined enum, warn. 16072 if (TUK != TUK_Definition && !Invalid) { 16073 TagDecl *Def; 16074 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16075 // C++0x: 7.2p2: opaque-enum-declaration. 16076 // Conflicts are diagnosed above. Do nothing. 16077 } 16078 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16079 Diag(Loc, diag::ext_forward_ref_enum_def) 16080 << New; 16081 Diag(Def->getLocation(), diag::note_previous_definition); 16082 } else { 16083 unsigned DiagID = diag::ext_forward_ref_enum; 16084 if (getLangOpts().MSVCCompat) 16085 DiagID = diag::ext_ms_forward_ref_enum; 16086 else if (getLangOpts().CPlusPlus) 16087 DiagID = diag::err_forward_ref_enum; 16088 Diag(Loc, DiagID); 16089 } 16090 } 16091 16092 if (EnumUnderlying) { 16093 EnumDecl *ED = cast<EnumDecl>(New); 16094 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16095 ED->setIntegerTypeSourceInfo(TI); 16096 else 16097 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16098 ED->setPromotionType(ED->getIntegerType()); 16099 assert(ED->isComplete() && "enum with type should be complete"); 16100 } 16101 } else { 16102 // struct/union/class 16103 16104 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16105 // struct X { int A; } D; D should chain to X. 16106 if (getLangOpts().CPlusPlus) { 16107 // FIXME: Look for a way to use RecordDecl for simple structs. 16108 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16109 cast_or_null<CXXRecordDecl>(PrevDecl)); 16110 16111 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16112 StdBadAlloc = cast<CXXRecordDecl>(New); 16113 } else 16114 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16115 cast_or_null<RecordDecl>(PrevDecl)); 16116 } 16117 16118 // C++11 [dcl.type]p3: 16119 // A type-specifier-seq shall not define a class or enumeration [...]. 16120 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16121 TUK == TUK_Definition) { 16122 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16123 << Context.getTagDeclType(New); 16124 Invalid = true; 16125 } 16126 16127 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16128 DC->getDeclKind() == Decl::Enum) { 16129 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16130 << Context.getTagDeclType(New); 16131 Invalid = true; 16132 } 16133 16134 // Maybe add qualifier info. 16135 if (SS.isNotEmpty()) { 16136 if (SS.isSet()) { 16137 // If this is either a declaration or a definition, check the 16138 // nested-name-specifier against the current context. 16139 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16140 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16141 isMemberSpecialization)) 16142 Invalid = true; 16143 16144 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16145 if (TemplateParameterLists.size() > 0) { 16146 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16147 } 16148 } 16149 else 16150 Invalid = true; 16151 } 16152 16153 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16154 // Add alignment attributes if necessary; these attributes are checked when 16155 // the ASTContext lays out the structure. 16156 // 16157 // It is important for implementing the correct semantics that this 16158 // happen here (in ActOnTag). The #pragma pack stack is 16159 // maintained as a result of parser callbacks which can occur at 16160 // many points during the parsing of a struct declaration (because 16161 // the #pragma tokens are effectively skipped over during the 16162 // parsing of the struct). 16163 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16164 AddAlignmentAttributesForRecord(RD); 16165 AddMsStructLayoutForRecord(RD); 16166 } 16167 } 16168 16169 if (ModulePrivateLoc.isValid()) { 16170 if (isMemberSpecialization) 16171 Diag(New->getLocation(), diag::err_module_private_specialization) 16172 << 2 16173 << FixItHint::CreateRemoval(ModulePrivateLoc); 16174 // __module_private__ does not apply to local classes. However, we only 16175 // diagnose this as an error when the declaration specifiers are 16176 // freestanding. Here, we just ignore the __module_private__. 16177 else if (!SearchDC->isFunctionOrMethod()) 16178 New->setModulePrivate(); 16179 } 16180 16181 // If this is a specialization of a member class (of a class template), 16182 // check the specialization. 16183 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16184 Invalid = true; 16185 16186 // If we're declaring or defining a tag in function prototype scope in C, 16187 // note that this type can only be used within the function and add it to 16188 // the list of decls to inject into the function definition scope. 16189 if ((Name || Kind == TTK_Enum) && 16190 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16191 if (getLangOpts().CPlusPlus) { 16192 // C++ [dcl.fct]p6: 16193 // Types shall not be defined in return or parameter types. 16194 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16195 Diag(Loc, diag::err_type_defined_in_param_type) 16196 << Name; 16197 Invalid = true; 16198 } 16199 } else if (!PrevDecl) { 16200 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16201 } 16202 } 16203 16204 if (Invalid) 16205 New->setInvalidDecl(); 16206 16207 // Set the lexical context. If the tag has a C++ scope specifier, the 16208 // lexical context will be different from the semantic context. 16209 New->setLexicalDeclContext(CurContext); 16210 16211 // Mark this as a friend decl if applicable. 16212 // In Microsoft mode, a friend declaration also acts as a forward 16213 // declaration so we always pass true to setObjectOfFriendDecl to make 16214 // the tag name visible. 16215 if (TUK == TUK_Friend) 16216 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16217 16218 // Set the access specifier. 16219 if (!Invalid && SearchDC->isRecord()) 16220 SetMemberAccessSpecifier(New, PrevDecl, AS); 16221 16222 if (PrevDecl) 16223 CheckRedeclarationModuleOwnership(New, PrevDecl); 16224 16225 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16226 New->startDefinition(); 16227 16228 ProcessDeclAttributeList(S, New, Attrs); 16229 AddPragmaAttributes(S, New); 16230 16231 // If this has an identifier, add it to the scope stack. 16232 if (TUK == TUK_Friend) { 16233 // We might be replacing an existing declaration in the lookup tables; 16234 // if so, borrow its access specifier. 16235 if (PrevDecl) 16236 New->setAccess(PrevDecl->getAccess()); 16237 16238 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16239 DC->makeDeclVisibleInContext(New); 16240 if (Name) // can be null along some error paths 16241 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16242 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16243 } else if (Name) { 16244 S = getNonFieldDeclScope(S); 16245 PushOnScopeChains(New, S, true); 16246 } else { 16247 CurContext->addDecl(New); 16248 } 16249 16250 // If this is the C FILE type, notify the AST context. 16251 if (IdentifierInfo *II = New->getIdentifier()) 16252 if (!New->isInvalidDecl() && 16253 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16254 II->isStr("FILE")) 16255 Context.setFILEDecl(New); 16256 16257 if (PrevDecl) 16258 mergeDeclAttributes(New, PrevDecl); 16259 16260 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16261 inferGslOwnerPointerAttribute(CXXRD); 16262 16263 // If there's a #pragma GCC visibility in scope, set the visibility of this 16264 // record. 16265 AddPushedVisibilityAttribute(New); 16266 16267 if (isMemberSpecialization && !New->isInvalidDecl()) 16268 CompleteMemberSpecialization(New, Previous); 16269 16270 OwnedDecl = true; 16271 // In C++, don't return an invalid declaration. We can't recover well from 16272 // the cases where we make the type anonymous. 16273 if (Invalid && getLangOpts().CPlusPlus) { 16274 if (New->isBeingDefined()) 16275 if (auto RD = dyn_cast<RecordDecl>(New)) 16276 RD->completeDefinition(); 16277 return nullptr; 16278 } else if (SkipBody && SkipBody->ShouldSkip) { 16279 return SkipBody->Previous; 16280 } else { 16281 return New; 16282 } 16283 } 16284 16285 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16286 AdjustDeclIfTemplate(TagD); 16287 TagDecl *Tag = cast<TagDecl>(TagD); 16288 16289 // Enter the tag context. 16290 PushDeclContext(S, Tag); 16291 16292 ActOnDocumentableDecl(TagD); 16293 16294 // If there's a #pragma GCC visibility in scope, set the visibility of this 16295 // record. 16296 AddPushedVisibilityAttribute(Tag); 16297 } 16298 16299 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16300 SkipBodyInfo &SkipBody) { 16301 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16302 return false; 16303 16304 // Make the previous decl visible. 16305 makeMergedDefinitionVisible(SkipBody.Previous); 16306 return true; 16307 } 16308 16309 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16310 assert(isa<ObjCContainerDecl>(IDecl) && 16311 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16312 DeclContext *OCD = cast<DeclContext>(IDecl); 16313 assert(OCD->getLexicalParent() == CurContext && 16314 "The next DeclContext should be lexically contained in the current one."); 16315 CurContext = OCD; 16316 return IDecl; 16317 } 16318 16319 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16320 SourceLocation FinalLoc, 16321 bool IsFinalSpelledSealed, 16322 SourceLocation LBraceLoc) { 16323 AdjustDeclIfTemplate(TagD); 16324 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16325 16326 FieldCollector->StartClass(); 16327 16328 if (!Record->getIdentifier()) 16329 return; 16330 16331 if (FinalLoc.isValid()) 16332 Record->addAttr(FinalAttr::Create( 16333 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16334 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16335 16336 // C++ [class]p2: 16337 // [...] The class-name is also inserted into the scope of the 16338 // class itself; this is known as the injected-class-name. For 16339 // purposes of access checking, the injected-class-name is treated 16340 // as if it were a public member name. 16341 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16342 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16343 Record->getLocation(), Record->getIdentifier(), 16344 /*PrevDecl=*/nullptr, 16345 /*DelayTypeCreation=*/true); 16346 Context.getTypeDeclType(InjectedClassName, Record); 16347 InjectedClassName->setImplicit(); 16348 InjectedClassName->setAccess(AS_public); 16349 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16350 InjectedClassName->setDescribedClassTemplate(Template); 16351 PushOnScopeChains(InjectedClassName, S); 16352 assert(InjectedClassName->isInjectedClassName() && 16353 "Broken injected-class-name"); 16354 } 16355 16356 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16357 SourceRange BraceRange) { 16358 AdjustDeclIfTemplate(TagD); 16359 TagDecl *Tag = cast<TagDecl>(TagD); 16360 Tag->setBraceRange(BraceRange); 16361 16362 // Make sure we "complete" the definition even it is invalid. 16363 if (Tag->isBeingDefined()) { 16364 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16365 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16366 RD->completeDefinition(); 16367 } 16368 16369 if (isa<CXXRecordDecl>(Tag)) { 16370 FieldCollector->FinishClass(); 16371 } 16372 16373 // Exit this scope of this tag's definition. 16374 PopDeclContext(); 16375 16376 if (getCurLexicalContext()->isObjCContainer() && 16377 Tag->getDeclContext()->isFileContext()) 16378 Tag->setTopLevelDeclInObjCContainer(); 16379 16380 // Notify the consumer that we've defined a tag. 16381 if (!Tag->isInvalidDecl()) 16382 Consumer.HandleTagDeclDefinition(Tag); 16383 } 16384 16385 void Sema::ActOnObjCContainerFinishDefinition() { 16386 // Exit this scope of this interface definition. 16387 PopDeclContext(); 16388 } 16389 16390 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16391 assert(DC == CurContext && "Mismatch of container contexts"); 16392 OriginalLexicalContext = DC; 16393 ActOnObjCContainerFinishDefinition(); 16394 } 16395 16396 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16397 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16398 OriginalLexicalContext = nullptr; 16399 } 16400 16401 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16402 AdjustDeclIfTemplate(TagD); 16403 TagDecl *Tag = cast<TagDecl>(TagD); 16404 Tag->setInvalidDecl(); 16405 16406 // Make sure we "complete" the definition even it is invalid. 16407 if (Tag->isBeingDefined()) { 16408 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16409 RD->completeDefinition(); 16410 } 16411 16412 // We're undoing ActOnTagStartDefinition here, not 16413 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16414 // the FieldCollector. 16415 16416 PopDeclContext(); 16417 } 16418 16419 // Note that FieldName may be null for anonymous bitfields. 16420 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16421 IdentifierInfo *FieldName, 16422 QualType FieldTy, bool IsMsStruct, 16423 Expr *BitWidth, bool *ZeroWidth) { 16424 assert(BitWidth); 16425 if (BitWidth->containsErrors()) 16426 return ExprError(); 16427 16428 // Default to true; that shouldn't confuse checks for emptiness 16429 if (ZeroWidth) 16430 *ZeroWidth = true; 16431 16432 // C99 6.7.2.1p4 - verify the field type. 16433 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16434 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16435 // Handle incomplete and sizeless types with a specific error. 16436 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16437 diag::err_field_incomplete_or_sizeless)) 16438 return ExprError(); 16439 if (FieldName) 16440 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16441 << FieldName << FieldTy << BitWidth->getSourceRange(); 16442 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16443 << FieldTy << BitWidth->getSourceRange(); 16444 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16445 UPPC_BitFieldWidth)) 16446 return ExprError(); 16447 16448 // If the bit-width is type- or value-dependent, don't try to check 16449 // it now. 16450 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16451 return BitWidth; 16452 16453 llvm::APSInt Value; 16454 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16455 if (ICE.isInvalid()) 16456 return ICE; 16457 BitWidth = ICE.get(); 16458 16459 if (Value != 0 && ZeroWidth) 16460 *ZeroWidth = false; 16461 16462 // Zero-width bitfield is ok for anonymous field. 16463 if (Value == 0 && FieldName) 16464 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16465 16466 if (Value.isSigned() && Value.isNegative()) { 16467 if (FieldName) 16468 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16469 << FieldName << Value.toString(10); 16470 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16471 << Value.toString(10); 16472 } 16473 16474 // The size of the bit-field must not exceed our maximum permitted object 16475 // size. 16476 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16477 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16478 << !FieldName << FieldName << Value.toString(10); 16479 } 16480 16481 if (!FieldTy->isDependentType()) { 16482 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16483 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16484 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16485 16486 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16487 // ABI. 16488 bool CStdConstraintViolation = 16489 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16490 bool MSBitfieldViolation = 16491 Value.ugt(TypeStorageSize) && 16492 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16493 if (CStdConstraintViolation || MSBitfieldViolation) { 16494 unsigned DiagWidth = 16495 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16496 if (FieldName) 16497 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16498 << FieldName << Value.toString(10) 16499 << !CStdConstraintViolation << DiagWidth; 16500 16501 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16502 << Value.toString(10) << !CStdConstraintViolation 16503 << DiagWidth; 16504 } 16505 16506 // Warn on types where the user might conceivably expect to get all 16507 // specified bits as value bits: that's all integral types other than 16508 // 'bool'. 16509 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16510 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16511 << FieldName << Value.toString(10) 16512 << (unsigned)TypeWidth; 16513 } 16514 } 16515 16516 return BitWidth; 16517 } 16518 16519 /// ActOnField - Each field of a C struct/union is passed into this in order 16520 /// to create a FieldDecl object for it. 16521 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16522 Declarator &D, Expr *BitfieldWidth) { 16523 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16524 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16525 /*InitStyle=*/ICIS_NoInit, AS_public); 16526 return Res; 16527 } 16528 16529 /// HandleField - Analyze a field of a C struct or a C++ data member. 16530 /// 16531 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16532 SourceLocation DeclStart, 16533 Declarator &D, Expr *BitWidth, 16534 InClassInitStyle InitStyle, 16535 AccessSpecifier AS) { 16536 if (D.isDecompositionDeclarator()) { 16537 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16538 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16539 << Decomp.getSourceRange(); 16540 return nullptr; 16541 } 16542 16543 IdentifierInfo *II = D.getIdentifier(); 16544 SourceLocation Loc = DeclStart; 16545 if (II) Loc = D.getIdentifierLoc(); 16546 16547 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16548 QualType T = TInfo->getType(); 16549 if (getLangOpts().CPlusPlus) { 16550 CheckExtraCXXDefaultArguments(D); 16551 16552 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16553 UPPC_DataMemberType)) { 16554 D.setInvalidType(); 16555 T = Context.IntTy; 16556 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16557 } 16558 } 16559 16560 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16561 16562 if (D.getDeclSpec().isInlineSpecified()) 16563 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16564 << getLangOpts().CPlusPlus17; 16565 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16566 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16567 diag::err_invalid_thread) 16568 << DeclSpec::getSpecifierName(TSCS); 16569 16570 // Check to see if this name was declared as a member previously 16571 NamedDecl *PrevDecl = nullptr; 16572 LookupResult Previous(*this, II, Loc, LookupMemberName, 16573 ForVisibleRedeclaration); 16574 LookupName(Previous, S); 16575 switch (Previous.getResultKind()) { 16576 case LookupResult::Found: 16577 case LookupResult::FoundUnresolvedValue: 16578 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16579 break; 16580 16581 case LookupResult::FoundOverloaded: 16582 PrevDecl = Previous.getRepresentativeDecl(); 16583 break; 16584 16585 case LookupResult::NotFound: 16586 case LookupResult::NotFoundInCurrentInstantiation: 16587 case LookupResult::Ambiguous: 16588 break; 16589 } 16590 Previous.suppressDiagnostics(); 16591 16592 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16593 // Maybe we will complain about the shadowed template parameter. 16594 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16595 // Just pretend that we didn't see the previous declaration. 16596 PrevDecl = nullptr; 16597 } 16598 16599 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16600 PrevDecl = nullptr; 16601 16602 bool Mutable 16603 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16604 SourceLocation TSSL = D.getBeginLoc(); 16605 FieldDecl *NewFD 16606 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16607 TSSL, AS, PrevDecl, &D); 16608 16609 if (NewFD->isInvalidDecl()) 16610 Record->setInvalidDecl(); 16611 16612 if (D.getDeclSpec().isModulePrivateSpecified()) 16613 NewFD->setModulePrivate(); 16614 16615 if (NewFD->isInvalidDecl() && PrevDecl) { 16616 // Don't introduce NewFD into scope; there's already something 16617 // with the same name in the same scope. 16618 } else if (II) { 16619 PushOnScopeChains(NewFD, S); 16620 } else 16621 Record->addDecl(NewFD); 16622 16623 return NewFD; 16624 } 16625 16626 /// Build a new FieldDecl and check its well-formedness. 16627 /// 16628 /// This routine builds a new FieldDecl given the fields name, type, 16629 /// record, etc. \p PrevDecl should refer to any previous declaration 16630 /// with the same name and in the same scope as the field to be 16631 /// created. 16632 /// 16633 /// \returns a new FieldDecl. 16634 /// 16635 /// \todo The Declarator argument is a hack. It will be removed once 16636 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16637 TypeSourceInfo *TInfo, 16638 RecordDecl *Record, SourceLocation Loc, 16639 bool Mutable, Expr *BitWidth, 16640 InClassInitStyle InitStyle, 16641 SourceLocation TSSL, 16642 AccessSpecifier AS, NamedDecl *PrevDecl, 16643 Declarator *D) { 16644 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16645 bool InvalidDecl = false; 16646 if (D) InvalidDecl = D->isInvalidType(); 16647 16648 // If we receive a broken type, recover by assuming 'int' and 16649 // marking this declaration as invalid. 16650 if (T.isNull() || T->containsErrors()) { 16651 InvalidDecl = true; 16652 T = Context.IntTy; 16653 } 16654 16655 QualType EltTy = Context.getBaseElementType(T); 16656 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16657 if (RequireCompleteSizedType(Loc, EltTy, 16658 diag::err_field_incomplete_or_sizeless)) { 16659 // Fields of incomplete type force their record to be invalid. 16660 Record->setInvalidDecl(); 16661 InvalidDecl = true; 16662 } else { 16663 NamedDecl *Def; 16664 EltTy->isIncompleteType(&Def); 16665 if (Def && Def->isInvalidDecl()) { 16666 Record->setInvalidDecl(); 16667 InvalidDecl = true; 16668 } 16669 } 16670 } 16671 16672 // TR 18037 does not allow fields to be declared with address space 16673 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16674 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16675 Diag(Loc, diag::err_field_with_address_space); 16676 Record->setInvalidDecl(); 16677 InvalidDecl = true; 16678 } 16679 16680 if (LangOpts.OpenCL) { 16681 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16682 // used as structure or union field: image, sampler, event or block types. 16683 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16684 T->isBlockPointerType()) { 16685 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16686 Record->setInvalidDecl(); 16687 InvalidDecl = true; 16688 } 16689 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16690 if (BitWidth) { 16691 Diag(Loc, diag::err_opencl_bitfields); 16692 InvalidDecl = true; 16693 } 16694 } 16695 16696 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16697 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16698 T.hasQualifiers()) { 16699 InvalidDecl = true; 16700 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16701 } 16702 16703 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16704 // than a variably modified type. 16705 if (!InvalidDecl && T->isVariablyModifiedType()) { 16706 if (!tryToFixVariablyModifiedVarType( 16707 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16708 InvalidDecl = true; 16709 } 16710 16711 // Fields can not have abstract class types 16712 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16713 diag::err_abstract_type_in_decl, 16714 AbstractFieldType)) 16715 InvalidDecl = true; 16716 16717 bool ZeroWidth = false; 16718 if (InvalidDecl) 16719 BitWidth = nullptr; 16720 // If this is declared as a bit-field, check the bit-field. 16721 if (BitWidth) { 16722 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16723 &ZeroWidth).get(); 16724 if (!BitWidth) { 16725 InvalidDecl = true; 16726 BitWidth = nullptr; 16727 ZeroWidth = false; 16728 } 16729 } 16730 16731 // Check that 'mutable' is consistent with the type of the declaration. 16732 if (!InvalidDecl && Mutable) { 16733 unsigned DiagID = 0; 16734 if (T->isReferenceType()) 16735 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16736 : diag::err_mutable_reference; 16737 else if (T.isConstQualified()) 16738 DiagID = diag::err_mutable_const; 16739 16740 if (DiagID) { 16741 SourceLocation ErrLoc = Loc; 16742 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16743 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16744 Diag(ErrLoc, DiagID); 16745 if (DiagID != diag::ext_mutable_reference) { 16746 Mutable = false; 16747 InvalidDecl = true; 16748 } 16749 } 16750 } 16751 16752 // C++11 [class.union]p8 (DR1460): 16753 // At most one variant member of a union may have a 16754 // brace-or-equal-initializer. 16755 if (InitStyle != ICIS_NoInit) 16756 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16757 16758 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16759 BitWidth, Mutable, InitStyle); 16760 if (InvalidDecl) 16761 NewFD->setInvalidDecl(); 16762 16763 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16764 Diag(Loc, diag::err_duplicate_member) << II; 16765 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16766 NewFD->setInvalidDecl(); 16767 } 16768 16769 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16770 if (Record->isUnion()) { 16771 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16772 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16773 if (RDecl->getDefinition()) { 16774 // C++ [class.union]p1: An object of a class with a non-trivial 16775 // constructor, a non-trivial copy constructor, a non-trivial 16776 // destructor, or a non-trivial copy assignment operator 16777 // cannot be a member of a union, nor can an array of such 16778 // objects. 16779 if (CheckNontrivialField(NewFD)) 16780 NewFD->setInvalidDecl(); 16781 } 16782 } 16783 16784 // C++ [class.union]p1: If a union contains a member of reference type, 16785 // the program is ill-formed, except when compiling with MSVC extensions 16786 // enabled. 16787 if (EltTy->isReferenceType()) { 16788 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16789 diag::ext_union_member_of_reference_type : 16790 diag::err_union_member_of_reference_type) 16791 << NewFD->getDeclName() << EltTy; 16792 if (!getLangOpts().MicrosoftExt) 16793 NewFD->setInvalidDecl(); 16794 } 16795 } 16796 } 16797 16798 // FIXME: We need to pass in the attributes given an AST 16799 // representation, not a parser representation. 16800 if (D) { 16801 // FIXME: The current scope is almost... but not entirely... correct here. 16802 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16803 16804 if (NewFD->hasAttrs()) 16805 CheckAlignasUnderalignment(NewFD); 16806 } 16807 16808 // In auto-retain/release, infer strong retension for fields of 16809 // retainable type. 16810 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16811 NewFD->setInvalidDecl(); 16812 16813 if (T.isObjCGCWeak()) 16814 Diag(Loc, diag::warn_attribute_weak_on_field); 16815 16816 // PPC MMA non-pointer types are not allowed as field types. 16817 if (Context.getTargetInfo().getTriple().isPPC64() && 16818 CheckPPCMMAType(T, NewFD->getLocation())) 16819 NewFD->setInvalidDecl(); 16820 16821 NewFD->setAccess(AS); 16822 return NewFD; 16823 } 16824 16825 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16826 assert(FD); 16827 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16828 16829 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16830 return false; 16831 16832 QualType EltTy = Context.getBaseElementType(FD->getType()); 16833 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16834 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16835 if (RDecl->getDefinition()) { 16836 // We check for copy constructors before constructors 16837 // because otherwise we'll never get complaints about 16838 // copy constructors. 16839 16840 CXXSpecialMember member = CXXInvalid; 16841 // We're required to check for any non-trivial constructors. Since the 16842 // implicit default constructor is suppressed if there are any 16843 // user-declared constructors, we just need to check that there is a 16844 // trivial default constructor and a trivial copy constructor. (We don't 16845 // worry about move constructors here, since this is a C++98 check.) 16846 if (RDecl->hasNonTrivialCopyConstructor()) 16847 member = CXXCopyConstructor; 16848 else if (!RDecl->hasTrivialDefaultConstructor()) 16849 member = CXXDefaultConstructor; 16850 else if (RDecl->hasNonTrivialCopyAssignment()) 16851 member = CXXCopyAssignment; 16852 else if (RDecl->hasNonTrivialDestructor()) 16853 member = CXXDestructor; 16854 16855 if (member != CXXInvalid) { 16856 if (!getLangOpts().CPlusPlus11 && 16857 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16858 // Objective-C++ ARC: it is an error to have a non-trivial field of 16859 // a union. However, system headers in Objective-C programs 16860 // occasionally have Objective-C lifetime objects within unions, 16861 // and rather than cause the program to fail, we make those 16862 // members unavailable. 16863 SourceLocation Loc = FD->getLocation(); 16864 if (getSourceManager().isInSystemHeader(Loc)) { 16865 if (!FD->hasAttr<UnavailableAttr>()) 16866 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16867 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16868 return false; 16869 } 16870 } 16871 16872 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16873 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16874 diag::err_illegal_union_or_anon_struct_member) 16875 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16876 DiagnoseNontrivial(RDecl, member); 16877 return !getLangOpts().CPlusPlus11; 16878 } 16879 } 16880 } 16881 16882 return false; 16883 } 16884 16885 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16886 /// AST enum value. 16887 static ObjCIvarDecl::AccessControl 16888 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16889 switch (ivarVisibility) { 16890 default: llvm_unreachable("Unknown visitibility kind"); 16891 case tok::objc_private: return ObjCIvarDecl::Private; 16892 case tok::objc_public: return ObjCIvarDecl::Public; 16893 case tok::objc_protected: return ObjCIvarDecl::Protected; 16894 case tok::objc_package: return ObjCIvarDecl::Package; 16895 } 16896 } 16897 16898 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16899 /// in order to create an IvarDecl object for it. 16900 Decl *Sema::ActOnIvar(Scope *S, 16901 SourceLocation DeclStart, 16902 Declarator &D, Expr *BitfieldWidth, 16903 tok::ObjCKeywordKind Visibility) { 16904 16905 IdentifierInfo *II = D.getIdentifier(); 16906 Expr *BitWidth = (Expr*)BitfieldWidth; 16907 SourceLocation Loc = DeclStart; 16908 if (II) Loc = D.getIdentifierLoc(); 16909 16910 // FIXME: Unnamed fields can be handled in various different ways, for 16911 // example, unnamed unions inject all members into the struct namespace! 16912 16913 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16914 QualType T = TInfo->getType(); 16915 16916 if (BitWidth) { 16917 // 6.7.2.1p3, 6.7.2.1p4 16918 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16919 if (!BitWidth) 16920 D.setInvalidType(); 16921 } else { 16922 // Not a bitfield. 16923 16924 // validate II. 16925 16926 } 16927 if (T->isReferenceType()) { 16928 Diag(Loc, diag::err_ivar_reference_type); 16929 D.setInvalidType(); 16930 } 16931 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16932 // than a variably modified type. 16933 else if (T->isVariablyModifiedType()) { 16934 if (!tryToFixVariablyModifiedVarType( 16935 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 16936 D.setInvalidType(); 16937 } 16938 16939 // Get the visibility (access control) for this ivar. 16940 ObjCIvarDecl::AccessControl ac = 16941 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16942 : ObjCIvarDecl::None; 16943 // Must set ivar's DeclContext to its enclosing interface. 16944 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16945 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16946 return nullptr; 16947 ObjCContainerDecl *EnclosingContext; 16948 if (ObjCImplementationDecl *IMPDecl = 16949 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16950 if (LangOpts.ObjCRuntime.isFragile()) { 16951 // Case of ivar declared in an implementation. Context is that of its class. 16952 EnclosingContext = IMPDecl->getClassInterface(); 16953 assert(EnclosingContext && "Implementation has no class interface!"); 16954 } 16955 else 16956 EnclosingContext = EnclosingDecl; 16957 } else { 16958 if (ObjCCategoryDecl *CDecl = 16959 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16960 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16961 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16962 return nullptr; 16963 } 16964 } 16965 EnclosingContext = EnclosingDecl; 16966 } 16967 16968 // Construct the decl. 16969 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16970 DeclStart, Loc, II, T, 16971 TInfo, ac, (Expr *)BitfieldWidth); 16972 16973 if (II) { 16974 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16975 ForVisibleRedeclaration); 16976 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16977 && !isa<TagDecl>(PrevDecl)) { 16978 Diag(Loc, diag::err_duplicate_member) << II; 16979 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16980 NewID->setInvalidDecl(); 16981 } 16982 } 16983 16984 // Process attributes attached to the ivar. 16985 ProcessDeclAttributes(S, NewID, D); 16986 16987 if (D.isInvalidType()) 16988 NewID->setInvalidDecl(); 16989 16990 // In ARC, infer 'retaining' for ivars of retainable type. 16991 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16992 NewID->setInvalidDecl(); 16993 16994 if (D.getDeclSpec().isModulePrivateSpecified()) 16995 NewID->setModulePrivate(); 16996 16997 if (II) { 16998 // FIXME: When interfaces are DeclContexts, we'll need to add 16999 // these to the interface. 17000 S->AddDecl(NewID); 17001 IdResolver.AddDecl(NewID); 17002 } 17003 17004 if (LangOpts.ObjCRuntime.isNonFragile() && 17005 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17006 Diag(Loc, diag::warn_ivars_in_interface); 17007 17008 return NewID; 17009 } 17010 17011 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17012 /// class and class extensions. For every class \@interface and class 17013 /// extension \@interface, if the last ivar is a bitfield of any type, 17014 /// then add an implicit `char :0` ivar to the end of that interface. 17015 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17016 SmallVectorImpl<Decl *> &AllIvarDecls) { 17017 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17018 return; 17019 17020 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17021 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17022 17023 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17024 return; 17025 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17026 if (!ID) { 17027 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17028 if (!CD->IsClassExtension()) 17029 return; 17030 } 17031 // No need to add this to end of @implementation. 17032 else 17033 return; 17034 } 17035 // All conditions are met. Add a new bitfield to the tail end of ivars. 17036 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17037 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17038 17039 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17040 DeclLoc, DeclLoc, nullptr, 17041 Context.CharTy, 17042 Context.getTrivialTypeSourceInfo(Context.CharTy, 17043 DeclLoc), 17044 ObjCIvarDecl::Private, BW, 17045 true); 17046 AllIvarDecls.push_back(Ivar); 17047 } 17048 17049 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17050 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17051 SourceLocation RBrac, 17052 const ParsedAttributesView &Attrs) { 17053 assert(EnclosingDecl && "missing record or interface decl"); 17054 17055 // If this is an Objective-C @implementation or category and we have 17056 // new fields here we should reset the layout of the interface since 17057 // it will now change. 17058 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17059 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17060 switch (DC->getKind()) { 17061 default: break; 17062 case Decl::ObjCCategory: 17063 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17064 break; 17065 case Decl::ObjCImplementation: 17066 Context. 17067 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17068 break; 17069 } 17070 } 17071 17072 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17073 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17074 17075 // Start counting up the number of named members; make sure to include 17076 // members of anonymous structs and unions in the total. 17077 unsigned NumNamedMembers = 0; 17078 if (Record) { 17079 for (const auto *I : Record->decls()) { 17080 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17081 if (IFD->getDeclName()) 17082 ++NumNamedMembers; 17083 } 17084 } 17085 17086 // Verify that all the fields are okay. 17087 SmallVector<FieldDecl*, 32> RecFields; 17088 17089 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17090 i != end; ++i) { 17091 FieldDecl *FD = cast<FieldDecl>(*i); 17092 17093 // Get the type for the field. 17094 const Type *FDTy = FD->getType().getTypePtr(); 17095 17096 if (!FD->isAnonymousStructOrUnion()) { 17097 // Remember all fields written by the user. 17098 RecFields.push_back(FD); 17099 } 17100 17101 // If the field is already invalid for some reason, don't emit more 17102 // diagnostics about it. 17103 if (FD->isInvalidDecl()) { 17104 EnclosingDecl->setInvalidDecl(); 17105 continue; 17106 } 17107 17108 // C99 6.7.2.1p2: 17109 // A structure or union shall not contain a member with 17110 // incomplete or function type (hence, a structure shall not 17111 // contain an instance of itself, but may contain a pointer to 17112 // an instance of itself), except that the last member of a 17113 // structure with more than one named member may have incomplete 17114 // array type; such a structure (and any union containing, 17115 // possibly recursively, a member that is such a structure) 17116 // shall not be a member of a structure or an element of an 17117 // array. 17118 bool IsLastField = (i + 1 == Fields.end()); 17119 if (FDTy->isFunctionType()) { 17120 // Field declared as a function. 17121 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17122 << FD->getDeclName(); 17123 FD->setInvalidDecl(); 17124 EnclosingDecl->setInvalidDecl(); 17125 continue; 17126 } else if (FDTy->isIncompleteArrayType() && 17127 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17128 if (Record) { 17129 // Flexible array member. 17130 // Microsoft and g++ is more permissive regarding flexible array. 17131 // It will accept flexible array in union and also 17132 // as the sole element of a struct/class. 17133 unsigned DiagID = 0; 17134 if (!Record->isUnion() && !IsLastField) { 17135 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17136 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17137 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17138 FD->setInvalidDecl(); 17139 EnclosingDecl->setInvalidDecl(); 17140 continue; 17141 } else if (Record->isUnion()) 17142 DiagID = getLangOpts().MicrosoftExt 17143 ? diag::ext_flexible_array_union_ms 17144 : getLangOpts().CPlusPlus 17145 ? diag::ext_flexible_array_union_gnu 17146 : diag::err_flexible_array_union; 17147 else if (NumNamedMembers < 1) 17148 DiagID = getLangOpts().MicrosoftExt 17149 ? diag::ext_flexible_array_empty_aggregate_ms 17150 : getLangOpts().CPlusPlus 17151 ? diag::ext_flexible_array_empty_aggregate_gnu 17152 : diag::err_flexible_array_empty_aggregate; 17153 17154 if (DiagID) 17155 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17156 << Record->getTagKind(); 17157 // While the layout of types that contain virtual bases is not specified 17158 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17159 // virtual bases after the derived members. This would make a flexible 17160 // array member declared at the end of an object not adjacent to the end 17161 // of the type. 17162 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17163 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17164 << FD->getDeclName() << Record->getTagKind(); 17165 if (!getLangOpts().C99) 17166 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17167 << FD->getDeclName() << Record->getTagKind(); 17168 17169 // If the element type has a non-trivial destructor, we would not 17170 // implicitly destroy the elements, so disallow it for now. 17171 // 17172 // FIXME: GCC allows this. We should probably either implicitly delete 17173 // the destructor of the containing class, or just allow this. 17174 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17175 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17176 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17177 << FD->getDeclName() << FD->getType(); 17178 FD->setInvalidDecl(); 17179 EnclosingDecl->setInvalidDecl(); 17180 continue; 17181 } 17182 // Okay, we have a legal flexible array member at the end of the struct. 17183 Record->setHasFlexibleArrayMember(true); 17184 } else { 17185 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17186 // unless they are followed by another ivar. That check is done 17187 // elsewhere, after synthesized ivars are known. 17188 } 17189 } else if (!FDTy->isDependentType() && 17190 RequireCompleteSizedType( 17191 FD->getLocation(), FD->getType(), 17192 diag::err_field_incomplete_or_sizeless)) { 17193 // Incomplete type 17194 FD->setInvalidDecl(); 17195 EnclosingDecl->setInvalidDecl(); 17196 continue; 17197 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17198 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17199 // A type which contains a flexible array member is considered to be a 17200 // flexible array member. 17201 Record->setHasFlexibleArrayMember(true); 17202 if (!Record->isUnion()) { 17203 // If this is a struct/class and this is not the last element, reject 17204 // it. Note that GCC supports variable sized arrays in the middle of 17205 // structures. 17206 if (!IsLastField) 17207 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17208 << FD->getDeclName() << FD->getType(); 17209 else { 17210 // We support flexible arrays at the end of structs in 17211 // other structs as an extension. 17212 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17213 << FD->getDeclName(); 17214 } 17215 } 17216 } 17217 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17218 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17219 diag::err_abstract_type_in_decl, 17220 AbstractIvarType)) { 17221 // Ivars can not have abstract class types 17222 FD->setInvalidDecl(); 17223 } 17224 if (Record && FDTTy->getDecl()->hasObjectMember()) 17225 Record->setHasObjectMember(true); 17226 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17227 Record->setHasVolatileMember(true); 17228 } else if (FDTy->isObjCObjectType()) { 17229 /// A field cannot be an Objective-c object 17230 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17231 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17232 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17233 FD->setType(T); 17234 } else if (Record && Record->isUnion() && 17235 FD->getType().hasNonTrivialObjCLifetime() && 17236 getSourceManager().isInSystemHeader(FD->getLocation()) && 17237 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17238 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17239 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17240 // For backward compatibility, fields of C unions declared in system 17241 // headers that have non-trivial ObjC ownership qualifications are marked 17242 // as unavailable unless the qualifier is explicit and __strong. This can 17243 // break ABI compatibility between programs compiled with ARC and MRR, but 17244 // is a better option than rejecting programs using those unions under 17245 // ARC. 17246 FD->addAttr(UnavailableAttr::CreateImplicit( 17247 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17248 FD->getLocation())); 17249 } else if (getLangOpts().ObjC && 17250 getLangOpts().getGC() != LangOptions::NonGC && Record && 17251 !Record->hasObjectMember()) { 17252 if (FD->getType()->isObjCObjectPointerType() || 17253 FD->getType().isObjCGCStrong()) 17254 Record->setHasObjectMember(true); 17255 else if (Context.getAsArrayType(FD->getType())) { 17256 QualType BaseType = Context.getBaseElementType(FD->getType()); 17257 if (BaseType->isRecordType() && 17258 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17259 Record->setHasObjectMember(true); 17260 else if (BaseType->isObjCObjectPointerType() || 17261 BaseType.isObjCGCStrong()) 17262 Record->setHasObjectMember(true); 17263 } 17264 } 17265 17266 if (Record && !getLangOpts().CPlusPlus && 17267 !shouldIgnoreForRecordTriviality(FD)) { 17268 QualType FT = FD->getType(); 17269 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17270 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17271 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17272 Record->isUnion()) 17273 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17274 } 17275 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17276 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17277 Record->setNonTrivialToPrimitiveCopy(true); 17278 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17279 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17280 } 17281 if (FT.isDestructedType()) { 17282 Record->setNonTrivialToPrimitiveDestroy(true); 17283 Record->setParamDestroyedInCallee(true); 17284 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17285 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17286 } 17287 17288 if (const auto *RT = FT->getAs<RecordType>()) { 17289 if (RT->getDecl()->getArgPassingRestrictions() == 17290 RecordDecl::APK_CanNeverPassInRegs) 17291 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17292 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17293 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17294 } 17295 17296 if (Record && FD->getType().isVolatileQualified()) 17297 Record->setHasVolatileMember(true); 17298 // Keep track of the number of named members. 17299 if (FD->getIdentifier()) 17300 ++NumNamedMembers; 17301 } 17302 17303 // Okay, we successfully defined 'Record'. 17304 if (Record) { 17305 bool Completed = false; 17306 if (CXXRecord) { 17307 if (!CXXRecord->isInvalidDecl()) { 17308 // Set access bits correctly on the directly-declared conversions. 17309 for (CXXRecordDecl::conversion_iterator 17310 I = CXXRecord->conversion_begin(), 17311 E = CXXRecord->conversion_end(); I != E; ++I) 17312 I.setAccess((*I)->getAccess()); 17313 } 17314 17315 // Add any implicitly-declared members to this class. 17316 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17317 17318 if (!CXXRecord->isDependentType()) { 17319 if (!CXXRecord->isInvalidDecl()) { 17320 // If we have virtual base classes, we may end up finding multiple 17321 // final overriders for a given virtual function. Check for this 17322 // problem now. 17323 if (CXXRecord->getNumVBases()) { 17324 CXXFinalOverriderMap FinalOverriders; 17325 CXXRecord->getFinalOverriders(FinalOverriders); 17326 17327 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17328 MEnd = FinalOverriders.end(); 17329 M != MEnd; ++M) { 17330 for (OverridingMethods::iterator SO = M->second.begin(), 17331 SOEnd = M->second.end(); 17332 SO != SOEnd; ++SO) { 17333 assert(SO->second.size() > 0 && 17334 "Virtual function without overriding functions?"); 17335 if (SO->second.size() == 1) 17336 continue; 17337 17338 // C++ [class.virtual]p2: 17339 // In a derived class, if a virtual member function of a base 17340 // class subobject has more than one final overrider the 17341 // program is ill-formed. 17342 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17343 << (const NamedDecl *)M->first << Record; 17344 Diag(M->first->getLocation(), 17345 diag::note_overridden_virtual_function); 17346 for (OverridingMethods::overriding_iterator 17347 OM = SO->second.begin(), 17348 OMEnd = SO->second.end(); 17349 OM != OMEnd; ++OM) 17350 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17351 << (const NamedDecl *)M->first << OM->Method->getParent(); 17352 17353 Record->setInvalidDecl(); 17354 } 17355 } 17356 CXXRecord->completeDefinition(&FinalOverriders); 17357 Completed = true; 17358 } 17359 } 17360 } 17361 } 17362 17363 if (!Completed) 17364 Record->completeDefinition(); 17365 17366 // Handle attributes before checking the layout. 17367 ProcessDeclAttributeList(S, Record, Attrs); 17368 17369 // We may have deferred checking for a deleted destructor. Check now. 17370 if (CXXRecord) { 17371 auto *Dtor = CXXRecord->getDestructor(); 17372 if (Dtor && Dtor->isImplicit() && 17373 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17374 CXXRecord->setImplicitDestructorIsDeleted(); 17375 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17376 } 17377 } 17378 17379 if (Record->hasAttrs()) { 17380 CheckAlignasUnderalignment(Record); 17381 17382 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17383 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17384 IA->getRange(), IA->getBestCase(), 17385 IA->getInheritanceModel()); 17386 } 17387 17388 // Check if the structure/union declaration is a type that can have zero 17389 // size in C. For C this is a language extension, for C++ it may cause 17390 // compatibility problems. 17391 bool CheckForZeroSize; 17392 if (!getLangOpts().CPlusPlus) { 17393 CheckForZeroSize = true; 17394 } else { 17395 // For C++ filter out types that cannot be referenced in C code. 17396 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17397 CheckForZeroSize = 17398 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17399 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17400 CXXRecord->isCLike(); 17401 } 17402 if (CheckForZeroSize) { 17403 bool ZeroSize = true; 17404 bool IsEmpty = true; 17405 unsigned NonBitFields = 0; 17406 for (RecordDecl::field_iterator I = Record->field_begin(), 17407 E = Record->field_end(); 17408 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17409 IsEmpty = false; 17410 if (I->isUnnamedBitfield()) { 17411 if (!I->isZeroLengthBitField(Context)) 17412 ZeroSize = false; 17413 } else { 17414 ++NonBitFields; 17415 QualType FieldType = I->getType(); 17416 if (FieldType->isIncompleteType() || 17417 !Context.getTypeSizeInChars(FieldType).isZero()) 17418 ZeroSize = false; 17419 } 17420 } 17421 17422 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17423 // allowed in C++, but warn if its declaration is inside 17424 // extern "C" block. 17425 if (ZeroSize) { 17426 Diag(RecLoc, getLangOpts().CPlusPlus ? 17427 diag::warn_zero_size_struct_union_in_extern_c : 17428 diag::warn_zero_size_struct_union_compat) 17429 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17430 } 17431 17432 // Structs without named members are extension in C (C99 6.7.2.1p7), 17433 // but are accepted by GCC. 17434 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17435 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17436 diag::ext_no_named_members_in_struct_union) 17437 << Record->isUnion(); 17438 } 17439 } 17440 } else { 17441 ObjCIvarDecl **ClsFields = 17442 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17443 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17444 ID->setEndOfDefinitionLoc(RBrac); 17445 // Add ivar's to class's DeclContext. 17446 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17447 ClsFields[i]->setLexicalDeclContext(ID); 17448 ID->addDecl(ClsFields[i]); 17449 } 17450 // Must enforce the rule that ivars in the base classes may not be 17451 // duplicates. 17452 if (ID->getSuperClass()) 17453 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17454 } else if (ObjCImplementationDecl *IMPDecl = 17455 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17456 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17457 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17458 // Ivar declared in @implementation never belongs to the implementation. 17459 // Only it is in implementation's lexical context. 17460 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17461 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17462 IMPDecl->setIvarLBraceLoc(LBrac); 17463 IMPDecl->setIvarRBraceLoc(RBrac); 17464 } else if (ObjCCategoryDecl *CDecl = 17465 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17466 // case of ivars in class extension; all other cases have been 17467 // reported as errors elsewhere. 17468 // FIXME. Class extension does not have a LocEnd field. 17469 // CDecl->setLocEnd(RBrac); 17470 // Add ivar's to class extension's DeclContext. 17471 // Diagnose redeclaration of private ivars. 17472 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17473 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17474 if (IDecl) { 17475 if (const ObjCIvarDecl *ClsIvar = 17476 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17477 Diag(ClsFields[i]->getLocation(), 17478 diag::err_duplicate_ivar_declaration); 17479 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17480 continue; 17481 } 17482 for (const auto *Ext : IDecl->known_extensions()) { 17483 if (const ObjCIvarDecl *ClsExtIvar 17484 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17485 Diag(ClsFields[i]->getLocation(), 17486 diag::err_duplicate_ivar_declaration); 17487 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17488 continue; 17489 } 17490 } 17491 } 17492 ClsFields[i]->setLexicalDeclContext(CDecl); 17493 CDecl->addDecl(ClsFields[i]); 17494 } 17495 CDecl->setIvarLBraceLoc(LBrac); 17496 CDecl->setIvarRBraceLoc(RBrac); 17497 } 17498 } 17499 } 17500 17501 /// Determine whether the given integral value is representable within 17502 /// the given type T. 17503 static bool isRepresentableIntegerValue(ASTContext &Context, 17504 llvm::APSInt &Value, 17505 QualType T) { 17506 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17507 "Integral type required!"); 17508 unsigned BitWidth = Context.getIntWidth(T); 17509 17510 if (Value.isUnsigned() || Value.isNonNegative()) { 17511 if (T->isSignedIntegerOrEnumerationType()) 17512 --BitWidth; 17513 return Value.getActiveBits() <= BitWidth; 17514 } 17515 return Value.getMinSignedBits() <= BitWidth; 17516 } 17517 17518 // Given an integral type, return the next larger integral type 17519 // (or a NULL type of no such type exists). 17520 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17521 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17522 // enum checking below. 17523 assert((T->isIntegralType(Context) || 17524 T->isEnumeralType()) && "Integral type required!"); 17525 const unsigned NumTypes = 4; 17526 QualType SignedIntegralTypes[NumTypes] = { 17527 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17528 }; 17529 QualType UnsignedIntegralTypes[NumTypes] = { 17530 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17531 Context.UnsignedLongLongTy 17532 }; 17533 17534 unsigned BitWidth = Context.getTypeSize(T); 17535 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17536 : UnsignedIntegralTypes; 17537 for (unsigned I = 0; I != NumTypes; ++I) 17538 if (Context.getTypeSize(Types[I]) > BitWidth) 17539 return Types[I]; 17540 17541 return QualType(); 17542 } 17543 17544 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17545 EnumConstantDecl *LastEnumConst, 17546 SourceLocation IdLoc, 17547 IdentifierInfo *Id, 17548 Expr *Val) { 17549 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17550 llvm::APSInt EnumVal(IntWidth); 17551 QualType EltTy; 17552 17553 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17554 Val = nullptr; 17555 17556 if (Val) 17557 Val = DefaultLvalueConversion(Val).get(); 17558 17559 if (Val) { 17560 if (Enum->isDependentType() || Val->isTypeDependent()) 17561 EltTy = Context.DependentTy; 17562 else { 17563 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17564 // underlying type, but do allow it in all other contexts. 17565 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17566 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17567 // constant-expression in the enumerator-definition shall be a converted 17568 // constant expression of the underlying type. 17569 EltTy = Enum->getIntegerType(); 17570 ExprResult Converted = 17571 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17572 CCEK_Enumerator); 17573 if (Converted.isInvalid()) 17574 Val = nullptr; 17575 else 17576 Val = Converted.get(); 17577 } else if (!Val->isValueDependent() && 17578 !(Val = 17579 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17580 .get())) { 17581 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17582 } else { 17583 if (Enum->isComplete()) { 17584 EltTy = Enum->getIntegerType(); 17585 17586 // In Obj-C and Microsoft mode, require the enumeration value to be 17587 // representable in the underlying type of the enumeration. In C++11, 17588 // we perform a non-narrowing conversion as part of converted constant 17589 // expression checking. 17590 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17591 if (Context.getTargetInfo() 17592 .getTriple() 17593 .isWindowsMSVCEnvironment()) { 17594 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17595 } else { 17596 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17597 } 17598 } 17599 17600 // Cast to the underlying type. 17601 Val = ImpCastExprToType(Val, EltTy, 17602 EltTy->isBooleanType() ? CK_IntegralToBoolean 17603 : CK_IntegralCast) 17604 .get(); 17605 } else if (getLangOpts().CPlusPlus) { 17606 // C++11 [dcl.enum]p5: 17607 // If the underlying type is not fixed, the type of each enumerator 17608 // is the type of its initializing value: 17609 // - If an initializer is specified for an enumerator, the 17610 // initializing value has the same type as the expression. 17611 EltTy = Val->getType(); 17612 } else { 17613 // C99 6.7.2.2p2: 17614 // The expression that defines the value of an enumeration constant 17615 // shall be an integer constant expression that has a value 17616 // representable as an int. 17617 17618 // Complain if the value is not representable in an int. 17619 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17620 Diag(IdLoc, diag::ext_enum_value_not_int) 17621 << EnumVal.toString(10) << Val->getSourceRange() 17622 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17623 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17624 // Force the type of the expression to 'int'. 17625 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17626 } 17627 EltTy = Val->getType(); 17628 } 17629 } 17630 } 17631 } 17632 17633 if (!Val) { 17634 if (Enum->isDependentType()) 17635 EltTy = Context.DependentTy; 17636 else if (!LastEnumConst) { 17637 // C++0x [dcl.enum]p5: 17638 // If the underlying type is not fixed, the type of each enumerator 17639 // is the type of its initializing value: 17640 // - If no initializer is specified for the first enumerator, the 17641 // initializing value has an unspecified integral type. 17642 // 17643 // GCC uses 'int' for its unspecified integral type, as does 17644 // C99 6.7.2.2p3. 17645 if (Enum->isFixed()) { 17646 EltTy = Enum->getIntegerType(); 17647 } 17648 else { 17649 EltTy = Context.IntTy; 17650 } 17651 } else { 17652 // Assign the last value + 1. 17653 EnumVal = LastEnumConst->getInitVal(); 17654 ++EnumVal; 17655 EltTy = LastEnumConst->getType(); 17656 17657 // Check for overflow on increment. 17658 if (EnumVal < LastEnumConst->getInitVal()) { 17659 // C++0x [dcl.enum]p5: 17660 // If the underlying type is not fixed, the type of each enumerator 17661 // is the type of its initializing value: 17662 // 17663 // - Otherwise the type of the initializing value is the same as 17664 // the type of the initializing value of the preceding enumerator 17665 // unless the incremented value is not representable in that type, 17666 // in which case the type is an unspecified integral type 17667 // sufficient to contain the incremented value. If no such type 17668 // exists, the program is ill-formed. 17669 QualType T = getNextLargerIntegralType(Context, EltTy); 17670 if (T.isNull() || Enum->isFixed()) { 17671 // There is no integral type larger enough to represent this 17672 // value. Complain, then allow the value to wrap around. 17673 EnumVal = LastEnumConst->getInitVal(); 17674 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17675 ++EnumVal; 17676 if (Enum->isFixed()) 17677 // When the underlying type is fixed, this is ill-formed. 17678 Diag(IdLoc, diag::err_enumerator_wrapped) 17679 << EnumVal.toString(10) 17680 << EltTy; 17681 else 17682 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17683 << EnumVal.toString(10); 17684 } else { 17685 EltTy = T; 17686 } 17687 17688 // Retrieve the last enumerator's value, extent that type to the 17689 // type that is supposed to be large enough to represent the incremented 17690 // value, then increment. 17691 EnumVal = LastEnumConst->getInitVal(); 17692 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17693 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17694 ++EnumVal; 17695 17696 // If we're not in C++, diagnose the overflow of enumerator values, 17697 // which in C99 means that the enumerator value is not representable in 17698 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17699 // permits enumerator values that are representable in some larger 17700 // integral type. 17701 if (!getLangOpts().CPlusPlus && !T.isNull()) 17702 Diag(IdLoc, diag::warn_enum_value_overflow); 17703 } else if (!getLangOpts().CPlusPlus && 17704 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17705 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17706 Diag(IdLoc, diag::ext_enum_value_not_int) 17707 << EnumVal.toString(10) << 1; 17708 } 17709 } 17710 } 17711 17712 if (!EltTy->isDependentType()) { 17713 // Make the enumerator value match the signedness and size of the 17714 // enumerator's type. 17715 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17716 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17717 } 17718 17719 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17720 Val, EnumVal); 17721 } 17722 17723 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17724 SourceLocation IILoc) { 17725 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17726 !getLangOpts().CPlusPlus) 17727 return SkipBodyInfo(); 17728 17729 // We have an anonymous enum definition. Look up the first enumerator to 17730 // determine if we should merge the definition with an existing one and 17731 // skip the body. 17732 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17733 forRedeclarationInCurContext()); 17734 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17735 if (!PrevECD) 17736 return SkipBodyInfo(); 17737 17738 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17739 NamedDecl *Hidden; 17740 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17741 SkipBodyInfo Skip; 17742 Skip.Previous = Hidden; 17743 return Skip; 17744 } 17745 17746 return SkipBodyInfo(); 17747 } 17748 17749 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17750 SourceLocation IdLoc, IdentifierInfo *Id, 17751 const ParsedAttributesView &Attrs, 17752 SourceLocation EqualLoc, Expr *Val) { 17753 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17754 EnumConstantDecl *LastEnumConst = 17755 cast_or_null<EnumConstantDecl>(lastEnumConst); 17756 17757 // The scope passed in may not be a decl scope. Zip up the scope tree until 17758 // we find one that is. 17759 S = getNonFieldDeclScope(S); 17760 17761 // Verify that there isn't already something declared with this name in this 17762 // scope. 17763 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17764 LookupName(R, S); 17765 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17766 17767 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17768 // Maybe we will complain about the shadowed template parameter. 17769 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17770 // Just pretend that we didn't see the previous declaration. 17771 PrevDecl = nullptr; 17772 } 17773 17774 // C++ [class.mem]p15: 17775 // If T is the name of a class, then each of the following shall have a name 17776 // different from T: 17777 // - every enumerator of every member of class T that is an unscoped 17778 // enumerated type 17779 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17780 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17781 DeclarationNameInfo(Id, IdLoc)); 17782 17783 EnumConstantDecl *New = 17784 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17785 if (!New) 17786 return nullptr; 17787 17788 if (PrevDecl) { 17789 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17790 // Check for other kinds of shadowing not already handled. 17791 CheckShadow(New, PrevDecl, R); 17792 } 17793 17794 // When in C++, we may get a TagDecl with the same name; in this case the 17795 // enum constant will 'hide' the tag. 17796 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17797 "Received TagDecl when not in C++!"); 17798 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17799 if (isa<EnumConstantDecl>(PrevDecl)) 17800 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17801 else 17802 Diag(IdLoc, diag::err_redefinition) << Id; 17803 notePreviousDefinition(PrevDecl, IdLoc); 17804 return nullptr; 17805 } 17806 } 17807 17808 // Process attributes. 17809 ProcessDeclAttributeList(S, New, Attrs); 17810 AddPragmaAttributes(S, New); 17811 17812 // Register this decl in the current scope stack. 17813 New->setAccess(TheEnumDecl->getAccess()); 17814 PushOnScopeChains(New, S); 17815 17816 ActOnDocumentableDecl(New); 17817 17818 return New; 17819 } 17820 17821 // Returns true when the enum initial expression does not trigger the 17822 // duplicate enum warning. A few common cases are exempted as follows: 17823 // Element2 = Element1 17824 // Element2 = Element1 + 1 17825 // Element2 = Element1 - 1 17826 // Where Element2 and Element1 are from the same enum. 17827 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17828 Expr *InitExpr = ECD->getInitExpr(); 17829 if (!InitExpr) 17830 return true; 17831 InitExpr = InitExpr->IgnoreImpCasts(); 17832 17833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17834 if (!BO->isAdditiveOp()) 17835 return true; 17836 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17837 if (!IL) 17838 return true; 17839 if (IL->getValue() != 1) 17840 return true; 17841 17842 InitExpr = BO->getLHS(); 17843 } 17844 17845 // This checks if the elements are from the same enum. 17846 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17847 if (!DRE) 17848 return true; 17849 17850 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17851 if (!EnumConstant) 17852 return true; 17853 17854 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17855 Enum) 17856 return true; 17857 17858 return false; 17859 } 17860 17861 // Emits a warning when an element is implicitly set a value that 17862 // a previous element has already been set to. 17863 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17864 EnumDecl *Enum, QualType EnumType) { 17865 // Avoid anonymous enums 17866 if (!Enum->getIdentifier()) 17867 return; 17868 17869 // Only check for small enums. 17870 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17871 return; 17872 17873 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17874 return; 17875 17876 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17877 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17878 17879 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17880 17881 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17882 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17883 17884 // Use int64_t as a key to avoid needing special handling for map keys. 17885 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17886 llvm::APSInt Val = D->getInitVal(); 17887 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17888 }; 17889 17890 DuplicatesVector DupVector; 17891 ValueToVectorMap EnumMap; 17892 17893 // Populate the EnumMap with all values represented by enum constants without 17894 // an initializer. 17895 for (auto *Element : Elements) { 17896 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17897 17898 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17899 // this constant. Skip this enum since it may be ill-formed. 17900 if (!ECD) { 17901 return; 17902 } 17903 17904 // Constants with initalizers are handled in the next loop. 17905 if (ECD->getInitExpr()) 17906 continue; 17907 17908 // Duplicate values are handled in the next loop. 17909 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17910 } 17911 17912 if (EnumMap.size() == 0) 17913 return; 17914 17915 // Create vectors for any values that has duplicates. 17916 for (auto *Element : Elements) { 17917 // The last loop returned if any constant was null. 17918 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17919 if (!ValidDuplicateEnum(ECD, Enum)) 17920 continue; 17921 17922 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17923 if (Iter == EnumMap.end()) 17924 continue; 17925 17926 DeclOrVector& Entry = Iter->second; 17927 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17928 // Ensure constants are different. 17929 if (D == ECD) 17930 continue; 17931 17932 // Create new vector and push values onto it. 17933 auto Vec = std::make_unique<ECDVector>(); 17934 Vec->push_back(D); 17935 Vec->push_back(ECD); 17936 17937 // Update entry to point to the duplicates vector. 17938 Entry = Vec.get(); 17939 17940 // Store the vector somewhere we can consult later for quick emission of 17941 // diagnostics. 17942 DupVector.emplace_back(std::move(Vec)); 17943 continue; 17944 } 17945 17946 ECDVector *Vec = Entry.get<ECDVector*>(); 17947 // Make sure constants are not added more than once. 17948 if (*Vec->begin() == ECD) 17949 continue; 17950 17951 Vec->push_back(ECD); 17952 } 17953 17954 // Emit diagnostics. 17955 for (const auto &Vec : DupVector) { 17956 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17957 17958 // Emit warning for one enum constant. 17959 auto *FirstECD = Vec->front(); 17960 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17961 << FirstECD << FirstECD->getInitVal().toString(10) 17962 << FirstECD->getSourceRange(); 17963 17964 // Emit one note for each of the remaining enum constants with 17965 // the same value. 17966 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17967 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17968 << ECD << ECD->getInitVal().toString(10) 17969 << ECD->getSourceRange(); 17970 } 17971 } 17972 17973 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17974 bool AllowMask) const { 17975 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17976 assert(ED->isCompleteDefinition() && "expected enum definition"); 17977 17978 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17979 llvm::APInt &FlagBits = R.first->second; 17980 17981 if (R.second) { 17982 for (auto *E : ED->enumerators()) { 17983 const auto &EVal = E->getInitVal(); 17984 // Only single-bit enumerators introduce new flag values. 17985 if (EVal.isPowerOf2()) 17986 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17987 } 17988 } 17989 17990 // A value is in a flag enum if either its bits are a subset of the enum's 17991 // flag bits (the first condition) or we are allowing masks and the same is 17992 // true of its complement (the second condition). When masks are allowed, we 17993 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17994 // 17995 // While it's true that any value could be used as a mask, the assumption is 17996 // that a mask will have all of the insignificant bits set. Anything else is 17997 // likely a logic error. 17998 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17999 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18000 } 18001 18002 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18003 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18004 const ParsedAttributesView &Attrs) { 18005 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18006 QualType EnumType = Context.getTypeDeclType(Enum); 18007 18008 ProcessDeclAttributeList(S, Enum, Attrs); 18009 18010 if (Enum->isDependentType()) { 18011 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18012 EnumConstantDecl *ECD = 18013 cast_or_null<EnumConstantDecl>(Elements[i]); 18014 if (!ECD) continue; 18015 18016 ECD->setType(EnumType); 18017 } 18018 18019 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18020 return; 18021 } 18022 18023 // TODO: If the result value doesn't fit in an int, it must be a long or long 18024 // long value. ISO C does not support this, but GCC does as an extension, 18025 // emit a warning. 18026 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18027 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18028 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18029 18030 // Verify that all the values are okay, compute the size of the values, and 18031 // reverse the list. 18032 unsigned NumNegativeBits = 0; 18033 unsigned NumPositiveBits = 0; 18034 18035 // Keep track of whether all elements have type int. 18036 bool AllElementsInt = true; 18037 18038 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18039 EnumConstantDecl *ECD = 18040 cast_or_null<EnumConstantDecl>(Elements[i]); 18041 if (!ECD) continue; // Already issued a diagnostic. 18042 18043 const llvm::APSInt &InitVal = ECD->getInitVal(); 18044 18045 // Keep track of the size of positive and negative values. 18046 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18047 NumPositiveBits = std::max(NumPositiveBits, 18048 (unsigned)InitVal.getActiveBits()); 18049 else 18050 NumNegativeBits = std::max(NumNegativeBits, 18051 (unsigned)InitVal.getMinSignedBits()); 18052 18053 // Keep track of whether every enum element has type int (very common). 18054 if (AllElementsInt) 18055 AllElementsInt = ECD->getType() == Context.IntTy; 18056 } 18057 18058 // Figure out the type that should be used for this enum. 18059 QualType BestType; 18060 unsigned BestWidth; 18061 18062 // C++0x N3000 [conv.prom]p3: 18063 // An rvalue of an unscoped enumeration type whose underlying 18064 // type is not fixed can be converted to an rvalue of the first 18065 // of the following types that can represent all the values of 18066 // the enumeration: int, unsigned int, long int, unsigned long 18067 // int, long long int, or unsigned long long int. 18068 // C99 6.4.4.3p2: 18069 // An identifier declared as an enumeration constant has type int. 18070 // The C99 rule is modified by a gcc extension 18071 QualType BestPromotionType; 18072 18073 bool Packed = Enum->hasAttr<PackedAttr>(); 18074 // -fshort-enums is the equivalent to specifying the packed attribute on all 18075 // enum definitions. 18076 if (LangOpts.ShortEnums) 18077 Packed = true; 18078 18079 // If the enum already has a type because it is fixed or dictated by the 18080 // target, promote that type instead of analyzing the enumerators. 18081 if (Enum->isComplete()) { 18082 BestType = Enum->getIntegerType(); 18083 if (BestType->isPromotableIntegerType()) 18084 BestPromotionType = Context.getPromotedIntegerType(BestType); 18085 else 18086 BestPromotionType = BestType; 18087 18088 BestWidth = Context.getIntWidth(BestType); 18089 } 18090 else if (NumNegativeBits) { 18091 // If there is a negative value, figure out the smallest integer type (of 18092 // int/long/longlong) that fits. 18093 // If it's packed, check also if it fits a char or a short. 18094 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18095 BestType = Context.SignedCharTy; 18096 BestWidth = CharWidth; 18097 } else if (Packed && NumNegativeBits <= ShortWidth && 18098 NumPositiveBits < ShortWidth) { 18099 BestType = Context.ShortTy; 18100 BestWidth = ShortWidth; 18101 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18102 BestType = Context.IntTy; 18103 BestWidth = IntWidth; 18104 } else { 18105 BestWidth = Context.getTargetInfo().getLongWidth(); 18106 18107 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18108 BestType = Context.LongTy; 18109 } else { 18110 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18111 18112 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18113 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18114 BestType = Context.LongLongTy; 18115 } 18116 } 18117 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18118 } else { 18119 // If there is no negative value, figure out the smallest type that fits 18120 // all of the enumerator values. 18121 // If it's packed, check also if it fits a char or a short. 18122 if (Packed && NumPositiveBits <= CharWidth) { 18123 BestType = Context.UnsignedCharTy; 18124 BestPromotionType = Context.IntTy; 18125 BestWidth = CharWidth; 18126 } else if (Packed && NumPositiveBits <= ShortWidth) { 18127 BestType = Context.UnsignedShortTy; 18128 BestPromotionType = Context.IntTy; 18129 BestWidth = ShortWidth; 18130 } else if (NumPositiveBits <= IntWidth) { 18131 BestType = Context.UnsignedIntTy; 18132 BestWidth = IntWidth; 18133 BestPromotionType 18134 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18135 ? Context.UnsignedIntTy : Context.IntTy; 18136 } else if (NumPositiveBits <= 18137 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18138 BestType = Context.UnsignedLongTy; 18139 BestPromotionType 18140 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18141 ? Context.UnsignedLongTy : Context.LongTy; 18142 } else { 18143 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18144 assert(NumPositiveBits <= BestWidth && 18145 "How could an initializer get larger than ULL?"); 18146 BestType = Context.UnsignedLongLongTy; 18147 BestPromotionType 18148 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18149 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18150 } 18151 } 18152 18153 // Loop over all of the enumerator constants, changing their types to match 18154 // the type of the enum if needed. 18155 for (auto *D : Elements) { 18156 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18157 if (!ECD) continue; // Already issued a diagnostic. 18158 18159 // Standard C says the enumerators have int type, but we allow, as an 18160 // extension, the enumerators to be larger than int size. If each 18161 // enumerator value fits in an int, type it as an int, otherwise type it the 18162 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18163 // that X has type 'int', not 'unsigned'. 18164 18165 // Determine whether the value fits into an int. 18166 llvm::APSInt InitVal = ECD->getInitVal(); 18167 18168 // If it fits into an integer type, force it. Otherwise force it to match 18169 // the enum decl type. 18170 QualType NewTy; 18171 unsigned NewWidth; 18172 bool NewSign; 18173 if (!getLangOpts().CPlusPlus && 18174 !Enum->isFixed() && 18175 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18176 NewTy = Context.IntTy; 18177 NewWidth = IntWidth; 18178 NewSign = true; 18179 } else if (ECD->getType() == BestType) { 18180 // Already the right type! 18181 if (getLangOpts().CPlusPlus) 18182 // C++ [dcl.enum]p4: Following the closing brace of an 18183 // enum-specifier, each enumerator has the type of its 18184 // enumeration. 18185 ECD->setType(EnumType); 18186 continue; 18187 } else { 18188 NewTy = BestType; 18189 NewWidth = BestWidth; 18190 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18191 } 18192 18193 // Adjust the APSInt value. 18194 InitVal = InitVal.extOrTrunc(NewWidth); 18195 InitVal.setIsSigned(NewSign); 18196 ECD->setInitVal(InitVal); 18197 18198 // Adjust the Expr initializer and type. 18199 if (ECD->getInitExpr() && 18200 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18201 ECD->setInitExpr(ImplicitCastExpr::Create( 18202 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18203 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18204 if (getLangOpts().CPlusPlus) 18205 // C++ [dcl.enum]p4: Following the closing brace of an 18206 // enum-specifier, each enumerator has the type of its 18207 // enumeration. 18208 ECD->setType(EnumType); 18209 else 18210 ECD->setType(NewTy); 18211 } 18212 18213 Enum->completeDefinition(BestType, BestPromotionType, 18214 NumPositiveBits, NumNegativeBits); 18215 18216 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18217 18218 if (Enum->isClosedFlag()) { 18219 for (Decl *D : Elements) { 18220 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18221 if (!ECD) continue; // Already issued a diagnostic. 18222 18223 llvm::APSInt InitVal = ECD->getInitVal(); 18224 if (InitVal != 0 && !InitVal.isPowerOf2() && 18225 !IsValueInFlagEnum(Enum, InitVal, true)) 18226 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18227 << ECD << Enum; 18228 } 18229 } 18230 18231 // Now that the enum type is defined, ensure it's not been underaligned. 18232 if (Enum->hasAttrs()) 18233 CheckAlignasUnderalignment(Enum); 18234 } 18235 18236 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18237 SourceLocation StartLoc, 18238 SourceLocation EndLoc) { 18239 StringLiteral *AsmString = cast<StringLiteral>(expr); 18240 18241 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18242 AsmString, StartLoc, 18243 EndLoc); 18244 CurContext->addDecl(New); 18245 return New; 18246 } 18247 18248 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18249 IdentifierInfo* AliasName, 18250 SourceLocation PragmaLoc, 18251 SourceLocation NameLoc, 18252 SourceLocation AliasNameLoc) { 18253 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18254 LookupOrdinaryName); 18255 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18256 AttributeCommonInfo::AS_Pragma); 18257 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18258 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18259 18260 // If a declaration that: 18261 // 1) declares a function or a variable 18262 // 2) has external linkage 18263 // already exists, add a label attribute to it. 18264 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18265 if (isDeclExternC(PrevDecl)) 18266 PrevDecl->addAttr(Attr); 18267 else 18268 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18269 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18270 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18271 } else 18272 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18273 } 18274 18275 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18276 SourceLocation PragmaLoc, 18277 SourceLocation NameLoc) { 18278 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18279 18280 if (PrevDecl) { 18281 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18282 } else { 18283 (void)WeakUndeclaredIdentifiers.insert( 18284 std::pair<IdentifierInfo*,WeakInfo> 18285 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18286 } 18287 } 18288 18289 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18290 IdentifierInfo* AliasName, 18291 SourceLocation PragmaLoc, 18292 SourceLocation NameLoc, 18293 SourceLocation AliasNameLoc) { 18294 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18295 LookupOrdinaryName); 18296 WeakInfo W = WeakInfo(Name, NameLoc); 18297 18298 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18299 if (!PrevDecl->hasAttr<AliasAttr>()) 18300 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18301 DeclApplyPragmaWeak(TUScope, ND, W); 18302 } else { 18303 (void)WeakUndeclaredIdentifiers.insert( 18304 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18305 } 18306 } 18307 18308 Decl *Sema::getObjCDeclContext() const { 18309 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18310 } 18311 18312 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18313 bool Final) { 18314 // SYCL functions can be template, so we check if they have appropriate 18315 // attribute prior to checking if it is a template. 18316 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18317 return FunctionEmissionStatus::Emitted; 18318 18319 // Templates are emitted when they're instantiated. 18320 if (FD->isDependentContext()) 18321 return FunctionEmissionStatus::TemplateDiscarded; 18322 18323 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18324 if (LangOpts.OpenMPIsDevice) { 18325 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18326 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18327 if (DevTy.hasValue()) { 18328 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18329 OMPES = FunctionEmissionStatus::OMPDiscarded; 18330 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18331 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18332 OMPES = FunctionEmissionStatus::Emitted; 18333 } 18334 } 18335 } else if (LangOpts.OpenMP) { 18336 // In OpenMP 4.5 all the functions are host functions. 18337 if (LangOpts.OpenMP <= 45) { 18338 OMPES = FunctionEmissionStatus::Emitted; 18339 } else { 18340 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18341 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18342 // In OpenMP 5.0 or above, DevTy may be changed later by 18343 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18344 // having no value does not imply host. The emission status will be 18345 // checked again at the end of compilation unit. 18346 if (DevTy.hasValue()) { 18347 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18348 OMPES = FunctionEmissionStatus::OMPDiscarded; 18349 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18350 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18351 OMPES = FunctionEmissionStatus::Emitted; 18352 } else if (Final) 18353 OMPES = FunctionEmissionStatus::Emitted; 18354 } 18355 } 18356 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18357 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18358 return OMPES; 18359 18360 if (LangOpts.CUDA) { 18361 // When compiling for device, host functions are never emitted. Similarly, 18362 // when compiling for host, device and global functions are never emitted. 18363 // (Technically, we do emit a host-side stub for global functions, but this 18364 // doesn't count for our purposes here.) 18365 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18366 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18367 return FunctionEmissionStatus::CUDADiscarded; 18368 if (!LangOpts.CUDAIsDevice && 18369 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18370 return FunctionEmissionStatus::CUDADiscarded; 18371 18372 // Check whether this function is externally visible -- if so, it's 18373 // known-emitted. 18374 // 18375 // We have to check the GVA linkage of the function's *definition* -- if we 18376 // only have a declaration, we don't know whether or not the function will 18377 // be emitted, because (say) the definition could include "inline". 18378 FunctionDecl *Def = FD->getDefinition(); 18379 18380 if (Def && 18381 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18382 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18383 return FunctionEmissionStatus::Emitted; 18384 } 18385 18386 // Otherwise, the function is known-emitted if it's in our set of 18387 // known-emitted functions. 18388 return FunctionEmissionStatus::Unknown; 18389 } 18390 18391 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18392 // Host-side references to a __global__ function refer to the stub, so the 18393 // function itself is never emitted and therefore should not be marked. 18394 // If we have host fn calls kernel fn calls host+device, the HD function 18395 // does not get instantiated on the host. We model this by omitting at the 18396 // call to the kernel from the callgraph. This ensures that, when compiling 18397 // for host, only HD functions actually called from the host get marked as 18398 // known-emitted. 18399 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18400 IdentifyCUDATarget(Callee) == CFT_Global; 18401 } 18402