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 || (*Res)->getLocation() < IIDecl->getLocation()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 752 SuggestedType = 753 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 754 } else if (isDependentScopeSpecifier(*SS)) { 755 unsigned DiagID = diag::err_typename_missing; 756 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 757 DiagID = diag::ext_typename_missing; 758 759 Diag(SS->getRange().getBegin(), DiagID) 760 << SS->getScopeRep() << II->getName() 761 << SourceRange(SS->getRange().getBegin(), IILoc) 762 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 763 SuggestedType = ActOnTypenameType(S, SourceLocation(), 764 *SS, *II, IILoc).get(); 765 } else { 766 assert(SS && SS->isInvalid() && 767 "Invalid scope specifier has already been diagnosed"); 768 } 769 } 770 771 /// Determine whether the given result set contains either a type name 772 /// or 773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 774 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 775 NextToken.is(tok::less); 776 777 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 778 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 779 return true; 780 781 if (CheckTemplate && isa<TemplateDecl>(*I)) 782 return true; 783 } 784 785 return false; 786 } 787 788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 789 Scope *S, CXXScopeSpec &SS, 790 IdentifierInfo *&Name, 791 SourceLocation NameLoc) { 792 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 793 SemaRef.LookupParsedName(R, S, &SS); 794 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 795 StringRef FixItTagName; 796 switch (Tag->getTagKind()) { 797 case TTK_Class: 798 FixItTagName = "class "; 799 break; 800 801 case TTK_Enum: 802 FixItTagName = "enum "; 803 break; 804 805 case TTK_Struct: 806 FixItTagName = "struct "; 807 break; 808 809 case TTK_Interface: 810 FixItTagName = "__interface "; 811 break; 812 813 case TTK_Union: 814 FixItTagName = "union "; 815 break; 816 } 817 818 StringRef TagName = FixItTagName.drop_back(); 819 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 820 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 821 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 822 823 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 824 I != IEnd; ++I) 825 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 826 << Name << TagName; 827 828 // Replace lookup results with just the tag decl. 829 Result.clear(Sema::LookupTagName); 830 SemaRef.LookupParsedName(Result, S, &SS); 831 return true; 832 } 833 834 return false; 835 } 836 837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 839 QualType T, SourceLocation NameLoc) { 840 ASTContext &Context = S.Context; 841 842 TypeLocBuilder Builder; 843 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 844 845 T = S.getElaboratedType(ETK_None, SS, T); 846 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 847 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 848 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 849 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 850 } 851 852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 853 IdentifierInfo *&Name, 854 SourceLocation NameLoc, 855 const Token &NextToken, 856 CorrectionCandidateCallback *CCC) { 857 DeclarationNameInfo NameInfo(Name, NameLoc); 858 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 859 860 assert(NextToken.isNot(tok::coloncolon) && 861 "parse nested name specifiers before calling ClassifyName"); 862 if (getLangOpts().CPlusPlus && SS.isSet() && 863 isCurrentClassName(*Name, S, &SS)) { 864 // Per [class.qual]p2, this names the constructors of SS, not the 865 // injected-class-name. We don't have a classification for that. 866 // There's not much point caching this result, since the parser 867 // will reject it later. 868 return NameClassification::Unknown(); 869 } 870 871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 872 LookupParsedName(Result, S, &SS, !CurMethod); 873 874 if (SS.isInvalid()) 875 return NameClassification::Error(); 876 877 // For unqualified lookup in a class template in MSVC mode, look into 878 // dependent base classes where the primary class template is known. 879 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 880 if (ParsedType TypeInBase = 881 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 882 return TypeInBase; 883 } 884 885 // Perform lookup for Objective-C instance variables (including automatically 886 // synthesized instance variables), if we're in an Objective-C method. 887 // FIXME: This lookup really, really needs to be folded in to the normal 888 // unqualified lookup mechanism. 889 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 890 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 891 if (Ivar.isInvalid()) 892 return NameClassification::Error(); 893 if (Ivar.isUsable()) 894 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 895 896 // We defer builtin creation until after ivar lookup inside ObjC methods. 897 if (Result.empty()) 898 LookupBuiltin(Result); 899 } 900 901 bool SecondTry = false; 902 bool IsFilteredTemplateName = false; 903 904 Corrected: 905 switch (Result.getResultKind()) { 906 case LookupResult::NotFound: 907 // If an unqualified-id is followed by a '(', then we have a function 908 // call. 909 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 910 // In C++, this is an ADL-only call. 911 // FIXME: Reference? 912 if (getLangOpts().CPlusPlus) 913 return NameClassification::UndeclaredNonType(); 914 915 // C90 6.3.2.2: 916 // If the expression that precedes the parenthesized argument list in a 917 // function call consists solely of an identifier, and if no 918 // declaration is visible for this identifier, the identifier is 919 // implicitly declared exactly as if, in the innermost block containing 920 // the function call, the declaration 921 // 922 // extern int identifier (); 923 // 924 // appeared. 925 // 926 // We also allow this in C99 as an extension. 927 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 928 return NameClassification::NonType(D); 929 } 930 931 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 932 // In C++20 onwards, this could be an ADL-only call to a function 933 // template, and we're required to assume that this is a template name. 934 // 935 // FIXME: Find a way to still do typo correction in this case. 936 TemplateName Template = 937 Context.getAssumedTemplateName(NameInfo.getName()); 938 return NameClassification::UndeclaredTemplate(Template); 939 } 940 941 // In C, we first see whether there is a tag type by the same name, in 942 // which case it's likely that the user just forgot to write "enum", 943 // "struct", or "union". 944 if (!getLangOpts().CPlusPlus && !SecondTry && 945 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 946 break; 947 } 948 949 // Perform typo correction to determine if there is another name that is 950 // close to this name. 951 if (!SecondTry && CCC) { 952 SecondTry = true; 953 if (TypoCorrection Corrected = 954 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 955 &SS, *CCC, CTK_ErrorRecovery)) { 956 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 957 unsigned QualifiedDiag = diag::err_no_member_suggest; 958 959 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 960 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 961 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 962 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 963 UnqualifiedDiag = diag::err_no_template_suggest; 964 QualifiedDiag = diag::err_no_member_template_suggest; 965 } else if (UnderlyingFirstDecl && 966 (isa<TypeDecl>(UnderlyingFirstDecl) || 967 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 968 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 969 UnqualifiedDiag = diag::err_unknown_typename_suggest; 970 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 971 } 972 973 if (SS.isEmpty()) { 974 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 975 } else {// FIXME: is this even reachable? Test it. 976 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 977 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 978 Name->getName().equals(CorrectedStr); 979 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 980 << Name << computeDeclContext(SS, false) 981 << DroppedSpecifier << SS.getRange()); 982 } 983 984 // Update the name, so that the caller has the new name. 985 Name = Corrected.getCorrectionAsIdentifierInfo(); 986 987 // Typo correction corrected to a keyword. 988 if (Corrected.isKeyword()) 989 return Name; 990 991 // Also update the LookupResult... 992 // FIXME: This should probably go away at some point 993 Result.clear(); 994 Result.setLookupName(Corrected.getCorrection()); 995 if (FirstDecl) 996 Result.addDecl(FirstDecl); 997 998 // If we found an Objective-C instance variable, let 999 // LookupInObjCMethod build the appropriate expression to 1000 // reference the ivar. 1001 // FIXME: This is a gross hack. 1002 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1003 DeclResult R = 1004 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1005 if (R.isInvalid()) 1006 return NameClassification::Error(); 1007 if (R.isUsable()) 1008 return NameClassification::NonType(Ivar); 1009 } 1010 1011 goto Corrected; 1012 } 1013 } 1014 1015 // We failed to correct; just fall through and let the parser deal with it. 1016 Result.suppressDiagnostics(); 1017 return NameClassification::Unknown(); 1018 1019 case LookupResult::NotFoundInCurrentInstantiation: { 1020 // We performed name lookup into the current instantiation, and there were 1021 // dependent bases, so we treat this result the same way as any other 1022 // dependent nested-name-specifier. 1023 1024 // C++ [temp.res]p2: 1025 // A name used in a template declaration or definition and that is 1026 // dependent on a template-parameter is assumed not to name a type 1027 // unless the applicable name lookup finds a type name or the name is 1028 // qualified by the keyword typename. 1029 // 1030 // FIXME: If the next token is '<', we might want to ask the parser to 1031 // perform some heroics to see if we actually have a 1032 // template-argument-list, which would indicate a missing 'template' 1033 // keyword here. 1034 return NameClassification::DependentNonType(); 1035 } 1036 1037 case LookupResult::Found: 1038 case LookupResult::FoundOverloaded: 1039 case LookupResult::FoundUnresolvedValue: 1040 break; 1041 1042 case LookupResult::Ambiguous: 1043 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1044 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1045 /*AllowDependent=*/false)) { 1046 // C++ [temp.local]p3: 1047 // A lookup that finds an injected-class-name (10.2) can result in an 1048 // ambiguity in certain cases (for example, if it is found in more than 1049 // one base class). If all of the injected-class-names that are found 1050 // refer to specializations of the same class template, and if the name 1051 // is followed by a template-argument-list, the reference refers to the 1052 // class template itself and not a specialization thereof, and is not 1053 // ambiguous. 1054 // 1055 // This filtering can make an ambiguous result into an unambiguous one, 1056 // so try again after filtering out template names. 1057 FilterAcceptableTemplateNames(Result); 1058 if (!Result.isAmbiguous()) { 1059 IsFilteredTemplateName = true; 1060 break; 1061 } 1062 } 1063 1064 // Diagnose the ambiguity and return an error. 1065 return NameClassification::Error(); 1066 } 1067 1068 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1069 (IsFilteredTemplateName || 1070 hasAnyAcceptableTemplateNames( 1071 Result, /*AllowFunctionTemplates=*/true, 1072 /*AllowDependent=*/false, 1073 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1074 getLangOpts().CPlusPlus20))) { 1075 // C++ [temp.names]p3: 1076 // After name lookup (3.4) finds that a name is a template-name or that 1077 // an operator-function-id or a literal- operator-id refers to a set of 1078 // overloaded functions any member of which is a function template if 1079 // this is followed by a <, the < is always taken as the delimiter of a 1080 // template-argument-list and never as the less-than operator. 1081 // C++2a [temp.names]p2: 1082 // A name is also considered to refer to a template if it is an 1083 // unqualified-id followed by a < and name lookup finds either one 1084 // or more functions or finds nothing. 1085 if (!IsFilteredTemplateName) 1086 FilterAcceptableTemplateNames(Result); 1087 1088 bool IsFunctionTemplate; 1089 bool IsVarTemplate; 1090 TemplateName Template; 1091 if (Result.end() - Result.begin() > 1) { 1092 IsFunctionTemplate = true; 1093 Template = Context.getOverloadedTemplateName(Result.begin(), 1094 Result.end()); 1095 } else if (!Result.empty()) { 1096 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1097 *Result.begin(), /*AllowFunctionTemplates=*/true, 1098 /*AllowDependent=*/false)); 1099 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1100 IsVarTemplate = isa<VarTemplateDecl>(TD); 1101 1102 if (SS.isNotEmpty()) 1103 Template = 1104 Context.getQualifiedTemplateName(SS.getScopeRep(), 1105 /*TemplateKeyword=*/false, TD); 1106 else 1107 Template = TemplateName(TD); 1108 } else { 1109 // All results were non-template functions. This is a function template 1110 // name. 1111 IsFunctionTemplate = true; 1112 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1113 } 1114 1115 if (IsFunctionTemplate) { 1116 // Function templates always go through overload resolution, at which 1117 // point we'll perform the various checks (e.g., accessibility) we need 1118 // to based on which function we selected. 1119 Result.suppressDiagnostics(); 1120 1121 return NameClassification::FunctionTemplate(Template); 1122 } 1123 1124 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1125 : NameClassification::TypeTemplate(Template); 1126 } 1127 1128 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1129 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1130 DiagnoseUseOfDecl(Type, NameLoc); 1131 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1132 QualType T = Context.getTypeDeclType(Type); 1133 if (SS.isNotEmpty()) 1134 return buildNestedType(*this, SS, T, NameLoc); 1135 return ParsedType::make(T); 1136 } 1137 1138 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1139 if (!Class) { 1140 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1141 if (ObjCCompatibleAliasDecl *Alias = 1142 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1143 Class = Alias->getClassInterface(); 1144 } 1145 1146 if (Class) { 1147 DiagnoseUseOfDecl(Class, NameLoc); 1148 1149 if (NextToken.is(tok::period)) { 1150 // Interface. <something> is parsed as a property reference expression. 1151 // Just return "unknown" as a fall-through for now. 1152 Result.suppressDiagnostics(); 1153 return NameClassification::Unknown(); 1154 } 1155 1156 QualType T = Context.getObjCInterfaceType(Class); 1157 return ParsedType::make(T); 1158 } 1159 1160 if (isa<ConceptDecl>(FirstDecl)) 1161 return NameClassification::Concept( 1162 TemplateName(cast<TemplateDecl>(FirstDecl))); 1163 1164 // We can have a type template here if we're classifying a template argument. 1165 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1166 !isa<VarTemplateDecl>(FirstDecl)) 1167 return NameClassification::TypeTemplate( 1168 TemplateName(cast<TemplateDecl>(FirstDecl))); 1169 1170 // Check for a tag type hidden by a non-type decl in a few cases where it 1171 // seems likely a type is wanted instead of the non-type that was found. 1172 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1173 if ((NextToken.is(tok::identifier) || 1174 (NextIsOp && 1175 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1176 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1177 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1178 DiagnoseUseOfDecl(Type, NameLoc); 1179 QualType T = Context.getTypeDeclType(Type); 1180 if (SS.isNotEmpty()) 1181 return buildNestedType(*this, SS, T, NameLoc); 1182 return ParsedType::make(T); 1183 } 1184 1185 // If we already know which single declaration is referenced, just annotate 1186 // that declaration directly. Defer resolving even non-overloaded class 1187 // member accesses, as we need to defer certain access checks until we know 1188 // the context. 1189 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1190 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1191 return NameClassification::NonType(Result.getRepresentativeDecl()); 1192 1193 // Otherwise, this is an overload set that we will need to resolve later. 1194 Result.suppressDiagnostics(); 1195 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1196 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1197 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1198 Result.begin(), Result.end())); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1239 // For an implicit class member access, transform the result into a member 1240 // access expression if necessary. 1241 auto *ULE = cast<UnresolvedLookupExpr>(E); 1242 if ((*ULE->decls_begin())->isCXXClassMember()) { 1243 CXXScopeSpec SS; 1244 SS.Adopt(ULE->getQualifierLoc()); 1245 1246 // Reconstruct the lookup result. 1247 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1248 LookupOrdinaryName); 1249 Result.setNamingClass(ULE->getNamingClass()); 1250 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1251 Result.addDecl(*I, I.getAccess()); 1252 Result.resolveKind(); 1253 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1254 nullptr, S); 1255 } 1256 1257 // Otherwise, this is already in the form we needed, and no further checks 1258 // are necessary. 1259 return ULE; 1260 } 1261 1262 Sema::TemplateNameKindForDiagnostics 1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1264 auto *TD = Name.getAsTemplateDecl(); 1265 if (!TD) 1266 return TemplateNameKindForDiagnostics::DependentTemplate; 1267 if (isa<ClassTemplateDecl>(TD)) 1268 return TemplateNameKindForDiagnostics::ClassTemplate; 1269 if (isa<FunctionTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::FunctionTemplate; 1271 if (isa<VarTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::VarTemplate; 1273 if (isa<TypeAliasTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::AliasTemplate; 1275 if (isa<TemplateTemplateParmDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1277 if (isa<ConceptDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::Concept; 1279 return TemplateNameKindForDiagnostics::DependentTemplate; 1280 } 1281 1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1283 assert(DC->getLexicalParent() == CurContext && 1284 "The next DeclContext should be lexically contained in the current one."); 1285 CurContext = DC; 1286 S->setEntity(DC); 1287 } 1288 1289 void Sema::PopDeclContext() { 1290 assert(CurContext && "DeclContext imbalance!"); 1291 1292 CurContext = CurContext->getLexicalParent(); 1293 assert(CurContext && "Popped translation unit!"); 1294 } 1295 1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1297 Decl *D) { 1298 // Unlike PushDeclContext, the context to which we return is not necessarily 1299 // the containing DC of TD, because the new context will be some pre-existing 1300 // TagDecl definition instead of a fresh one. 1301 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1302 CurContext = cast<TagDecl>(D)->getDefinition(); 1303 assert(CurContext && "skipping definition of undefined tag"); 1304 // Start lookups from the parent of the current context; we don't want to look 1305 // into the pre-existing complete definition. 1306 S->setEntity(CurContext->getLookupParent()); 1307 return Result; 1308 } 1309 1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1311 CurContext = static_cast<decltype(CurContext)>(Context); 1312 } 1313 1314 /// EnterDeclaratorContext - Used when we must lookup names in the context 1315 /// of a declarator's nested name specifier. 1316 /// 1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1318 // C++0x [basic.lookup.unqual]p13: 1319 // A name used in the definition of a static data member of class 1320 // X (after the qualified-id of the static member) is looked up as 1321 // if the name was used in a member function of X. 1322 // C++0x [basic.lookup.unqual]p14: 1323 // If a variable member of a namespace is defined outside of the 1324 // scope of its namespace then any name used in the definition of 1325 // the variable member (after the declarator-id) is looked up as 1326 // if the definition of the variable member occurred in its 1327 // namespace. 1328 // Both of these imply that we should push a scope whose context 1329 // is the semantic context of the declaration. We can't use 1330 // PushDeclContext here because that context is not necessarily 1331 // lexically contained in the current context. Fortunately, 1332 // the containing scope should have the appropriate information. 1333 1334 assert(!S->getEntity() && "scope already has entity"); 1335 1336 #ifndef NDEBUG 1337 Scope *Ancestor = S->getParent(); 1338 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1339 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1340 #endif 1341 1342 CurContext = DC; 1343 S->setEntity(DC); 1344 1345 if (S->getParent()->isTemplateParamScope()) { 1346 // Also set the corresponding entities for all immediately-enclosing 1347 // template parameter scopes. 1348 EnterTemplatedContext(S->getParent(), DC); 1349 } 1350 } 1351 1352 void Sema::ExitDeclaratorContext(Scope *S) { 1353 assert(S->getEntity() == CurContext && "Context imbalance!"); 1354 1355 // Switch back to the lexical context. The safety of this is 1356 // enforced by an assert in EnterDeclaratorContext. 1357 Scope *Ancestor = S->getParent(); 1358 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1359 CurContext = Ancestor->getEntity(); 1360 1361 // We don't need to do anything with the scope, which is going to 1362 // disappear. 1363 } 1364 1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1366 assert(S->isTemplateParamScope() && 1367 "expected to be initializing a template parameter scope"); 1368 1369 // C++20 [temp.local]p7: 1370 // In the definition of a member of a class template that appears outside 1371 // of the class template definition, the name of a member of the class 1372 // template hides the name of a template-parameter of any enclosing class 1373 // templates (but not a template-parameter of the member if the member is a 1374 // class or function template). 1375 // C++20 [temp.local]p9: 1376 // In the definition of a class template or in the definition of a member 1377 // of such a template that appears outside of the template definition, for 1378 // each non-dependent base class (13.8.2.1), if the name of the base class 1379 // or the name of a member of the base class is the same as the name of a 1380 // template-parameter, the base class name or member name hides the 1381 // template-parameter name (6.4.10). 1382 // 1383 // This means that a template parameter scope should be searched immediately 1384 // after searching the DeclContext for which it is a template parameter 1385 // scope. For example, for 1386 // template<typename T> template<typename U> template<typename V> 1387 // void N::A<T>::B<U>::f(...) 1388 // we search V then B<U> (and base classes) then U then A<T> (and base 1389 // classes) then T then N then ::. 1390 unsigned ScopeDepth = getTemplateDepth(S); 1391 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1392 DeclContext *SearchDCAfterScope = DC; 1393 for (; DC; DC = DC->getLookupParent()) { 1394 if (const TemplateParameterList *TPL = 1395 cast<Decl>(DC)->getDescribedTemplateParams()) { 1396 unsigned DCDepth = TPL->getDepth() + 1; 1397 if (DCDepth > ScopeDepth) 1398 continue; 1399 if (ScopeDepth == DCDepth) 1400 SearchDCAfterScope = DC = DC->getLookupParent(); 1401 break; 1402 } 1403 } 1404 S->setLookupEntity(SearchDCAfterScope); 1405 } 1406 } 1407 1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1409 // We assume that the caller has already called 1410 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1411 FunctionDecl *FD = D->getAsFunction(); 1412 if (!FD) 1413 return; 1414 1415 // Same implementation as PushDeclContext, but enters the context 1416 // from the lexical parent, rather than the top-level class. 1417 assert(CurContext == FD->getLexicalParent() && 1418 "The next DeclContext should be lexically contained in the current one."); 1419 CurContext = FD; 1420 S->setEntity(CurContext); 1421 1422 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1423 ParmVarDecl *Param = FD->getParamDecl(P); 1424 // If the parameter has an identifier, then add it to the scope 1425 if (Param->getIdentifier()) { 1426 S->AddDecl(Param); 1427 IdResolver.AddDecl(Param); 1428 } 1429 } 1430 } 1431 1432 void Sema::ActOnExitFunctionContext() { 1433 // Same implementation as PopDeclContext, but returns to the lexical parent, 1434 // rather than the top-level class. 1435 assert(CurContext && "DeclContext imbalance!"); 1436 CurContext = CurContext->getLexicalParent(); 1437 assert(CurContext && "Popped translation unit!"); 1438 } 1439 1440 /// Determine whether we allow overloading of the function 1441 /// PrevDecl with another declaration. 1442 /// 1443 /// This routine determines whether overloading is possible, not 1444 /// whether some new function is actually an overload. It will return 1445 /// true in C++ (where we can always provide overloads) or, as an 1446 /// extension, in C when the previous function is already an 1447 /// overloaded function declaration or has the "overloadable" 1448 /// attribute. 1449 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1450 ASTContext &Context, 1451 const FunctionDecl *New) { 1452 if (Context.getLangOpts().CPlusPlus) 1453 return true; 1454 1455 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1456 return true; 1457 1458 return Previous.getResultKind() == LookupResult::Found && 1459 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1460 New->hasAttr<OverloadableAttr>()); 1461 } 1462 1463 /// Add this decl to the scope shadowed decl chains. 1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1465 // Move up the scope chain until we find the nearest enclosing 1466 // non-transparent context. The declaration will be introduced into this 1467 // scope. 1468 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1469 S = S->getParent(); 1470 1471 // Add scoped declarations into their context, so that they can be 1472 // found later. Declarations without a context won't be inserted 1473 // into any context. 1474 if (AddToContext) 1475 CurContext->addDecl(D); 1476 1477 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1478 // are function-local declarations. 1479 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1480 return; 1481 1482 // Template instantiations should also not be pushed into scope. 1483 if (isa<FunctionDecl>(D) && 1484 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1485 return; 1486 1487 // If this replaces anything in the current scope, 1488 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1489 IEnd = IdResolver.end(); 1490 for (; I != IEnd; ++I) { 1491 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1492 S->RemoveDecl(*I); 1493 IdResolver.RemoveDecl(*I); 1494 1495 // Should only need to replace one decl. 1496 break; 1497 } 1498 } 1499 1500 S->AddDecl(D); 1501 1502 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1503 // Implicitly-generated labels may end up getting generated in an order that 1504 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1505 // the label at the appropriate place in the identifier chain. 1506 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1507 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1508 if (IDC == CurContext) { 1509 if (!S->isDeclScope(*I)) 1510 continue; 1511 } else if (IDC->Encloses(CurContext)) 1512 break; 1513 } 1514 1515 IdResolver.InsertDeclAfter(I, D); 1516 } else { 1517 IdResolver.AddDecl(D); 1518 } 1519 } 1520 1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1522 bool AllowInlineNamespace) { 1523 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1524 } 1525 1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1527 DeclContext *TargetDC = DC->getPrimaryContext(); 1528 do { 1529 if (DeclContext *ScopeDC = S->getEntity()) 1530 if (ScopeDC->getPrimaryContext() == TargetDC) 1531 return S; 1532 } while ((S = S->getParent())); 1533 1534 return nullptr; 1535 } 1536 1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1538 DeclContext*, 1539 ASTContext&); 1540 1541 /// Filters out lookup results that don't fall within the given scope 1542 /// as determined by isDeclInScope. 1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1544 bool ConsiderLinkage, 1545 bool AllowInlineNamespace) { 1546 LookupResult::Filter F = R.makeFilter(); 1547 while (F.hasNext()) { 1548 NamedDecl *D = F.next(); 1549 1550 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1551 continue; 1552 1553 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1554 continue; 1555 1556 F.erase(); 1557 } 1558 1559 F.done(); 1560 } 1561 1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1563 /// have compatible owning modules. 1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1565 // FIXME: The Modules TS is not clear about how friend declarations are 1566 // to be treated. It's not meaningful to have different owning modules for 1567 // linkage in redeclarations of the same entity, so for now allow the 1568 // redeclaration and change the owning modules to match. 1569 if (New->getFriendObjectKind() && 1570 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1571 New->setLocalOwningModule(Old->getOwningModule()); 1572 makeMergedDefinitionVisible(New); 1573 return false; 1574 } 1575 1576 Module *NewM = New->getOwningModule(); 1577 Module *OldM = Old->getOwningModule(); 1578 1579 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1580 NewM = NewM->Parent; 1581 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1582 OldM = OldM->Parent; 1583 1584 if (NewM == OldM) 1585 return false; 1586 1587 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1588 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1589 if (NewIsModuleInterface || OldIsModuleInterface) { 1590 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1591 // if a declaration of D [...] appears in the purview of a module, all 1592 // other such declarations shall appear in the purview of the same module 1593 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1594 << New 1595 << NewIsModuleInterface 1596 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1597 << OldIsModuleInterface 1598 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1599 Diag(Old->getLocation(), diag::note_previous_declaration); 1600 New->setInvalidDecl(); 1601 return true; 1602 } 1603 1604 return false; 1605 } 1606 1607 static bool isUsingDecl(NamedDecl *D) { 1608 return isa<UsingShadowDecl>(D) || 1609 isa<UnresolvedUsingTypenameDecl>(D) || 1610 isa<UnresolvedUsingValueDecl>(D); 1611 } 1612 1613 /// Removes using shadow declarations from the lookup results. 1614 static void RemoveUsingDecls(LookupResult &R) { 1615 LookupResult::Filter F = R.makeFilter(); 1616 while (F.hasNext()) 1617 if (isUsingDecl(F.next())) 1618 F.erase(); 1619 1620 F.done(); 1621 } 1622 1623 /// Check for this common pattern: 1624 /// @code 1625 /// class S { 1626 /// S(const S&); // DO NOT IMPLEMENT 1627 /// void operator=(const S&); // DO NOT IMPLEMENT 1628 /// }; 1629 /// @endcode 1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1631 // FIXME: Should check for private access too but access is set after we get 1632 // the decl here. 1633 if (D->doesThisDeclarationHaveABody()) 1634 return false; 1635 1636 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1637 return CD->isCopyConstructor(); 1638 return D->isCopyAssignmentOperator(); 1639 } 1640 1641 // We need this to handle 1642 // 1643 // typedef struct { 1644 // void *foo() { return 0; } 1645 // } A; 1646 // 1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1648 // for example. If 'A', foo will have external linkage. If we have '*A', 1649 // foo will have no linkage. Since we can't know until we get to the end 1650 // of the typedef, this function finds out if D might have non-external linkage. 1651 // Callers should verify at the end of the TU if it D has external linkage or 1652 // not. 1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1654 const DeclContext *DC = D->getDeclContext(); 1655 while (!DC->isTranslationUnit()) { 1656 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1657 if (!RD->hasNameForLinkage()) 1658 return true; 1659 } 1660 DC = DC->getParent(); 1661 } 1662 1663 return !D->isExternallyVisible(); 1664 } 1665 1666 // FIXME: This needs to be refactored; some other isInMainFile users want 1667 // these semantics. 1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1669 if (S.TUKind != TU_Complete) 1670 return false; 1671 return S.SourceMgr.isInMainFile(Loc); 1672 } 1673 1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1675 assert(D); 1676 1677 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1678 return false; 1679 1680 // Ignore all entities declared within templates, and out-of-line definitions 1681 // of members of class templates. 1682 if (D->getDeclContext()->isDependentContext() || 1683 D->getLexicalDeclContext()->isDependentContext()) 1684 return false; 1685 1686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1687 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 // A non-out-of-line declaration of a member specialization was implicitly 1690 // instantiated; it's the out-of-line declaration that we're interested in. 1691 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1693 return false; 1694 1695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1696 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1697 return false; 1698 } else { 1699 // 'static inline' functions are defined in headers; don't warn. 1700 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1701 return false; 1702 } 1703 1704 if (FD->doesThisDeclarationHaveABody() && 1705 Context.DeclMustBeEmitted(FD)) 1706 return false; 1707 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1708 // Constants and utility variables are defined in headers with internal 1709 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1710 // like "inline".) 1711 if (!isMainFileLoc(*this, VD->getLocation())) 1712 return false; 1713 1714 if (Context.DeclMustBeEmitted(VD)) 1715 return false; 1716 1717 if (VD->isStaticDataMember() && 1718 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1719 return false; 1720 if (VD->isStaticDataMember() && 1721 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1722 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1723 return false; 1724 1725 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1726 return false; 1727 } else { 1728 return false; 1729 } 1730 1731 // Only warn for unused decls internal to the translation unit. 1732 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1733 // for inline functions defined in the main source file, for instance. 1734 return mightHaveNonExternalLinkage(D); 1735 } 1736 1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1738 if (!D) 1739 return; 1740 1741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1742 const FunctionDecl *First = FD->getFirstDecl(); 1743 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1744 return; // First should already be in the vector. 1745 } 1746 1747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1748 const VarDecl *First = VD->getFirstDecl(); 1749 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1750 return; // First should already be in the vector. 1751 } 1752 1753 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1754 UnusedFileScopedDecls.push_back(D); 1755 } 1756 1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1758 if (D->isInvalidDecl()) 1759 return false; 1760 1761 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1762 // For a decomposition declaration, warn if none of the bindings are 1763 // referenced, instead of if the variable itself is referenced (which 1764 // it is, by the bindings' expressions). 1765 for (auto *BD : DD->bindings()) 1766 if (BD->isReferenced()) 1767 return false; 1768 } else if (!D->getDeclName()) { 1769 return false; 1770 } else if (D->isReferenced() || D->isUsed()) { 1771 return false; 1772 } 1773 1774 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1775 return false; 1776 1777 if (isa<LabelDecl>(D)) 1778 return true; 1779 1780 // Except for labels, we only care about unused decls that are local to 1781 // functions. 1782 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1783 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1784 // For dependent types, the diagnostic is deferred. 1785 WithinFunction = 1786 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1787 if (!WithinFunction) 1788 return false; 1789 1790 if (isa<TypedefNameDecl>(D)) 1791 return true; 1792 1793 // White-list anything that isn't a local variable. 1794 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1795 return false; 1796 1797 // Types of valid local variables should be complete, so this should succeed. 1798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1799 1800 // White-list anything with an __attribute__((unused)) type. 1801 const auto *Ty = VD->getType().getTypePtr(); 1802 1803 // Only look at the outermost level of typedef. 1804 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1805 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1806 return false; 1807 } 1808 1809 // If we failed to complete the type for some reason, or if the type is 1810 // dependent, don't diagnose the variable. 1811 if (Ty->isIncompleteType() || Ty->isDependentType()) 1812 return false; 1813 1814 // Look at the element type to ensure that the warning behaviour is 1815 // consistent for both scalars and arrays. 1816 Ty = Ty->getBaseElementTypeUnsafe(); 1817 1818 if (const TagType *TT = Ty->getAs<TagType>()) { 1819 const TagDecl *Tag = TT->getDecl(); 1820 if (Tag->hasAttr<UnusedAttr>()) 1821 return false; 1822 1823 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1824 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1825 return false; 1826 1827 if (const Expr *Init = VD->getInit()) { 1828 if (const ExprWithCleanups *Cleanups = 1829 dyn_cast<ExprWithCleanups>(Init)) 1830 Init = Cleanups->getSubExpr(); 1831 const CXXConstructExpr *Construct = 1832 dyn_cast<CXXConstructExpr>(Init); 1833 if (Construct && !Construct->isElidable()) { 1834 CXXConstructorDecl *CD = Construct->getConstructor(); 1835 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1836 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1837 return false; 1838 } 1839 1840 // Suppress the warning if we don't know how this is constructed, and 1841 // it could possibly be non-trivial constructor. 1842 if (Init->isTypeDependent()) 1843 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1844 if (!Ctor->isTrivial()) 1845 return false; 1846 } 1847 } 1848 } 1849 1850 // TODO: __attribute__((unused)) templates? 1851 } 1852 1853 return true; 1854 } 1855 1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1857 FixItHint &Hint) { 1858 if (isa<LabelDecl>(D)) { 1859 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1860 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1861 true); 1862 if (AfterColon.isInvalid()) 1863 return; 1864 Hint = FixItHint::CreateRemoval( 1865 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1866 } 1867 } 1868 1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1870 if (D->getTypeForDecl()->isDependentType()) 1871 return; 1872 1873 for (auto *TmpD : D->decls()) { 1874 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1875 DiagnoseUnusedDecl(T); 1876 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1877 DiagnoseUnusedNestedTypedefs(R); 1878 } 1879 } 1880 1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1882 /// unless they are marked attr(unused). 1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1884 if (!ShouldDiagnoseUnusedDecl(D)) 1885 return; 1886 1887 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1888 // typedefs can be referenced later on, so the diagnostics are emitted 1889 // at end-of-translation-unit. 1890 UnusedLocalTypedefNameCandidates.insert(TD); 1891 return; 1892 } 1893 1894 FixItHint Hint; 1895 GenerateFixForUnusedDecl(D, Context, Hint); 1896 1897 unsigned DiagID; 1898 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1899 DiagID = diag::warn_unused_exception_param; 1900 else if (isa<LabelDecl>(D)) 1901 DiagID = diag::warn_unused_label; 1902 else 1903 DiagID = diag::warn_unused_variable; 1904 1905 Diag(D->getLocation(), DiagID) << D << Hint; 1906 } 1907 1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1909 // Verify that we have no forward references left. If so, there was a goto 1910 // or address of a label taken, but no definition of it. Label fwd 1911 // definitions are indicated with a null substmt which is also not a resolved 1912 // MS inline assembly label name. 1913 bool Diagnose = false; 1914 if (L->isMSAsmLabel()) 1915 Diagnose = !L->isResolvedMSAsmLabel(); 1916 else 1917 Diagnose = L->getStmt() == nullptr; 1918 if (Diagnose) 1919 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1920 } 1921 1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1923 S->mergeNRVOIntoParent(); 1924 1925 if (S->decl_empty()) return; 1926 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1927 "Scope shouldn't contain decls!"); 1928 1929 for (auto *TmpD : S->decls()) { 1930 assert(TmpD && "This decl didn't get pushed??"); 1931 1932 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1933 NamedDecl *D = cast<NamedDecl>(TmpD); 1934 1935 // Diagnose unused variables in this scope. 1936 if (!S->hasUnrecoverableErrorOccurred()) { 1937 DiagnoseUnusedDecl(D); 1938 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1939 DiagnoseUnusedNestedTypedefs(RD); 1940 } 1941 1942 if (!D->getDeclName()) continue; 1943 1944 // If this was a forward reference to a label, verify it was defined. 1945 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1946 CheckPoppedLabel(LD, *this); 1947 1948 // Remove this name from our lexical scope, and warn on it if we haven't 1949 // already. 1950 IdResolver.RemoveDecl(D); 1951 auto ShadowI = ShadowingDecls.find(D); 1952 if (ShadowI != ShadowingDecls.end()) { 1953 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1954 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1955 << D << FD << FD->getParent(); 1956 Diag(FD->getLocation(), diag::note_previous_declaration); 1957 } 1958 ShadowingDecls.erase(ShadowI); 1959 } 1960 } 1961 } 1962 1963 /// Look for an Objective-C class in the translation unit. 1964 /// 1965 /// \param Id The name of the Objective-C class we're looking for. If 1966 /// typo-correction fixes this name, the Id will be updated 1967 /// to the fixed name. 1968 /// 1969 /// \param IdLoc The location of the name in the translation unit. 1970 /// 1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1972 /// if there is no class with the given name. 1973 /// 1974 /// \returns The declaration of the named Objective-C class, or NULL if the 1975 /// class could not be found. 1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1977 SourceLocation IdLoc, 1978 bool DoTypoCorrection) { 1979 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1980 // creation from this context. 1981 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1982 1983 if (!IDecl && DoTypoCorrection) { 1984 // Perform typo correction at the given location, but only if we 1985 // find an Objective-C class name. 1986 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1987 if (TypoCorrection C = 1988 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1989 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1990 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1991 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1992 Id = IDecl->getIdentifier(); 1993 } 1994 } 1995 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1996 // This routine must always return a class definition, if any. 1997 if (Def && Def->getDefinition()) 1998 Def = Def->getDefinition(); 1999 return Def; 2000 } 2001 2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2003 /// from S, where a non-field would be declared. This routine copes 2004 /// with the difference between C and C++ scoping rules in structs and 2005 /// unions. For example, the following code is well-formed in C but 2006 /// ill-formed in C++: 2007 /// @code 2008 /// struct S6 { 2009 /// enum { BAR } e; 2010 /// }; 2011 /// 2012 /// void test_S6() { 2013 /// struct S6 a; 2014 /// a.e = BAR; 2015 /// } 2016 /// @endcode 2017 /// For the declaration of BAR, this routine will return a different 2018 /// scope. The scope S will be the scope of the unnamed enumeration 2019 /// within S6. In C++, this routine will return the scope associated 2020 /// with S6, because the enumeration's scope is a transparent 2021 /// context but structures can contain non-field names. In C, this 2022 /// routine will return the translation unit scope, since the 2023 /// enumeration's scope is a transparent context and structures cannot 2024 /// contain non-field names. 2025 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2026 while (((S->getFlags() & Scope::DeclScope) == 0) || 2027 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2028 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2029 S = S->getParent(); 2030 return S; 2031 } 2032 2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2034 ASTContext::GetBuiltinTypeError Error) { 2035 switch (Error) { 2036 case ASTContext::GE_None: 2037 return ""; 2038 case ASTContext::GE_Missing_type: 2039 return BuiltinInfo.getHeaderName(ID); 2040 case ASTContext::GE_Missing_stdio: 2041 return "stdio.h"; 2042 case ASTContext::GE_Missing_setjmp: 2043 return "setjmp.h"; 2044 case ASTContext::GE_Missing_ucontext: 2045 return "ucontext.h"; 2046 } 2047 llvm_unreachable("unhandled error kind"); 2048 } 2049 2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2051 unsigned ID, SourceLocation Loc) { 2052 DeclContext *Parent = Context.getTranslationUnitDecl(); 2053 2054 if (getLangOpts().CPlusPlus) { 2055 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2056 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2057 CLinkageDecl->setImplicit(); 2058 Parent->addDecl(CLinkageDecl); 2059 Parent = CLinkageDecl; 2060 } 2061 2062 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2063 /*TInfo=*/nullptr, SC_Extern, false, 2064 Type->isFunctionProtoType()); 2065 New->setImplicit(); 2066 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2067 2068 // Create Decl objects for each parameter, adding them to the 2069 // FunctionDecl. 2070 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2071 SmallVector<ParmVarDecl *, 16> Params; 2072 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2073 ParmVarDecl *parm = ParmVarDecl::Create( 2074 Context, New, SourceLocation(), SourceLocation(), nullptr, 2075 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2076 parm->setScopeInfo(0, i); 2077 Params.push_back(parm); 2078 } 2079 New->setParams(Params); 2080 } 2081 2082 AddKnownFunctionAttributes(New); 2083 return New; 2084 } 2085 2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2087 /// file scope. lazily create a decl for it. ForRedeclaration is true 2088 /// if we're creating this built-in in anticipation of redeclaring the 2089 /// built-in. 2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2091 Scope *S, bool ForRedeclaration, 2092 SourceLocation Loc) { 2093 LookupNecessaryTypesForBuiltin(S, ID); 2094 2095 ASTContext::GetBuiltinTypeError Error; 2096 QualType R = Context.GetBuiltinType(ID, Error); 2097 if (Error) { 2098 if (!ForRedeclaration) 2099 return nullptr; 2100 2101 // If we have a builtin without an associated type we should not emit a 2102 // warning when we were not able to find a type for it. 2103 if (Error == ASTContext::GE_Missing_type || 2104 Context.BuiltinInfo.allowTypeMismatch(ID)) 2105 return nullptr; 2106 2107 // If we could not find a type for setjmp it is because the jmp_buf type was 2108 // not defined prior to the setjmp declaration. 2109 if (Error == ASTContext::GE_Missing_setjmp) { 2110 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2111 << Context.BuiltinInfo.getName(ID); 2112 return nullptr; 2113 } 2114 2115 // Generally, we emit a warning that the declaration requires the 2116 // appropriate header. 2117 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2118 << getHeaderName(Context.BuiltinInfo, ID, Error) 2119 << Context.BuiltinInfo.getName(ID); 2120 return nullptr; 2121 } 2122 2123 if (!ForRedeclaration && 2124 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2125 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2126 Diag(Loc, diag::ext_implicit_lib_function_decl) 2127 << Context.BuiltinInfo.getName(ID) << R; 2128 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2129 Diag(Loc, diag::note_include_header_or_declare) 2130 << Header << Context.BuiltinInfo.getName(ID); 2131 } 2132 2133 if (R.isNull()) 2134 return nullptr; 2135 2136 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2137 RegisterLocallyScopedExternCDecl(New, S); 2138 2139 // TUScope is the translation-unit scope to insert this function into. 2140 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2141 // relate Scopes to DeclContexts, and probably eliminate CurContext 2142 // entirely, but we're not there yet. 2143 DeclContext *SavedContext = CurContext; 2144 CurContext = New->getDeclContext(); 2145 PushOnScopeChains(New, TUScope); 2146 CurContext = SavedContext; 2147 return New; 2148 } 2149 2150 /// Typedef declarations don't have linkage, but they still denote the same 2151 /// entity if their types are the same. 2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2153 /// isSameEntity. 2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2155 TypedefNameDecl *Decl, 2156 LookupResult &Previous) { 2157 // This is only interesting when modules are enabled. 2158 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2159 return; 2160 2161 // Empty sets are uninteresting. 2162 if (Previous.empty()) 2163 return; 2164 2165 LookupResult::Filter Filter = Previous.makeFilter(); 2166 while (Filter.hasNext()) { 2167 NamedDecl *Old = Filter.next(); 2168 2169 // Non-hidden declarations are never ignored. 2170 if (S.isVisible(Old)) 2171 continue; 2172 2173 // Declarations of the same entity are not ignored, even if they have 2174 // different linkages. 2175 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2176 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2177 Decl->getUnderlyingType())) 2178 continue; 2179 2180 // If both declarations give a tag declaration a typedef name for linkage 2181 // purposes, then they declare the same entity. 2182 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2183 Decl->getAnonDeclWithTypedefName()) 2184 continue; 2185 } 2186 2187 Filter.erase(); 2188 } 2189 2190 Filter.done(); 2191 } 2192 2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2194 QualType OldType; 2195 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2196 OldType = OldTypedef->getUnderlyingType(); 2197 else 2198 OldType = Context.getTypeDeclType(Old); 2199 QualType NewType = New->getUnderlyingType(); 2200 2201 if (NewType->isVariablyModifiedType()) { 2202 // Must not redefine a typedef with a variably-modified type. 2203 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2204 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2205 << Kind << NewType; 2206 if (Old->getLocation().isValid()) 2207 notePreviousDefinition(Old, New->getLocation()); 2208 New->setInvalidDecl(); 2209 return true; 2210 } 2211 2212 if (OldType != NewType && 2213 !OldType->isDependentType() && 2214 !NewType->isDependentType() && 2215 !Context.hasSameType(OldType, NewType)) { 2216 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2217 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2218 << Kind << NewType << OldType; 2219 if (Old->getLocation().isValid()) 2220 notePreviousDefinition(Old, New->getLocation()); 2221 New->setInvalidDecl(); 2222 return true; 2223 } 2224 return false; 2225 } 2226 2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2228 /// same name and scope as a previous declaration 'Old'. Figure out 2229 /// how to resolve this situation, merging decls or emitting 2230 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2231 /// 2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2233 LookupResult &OldDecls) { 2234 // If the new decl is known invalid already, don't bother doing any 2235 // merging checks. 2236 if (New->isInvalidDecl()) return; 2237 2238 // Allow multiple definitions for ObjC built-in typedefs. 2239 // FIXME: Verify the underlying types are equivalent! 2240 if (getLangOpts().ObjC) { 2241 const IdentifierInfo *TypeID = New->getIdentifier(); 2242 switch (TypeID->getLength()) { 2243 default: break; 2244 case 2: 2245 { 2246 if (!TypeID->isStr("id")) 2247 break; 2248 QualType T = New->getUnderlyingType(); 2249 if (!T->isPointerType()) 2250 break; 2251 if (!T->isVoidPointerType()) { 2252 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2253 if (!PT->isStructureType()) 2254 break; 2255 } 2256 Context.setObjCIdRedefinitionType(T); 2257 // Install the built-in type for 'id', ignoring the current definition. 2258 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2259 return; 2260 } 2261 case 5: 2262 if (!TypeID->isStr("Class")) 2263 break; 2264 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2265 // Install the built-in type for 'Class', ignoring the current definition. 2266 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2267 return; 2268 case 3: 2269 if (!TypeID->isStr("SEL")) 2270 break; 2271 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2272 // Install the built-in type for 'SEL', ignoring the current definition. 2273 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2274 return; 2275 } 2276 // Fall through - the typedef name was not a builtin type. 2277 } 2278 2279 // Verify the old decl was also a type. 2280 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2281 if (!Old) { 2282 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2283 << New->getDeclName(); 2284 2285 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2286 if (OldD->getLocation().isValid()) 2287 notePreviousDefinition(OldD, New->getLocation()); 2288 2289 return New->setInvalidDecl(); 2290 } 2291 2292 // If the old declaration is invalid, just give up here. 2293 if (Old->isInvalidDecl()) 2294 return New->setInvalidDecl(); 2295 2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2297 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2298 auto *NewTag = New->getAnonDeclWithTypedefName(); 2299 NamedDecl *Hidden = nullptr; 2300 if (OldTag && NewTag && 2301 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2302 !hasVisibleDefinition(OldTag, &Hidden)) { 2303 // There is a definition of this tag, but it is not visible. Use it 2304 // instead of our tag. 2305 New->setTypeForDecl(OldTD->getTypeForDecl()); 2306 if (OldTD->isModed()) 2307 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2308 OldTD->getUnderlyingType()); 2309 else 2310 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2311 2312 // Make the old tag definition visible. 2313 makeMergedDefinitionVisible(Hidden); 2314 2315 // If this was an unscoped enumeration, yank all of its enumerators 2316 // out of the scope. 2317 if (isa<EnumDecl>(NewTag)) { 2318 Scope *EnumScope = getNonFieldDeclScope(S); 2319 for (auto *D : NewTag->decls()) { 2320 auto *ED = cast<EnumConstantDecl>(D); 2321 assert(EnumScope->isDeclScope(ED)); 2322 EnumScope->RemoveDecl(ED); 2323 IdResolver.RemoveDecl(ED); 2324 ED->getLexicalDeclContext()->removeDecl(ED); 2325 } 2326 } 2327 } 2328 } 2329 2330 // If the typedef types are not identical, reject them in all languages and 2331 // with any extensions enabled. 2332 if (isIncompatibleTypedef(Old, New)) 2333 return; 2334 2335 // The types match. Link up the redeclaration chain and merge attributes if 2336 // the old declaration was a typedef. 2337 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2338 New->setPreviousDecl(Typedef); 2339 mergeDeclAttributes(New, Old); 2340 } 2341 2342 if (getLangOpts().MicrosoftExt) 2343 return; 2344 2345 if (getLangOpts().CPlusPlus) { 2346 // C++ [dcl.typedef]p2: 2347 // In a given non-class scope, a typedef specifier can be used to 2348 // redefine the name of any type declared in that scope to refer 2349 // to the type to which it already refers. 2350 if (!isa<CXXRecordDecl>(CurContext)) 2351 return; 2352 2353 // C++0x [dcl.typedef]p4: 2354 // In a given class scope, a typedef specifier can be used to redefine 2355 // any class-name declared in that scope that is not also a typedef-name 2356 // to refer to the type to which it already refers. 2357 // 2358 // This wording came in via DR424, which was a correction to the 2359 // wording in DR56, which accidentally banned code like: 2360 // 2361 // struct S { 2362 // typedef struct A { } A; 2363 // }; 2364 // 2365 // in the C++03 standard. We implement the C++0x semantics, which 2366 // allow the above but disallow 2367 // 2368 // struct S { 2369 // typedef int I; 2370 // typedef int I; 2371 // }; 2372 // 2373 // since that was the intent of DR56. 2374 if (!isa<TypedefNameDecl>(Old)) 2375 return; 2376 2377 Diag(New->getLocation(), diag::err_redefinition) 2378 << New->getDeclName(); 2379 notePreviousDefinition(Old, New->getLocation()); 2380 return New->setInvalidDecl(); 2381 } 2382 2383 // Modules always permit redefinition of typedefs, as does C11. 2384 if (getLangOpts().Modules || getLangOpts().C11) 2385 return; 2386 2387 // If we have a redefinition of a typedef in C, emit a warning. This warning 2388 // is normally mapped to an error, but can be controlled with 2389 // -Wtypedef-redefinition. If either the original or the redefinition is 2390 // in a system header, don't emit this for compatibility with GCC. 2391 if (getDiagnostics().getSuppressSystemWarnings() && 2392 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2393 (Old->isImplicit() || 2394 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2395 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2396 return; 2397 2398 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2399 << New->getDeclName(); 2400 notePreviousDefinition(Old, New->getLocation()); 2401 } 2402 2403 /// DeclhasAttr - returns true if decl Declaration already has the target 2404 /// attribute. 2405 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2406 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2407 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2408 for (const auto *i : D->attrs()) 2409 if (i->getKind() == A->getKind()) { 2410 if (Ann) { 2411 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2412 return true; 2413 continue; 2414 } 2415 // FIXME: Don't hardcode this check 2416 if (OA && isa<OwnershipAttr>(i)) 2417 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2418 return true; 2419 } 2420 2421 return false; 2422 } 2423 2424 static bool isAttributeTargetADefinition(Decl *D) { 2425 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2426 return VD->isThisDeclarationADefinition(); 2427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2428 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2429 return true; 2430 } 2431 2432 /// Merge alignment attributes from \p Old to \p New, taking into account the 2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2434 /// 2435 /// \return \c true if any attributes were added to \p New. 2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2437 // Look for alignas attributes on Old, and pick out whichever attribute 2438 // specifies the strictest alignment requirement. 2439 AlignedAttr *OldAlignasAttr = nullptr; 2440 AlignedAttr *OldStrictestAlignAttr = nullptr; 2441 unsigned OldAlign = 0; 2442 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2443 // FIXME: We have no way of representing inherited dependent alignments 2444 // in a case like: 2445 // template<int A, int B> struct alignas(A) X; 2446 // template<int A, int B> struct alignas(B) X {}; 2447 // For now, we just ignore any alignas attributes which are not on the 2448 // definition in such a case. 2449 if (I->isAlignmentDependent()) 2450 return false; 2451 2452 if (I->isAlignas()) 2453 OldAlignasAttr = I; 2454 2455 unsigned Align = I->getAlignment(S.Context); 2456 if (Align > OldAlign) { 2457 OldAlign = Align; 2458 OldStrictestAlignAttr = I; 2459 } 2460 } 2461 2462 // Look for alignas attributes on New. 2463 AlignedAttr *NewAlignasAttr = nullptr; 2464 unsigned NewAlign = 0; 2465 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2466 if (I->isAlignmentDependent()) 2467 return false; 2468 2469 if (I->isAlignas()) 2470 NewAlignasAttr = I; 2471 2472 unsigned Align = I->getAlignment(S.Context); 2473 if (Align > NewAlign) 2474 NewAlign = Align; 2475 } 2476 2477 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2478 // Both declarations have 'alignas' attributes. We require them to match. 2479 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2480 // fall short. (If two declarations both have alignas, they must both match 2481 // every definition, and so must match each other if there is a definition.) 2482 2483 // If either declaration only contains 'alignas(0)' specifiers, then it 2484 // specifies the natural alignment for the type. 2485 if (OldAlign == 0 || NewAlign == 0) { 2486 QualType Ty; 2487 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2488 Ty = VD->getType(); 2489 else 2490 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2491 2492 if (OldAlign == 0) 2493 OldAlign = S.Context.getTypeAlign(Ty); 2494 if (NewAlign == 0) 2495 NewAlign = S.Context.getTypeAlign(Ty); 2496 } 2497 2498 if (OldAlign != NewAlign) { 2499 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2500 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2501 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2502 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2503 } 2504 } 2505 2506 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2507 // C++11 [dcl.align]p6: 2508 // if any declaration of an entity has an alignment-specifier, 2509 // every defining declaration of that entity shall specify an 2510 // equivalent alignment. 2511 // C11 6.7.5/7: 2512 // If the definition of an object does not have an alignment 2513 // specifier, any other declaration of that object shall also 2514 // have no alignment specifier. 2515 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2516 << OldAlignasAttr; 2517 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2518 << OldAlignasAttr; 2519 } 2520 2521 bool AnyAdded = false; 2522 2523 // Ensure we have an attribute representing the strictest alignment. 2524 if (OldAlign > NewAlign) { 2525 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 // Ensure we have an alignas attribute if the old declaration had one. 2532 if (OldAlignasAttr && !NewAlignasAttr && 2533 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2534 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2535 Clone->setInherited(true); 2536 New->addAttr(Clone); 2537 AnyAdded = true; 2538 } 2539 2540 return AnyAdded; 2541 } 2542 2543 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2544 const InheritableAttr *Attr, 2545 Sema::AvailabilityMergeKind AMK) { 2546 // This function copies an attribute Attr from a previous declaration to the 2547 // new declaration D if the new declaration doesn't itself have that attribute 2548 // yet or if that attribute allows duplicates. 2549 // If you're adding a new attribute that requires logic different from 2550 // "use explicit attribute on decl if present, else use attribute from 2551 // previous decl", for example if the attribute needs to be consistent 2552 // between redeclarations, you need to call a custom merge function here. 2553 InheritableAttr *NewAttr = nullptr; 2554 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2555 NewAttr = S.mergeAvailabilityAttr( 2556 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2557 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2558 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2559 AA->getPriority()); 2560 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2561 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2562 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2563 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2565 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2566 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2567 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2568 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2569 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2570 FA->getFirstArg()); 2571 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2572 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2573 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2574 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2575 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2576 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2577 IA->getInheritanceModel()); 2578 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2579 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2580 &S.Context.Idents.get(AA->getSpelling())); 2581 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2582 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2583 isa<CUDAGlobalAttr>(Attr))) { 2584 // CUDA target attributes are part of function signature for 2585 // overloading purposes and must not be merged. 2586 return false; 2587 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2588 NewAttr = S.mergeMinSizeAttr(D, *MA); 2589 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2590 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2591 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2592 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2593 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2594 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2595 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2596 NewAttr = S.mergeCommonAttr(D, *CommonA); 2597 else if (isa<AlignedAttr>(Attr)) 2598 // AlignedAttrs are handled separately, because we need to handle all 2599 // such attributes on a declaration at the same time. 2600 NewAttr = nullptr; 2601 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2602 (AMK == Sema::AMK_Override || 2603 AMK == Sema::AMK_ProtocolImplementation)) 2604 NewAttr = nullptr; 2605 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2606 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2607 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2608 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2609 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2612 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2613 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2614 NewAttr = S.mergeImportNameAttr(D, *INA); 2615 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2616 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2617 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2618 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2619 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2620 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2621 2622 if (NewAttr) { 2623 NewAttr->setInherited(true); 2624 D->addAttr(NewAttr); 2625 if (isa<MSInheritanceAttr>(NewAttr)) 2626 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2627 return true; 2628 } 2629 2630 return false; 2631 } 2632 2633 static const NamedDecl *getDefinition(const Decl *D) { 2634 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2635 return TD->getDefinition(); 2636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2637 const VarDecl *Def = VD->getDefinition(); 2638 if (Def) 2639 return Def; 2640 return VD->getActingDefinition(); 2641 } 2642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2643 const FunctionDecl *Def = nullptr; 2644 if (FD->isDefined(Def, true)) 2645 return Def; 2646 } 2647 return nullptr; 2648 } 2649 2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2651 for (const auto *Attribute : D->attrs()) 2652 if (Attribute->getKind() == Kind) 2653 return true; 2654 return false; 2655 } 2656 2657 /// checkNewAttributesAfterDef - If we already have a definition, check that 2658 /// there are no new attributes in this declaration. 2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2660 if (!New->hasAttrs()) 2661 return; 2662 2663 const NamedDecl *Def = getDefinition(Old); 2664 if (!Def || Def == New) 2665 return; 2666 2667 AttrVec &NewAttributes = New->getAttrs(); 2668 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2669 const Attr *NewAttribute = NewAttributes[I]; 2670 2671 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2673 Sema::SkipBodyInfo SkipBody; 2674 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2675 2676 // If we're skipping this definition, drop the "alias" attribute. 2677 if (SkipBody.ShouldSkip) { 2678 NewAttributes.erase(NewAttributes.begin() + I); 2679 --E; 2680 continue; 2681 } 2682 } else { 2683 VarDecl *VD = cast<VarDecl>(New); 2684 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2685 VarDecl::TentativeDefinition 2686 ? diag::err_alias_after_tentative 2687 : diag::err_redefinition; 2688 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2689 if (Diag == diag::err_redefinition) 2690 S.notePreviousDefinition(Def, VD->getLocation()); 2691 else 2692 S.Diag(Def->getLocation(), diag::note_previous_definition); 2693 VD->setInvalidDecl(); 2694 } 2695 ++I; 2696 continue; 2697 } 2698 2699 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2700 // Tentative definitions are only interesting for the alias check above. 2701 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2702 ++I; 2703 continue; 2704 } 2705 } 2706 2707 if (hasAttribute(Def, NewAttribute->getKind())) { 2708 ++I; 2709 continue; // regular attr merging will take care of validating this. 2710 } 2711 2712 if (isa<C11NoReturnAttr>(NewAttribute)) { 2713 // C's _Noreturn is allowed to be added to a function after it is defined. 2714 ++I; 2715 continue; 2716 } else if (isa<UuidAttr>(NewAttribute)) { 2717 // msvc will allow a subsequent definition to add an uuid to a class 2718 ++I; 2719 continue; 2720 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2721 if (AA->isAlignas()) { 2722 // C++11 [dcl.align]p6: 2723 // if any declaration of an entity has an alignment-specifier, 2724 // every defining declaration of that entity shall specify an 2725 // equivalent alignment. 2726 // C11 6.7.5/7: 2727 // If the definition of an object does not have an alignment 2728 // specifier, any other declaration of that object shall also 2729 // have no alignment specifier. 2730 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2731 << AA; 2732 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2733 << AA; 2734 NewAttributes.erase(NewAttributes.begin() + I); 2735 --E; 2736 continue; 2737 } 2738 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2739 // If there is a C definition followed by a redeclaration with this 2740 // attribute then there are two different definitions. In C++, prefer the 2741 // standard diagnostics. 2742 if (!S.getLangOpts().CPlusPlus) { 2743 S.Diag(NewAttribute->getLocation(), 2744 diag::err_loader_uninitialized_redeclaration); 2745 S.Diag(Def->getLocation(), diag::note_previous_definition); 2746 NewAttributes.erase(NewAttributes.begin() + I); 2747 --E; 2748 continue; 2749 } 2750 } else if (isa<SelectAnyAttr>(NewAttribute) && 2751 cast<VarDecl>(New)->isInline() && 2752 !cast<VarDecl>(New)->isInlineSpecified()) { 2753 // Don't warn about applying selectany to implicitly inline variables. 2754 // Older compilers and language modes would require the use of selectany 2755 // to make such variables inline, and it would have no effect if we 2756 // honored it. 2757 ++I; 2758 continue; 2759 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2760 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2761 // declarations after defintions. 2762 ++I; 2763 continue; 2764 } 2765 2766 S.Diag(NewAttribute->getLocation(), 2767 diag::warn_attribute_precede_definition); 2768 S.Diag(Def->getLocation(), diag::note_previous_definition); 2769 NewAttributes.erase(NewAttributes.begin() + I); 2770 --E; 2771 } 2772 } 2773 2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2775 const ConstInitAttr *CIAttr, 2776 bool AttrBeforeInit) { 2777 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2778 2779 // Figure out a good way to write this specifier on the old declaration. 2780 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2781 // enough of the attribute list spelling information to extract that without 2782 // heroics. 2783 std::string SuitableSpelling; 2784 if (S.getLangOpts().CPlusPlus20) 2785 SuitableSpelling = std::string( 2786 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2787 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2788 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2789 InsertLoc, {tok::l_square, tok::l_square, 2790 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2791 S.PP.getIdentifierInfo("require_constant_initialization"), 2792 tok::r_square, tok::r_square})); 2793 if (SuitableSpelling.empty()) 2794 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2795 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2796 S.PP.getIdentifierInfo("require_constant_initialization"), 2797 tok::r_paren, tok::r_paren})); 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2799 SuitableSpelling = "constinit"; 2800 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2801 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2802 if (SuitableSpelling.empty()) 2803 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2804 SuitableSpelling += " "; 2805 2806 if (AttrBeforeInit) { 2807 // extern constinit int a; 2808 // int a = 0; // error (missing 'constinit'), accepted as extension 2809 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2810 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2811 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2812 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2813 } else { 2814 // int a = 0; 2815 // constinit extern int a; // error (missing 'constinit') 2816 S.Diag(CIAttr->getLocation(), 2817 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2818 : diag::warn_require_const_init_added_too_late) 2819 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2820 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2821 << CIAttr->isConstinit() 2822 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2823 } 2824 } 2825 2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2828 AvailabilityMergeKind AMK) { 2829 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2830 UsedAttr *NewAttr = OldAttr->clone(Context); 2831 NewAttr->setInherited(true); 2832 New->addAttr(NewAttr); 2833 } 2834 2835 if (!Old->hasAttrs() && !New->hasAttrs()) 2836 return; 2837 2838 // [dcl.constinit]p1: 2839 // If the [constinit] specifier is applied to any declaration of a 2840 // variable, it shall be applied to the initializing declaration. 2841 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2842 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2843 if (bool(OldConstInit) != bool(NewConstInit)) { 2844 const auto *OldVD = cast<VarDecl>(Old); 2845 auto *NewVD = cast<VarDecl>(New); 2846 2847 // Find the initializing declaration. Note that we might not have linked 2848 // the new declaration into the redeclaration chain yet. 2849 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2850 if (!InitDecl && 2851 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2852 InitDecl = NewVD; 2853 2854 if (InitDecl == NewVD) { 2855 // This is the initializing declaration. If it would inherit 'constinit', 2856 // that's ill-formed. (Note that we do not apply this to the attribute 2857 // form). 2858 if (OldConstInit && OldConstInit->isConstinit()) 2859 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2860 /*AttrBeforeInit=*/true); 2861 } else if (NewConstInit) { 2862 // This is the first time we've been told that this declaration should 2863 // have a constant initializer. If we already saw the initializing 2864 // declaration, this is too late. 2865 if (InitDecl && InitDecl != NewVD) { 2866 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2867 /*AttrBeforeInit=*/false); 2868 NewVD->dropAttr<ConstInitAttr>(); 2869 } 2870 } 2871 } 2872 2873 // Attributes declared post-definition are currently ignored. 2874 checkNewAttributesAfterDef(*this, New, Old); 2875 2876 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2877 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2878 if (!OldA->isEquivalent(NewA)) { 2879 // This redeclaration changes __asm__ label. 2880 Diag(New->getLocation(), diag::err_different_asm_label); 2881 Diag(OldA->getLocation(), diag::note_previous_declaration); 2882 } 2883 } else if (Old->isUsed()) { 2884 // This redeclaration adds an __asm__ label to a declaration that has 2885 // already been ODR-used. 2886 Diag(New->getLocation(), diag::err_late_asm_label_name) 2887 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2888 } 2889 } 2890 2891 // Re-declaration cannot add abi_tag's. 2892 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2893 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2894 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2895 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2896 NewTag) == OldAbiTagAttr->tags_end()) { 2897 Diag(NewAbiTagAttr->getLocation(), 2898 diag::err_new_abi_tag_on_redeclaration) 2899 << NewTag; 2900 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2901 } 2902 } 2903 } else { 2904 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2905 Diag(Old->getLocation(), diag::note_previous_declaration); 2906 } 2907 } 2908 2909 // This redeclaration adds a section attribute. 2910 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2911 if (auto *VD = dyn_cast<VarDecl>(New)) { 2912 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2913 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2914 Diag(Old->getLocation(), diag::note_previous_declaration); 2915 } 2916 } 2917 } 2918 2919 // Redeclaration adds code-seg attribute. 2920 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2921 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2922 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2923 Diag(New->getLocation(), diag::warn_mismatched_section) 2924 << 0 /*codeseg*/; 2925 Diag(Old->getLocation(), diag::note_previous_declaration); 2926 } 2927 2928 if (!Old->hasAttrs()) 2929 return; 2930 2931 bool foundAny = New->hasAttrs(); 2932 2933 // Ensure that any moving of objects within the allocated map is done before 2934 // we process them. 2935 if (!foundAny) New->setAttrs(AttrVec()); 2936 2937 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2938 // Ignore deprecated/unavailable/availability attributes if requested. 2939 AvailabilityMergeKind LocalAMK = AMK_None; 2940 if (isa<DeprecatedAttr>(I) || 2941 isa<UnavailableAttr>(I) || 2942 isa<AvailabilityAttr>(I)) { 2943 switch (AMK) { 2944 case AMK_None: 2945 continue; 2946 2947 case AMK_Redeclaration: 2948 case AMK_Override: 2949 case AMK_ProtocolImplementation: 2950 LocalAMK = AMK; 2951 break; 2952 } 2953 } 2954 2955 // Already handled. 2956 if (isa<UsedAttr>(I)) 2957 continue; 2958 2959 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2960 foundAny = true; 2961 } 2962 2963 if (mergeAlignedAttrs(*this, New, Old)) 2964 foundAny = true; 2965 2966 if (!foundAny) New->dropAttrs(); 2967 } 2968 2969 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2970 /// to the new one. 2971 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2972 const ParmVarDecl *oldDecl, 2973 Sema &S) { 2974 // C++11 [dcl.attr.depend]p2: 2975 // The first declaration of a function shall specify the 2976 // carries_dependency attribute for its declarator-id if any declaration 2977 // of the function specifies the carries_dependency attribute. 2978 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2979 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2980 S.Diag(CDA->getLocation(), 2981 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2982 // Find the first declaration of the parameter. 2983 // FIXME: Should we build redeclaration chains for function parameters? 2984 const FunctionDecl *FirstFD = 2985 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2986 const ParmVarDecl *FirstVD = 2987 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2988 S.Diag(FirstVD->getLocation(), 2989 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2990 } 2991 2992 if (!oldDecl->hasAttrs()) 2993 return; 2994 2995 bool foundAny = newDecl->hasAttrs(); 2996 2997 // Ensure that any moving of objects within the allocated map is 2998 // done before we process them. 2999 if (!foundAny) newDecl->setAttrs(AttrVec()); 3000 3001 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3002 if (!DeclHasAttr(newDecl, I)) { 3003 InheritableAttr *newAttr = 3004 cast<InheritableParamAttr>(I->clone(S.Context)); 3005 newAttr->setInherited(true); 3006 newDecl->addAttr(newAttr); 3007 foundAny = true; 3008 } 3009 } 3010 3011 if (!foundAny) newDecl->dropAttrs(); 3012 } 3013 3014 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3015 const ParmVarDecl *OldParam, 3016 Sema &S) { 3017 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3018 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3019 if (*Oldnullability != *Newnullability) { 3020 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3021 << DiagNullabilityKind( 3022 *Newnullability, 3023 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3024 != 0)) 3025 << DiagNullabilityKind( 3026 *Oldnullability, 3027 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3028 != 0)); 3029 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3030 } 3031 } else { 3032 QualType NewT = NewParam->getType(); 3033 NewT = S.Context.getAttributedType( 3034 AttributedType::getNullabilityAttrKind(*Oldnullability), 3035 NewT, NewT); 3036 NewParam->setType(NewT); 3037 } 3038 } 3039 } 3040 3041 namespace { 3042 3043 /// Used in MergeFunctionDecl to keep track of function parameters in 3044 /// C. 3045 struct GNUCompatibleParamWarning { 3046 ParmVarDecl *OldParm; 3047 ParmVarDecl *NewParm; 3048 QualType PromotedType; 3049 }; 3050 3051 } // end anonymous namespace 3052 3053 // Determine whether the previous declaration was a definition, implicit 3054 // declaration, or a declaration. 3055 template <typename T> 3056 static std::pair<diag::kind, SourceLocation> 3057 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3058 diag::kind PrevDiag; 3059 SourceLocation OldLocation = Old->getLocation(); 3060 if (Old->isThisDeclarationADefinition()) 3061 PrevDiag = diag::note_previous_definition; 3062 else if (Old->isImplicit()) { 3063 PrevDiag = diag::note_previous_implicit_declaration; 3064 if (OldLocation.isInvalid()) 3065 OldLocation = New->getLocation(); 3066 } else 3067 PrevDiag = diag::note_previous_declaration; 3068 return std::make_pair(PrevDiag, OldLocation); 3069 } 3070 3071 /// canRedefineFunction - checks if a function can be redefined. Currently, 3072 /// only extern inline functions can be redefined, and even then only in 3073 /// GNU89 mode. 3074 static bool canRedefineFunction(const FunctionDecl *FD, 3075 const LangOptions& LangOpts) { 3076 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3077 !LangOpts.CPlusPlus && 3078 FD->isInlineSpecified() && 3079 FD->getStorageClass() == SC_Extern); 3080 } 3081 3082 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3083 const AttributedType *AT = T->getAs<AttributedType>(); 3084 while (AT && !AT->isCallingConv()) 3085 AT = AT->getModifiedType()->getAs<AttributedType>(); 3086 return AT; 3087 } 3088 3089 template <typename T> 3090 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3091 const DeclContext *DC = Old->getDeclContext(); 3092 if (DC->isRecord()) 3093 return false; 3094 3095 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3096 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3097 return true; 3098 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3099 return true; 3100 return false; 3101 } 3102 3103 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3104 static bool isExternC(VarTemplateDecl *) { return false; } 3105 3106 /// Check whether a redeclaration of an entity introduced by a 3107 /// using-declaration is valid, given that we know it's not an overload 3108 /// (nor a hidden tag declaration). 3109 template<typename ExpectedDecl> 3110 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3111 ExpectedDecl *New) { 3112 // C++11 [basic.scope.declarative]p4: 3113 // Given a set of declarations in a single declarative region, each of 3114 // which specifies the same unqualified name, 3115 // -- they shall all refer to the same entity, or all refer to functions 3116 // and function templates; or 3117 // -- exactly one declaration shall declare a class name or enumeration 3118 // name that is not a typedef name and the other declarations shall all 3119 // refer to the same variable or enumerator, or all refer to functions 3120 // and function templates; in this case the class name or enumeration 3121 // name is hidden (3.3.10). 3122 3123 // C++11 [namespace.udecl]p14: 3124 // If a function declaration in namespace scope or block scope has the 3125 // same name and the same parameter-type-list as a function introduced 3126 // by a using-declaration, and the declarations do not declare the same 3127 // function, the program is ill-formed. 3128 3129 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3130 if (Old && 3131 !Old->getDeclContext()->getRedeclContext()->Equals( 3132 New->getDeclContext()->getRedeclContext()) && 3133 !(isExternC(Old) && isExternC(New))) 3134 Old = nullptr; 3135 3136 if (!Old) { 3137 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3138 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3139 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3140 return true; 3141 } 3142 return false; 3143 } 3144 3145 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3146 const FunctionDecl *B) { 3147 assert(A->getNumParams() == B->getNumParams()); 3148 3149 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3150 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3151 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3152 if (AttrA == AttrB) 3153 return true; 3154 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3155 AttrA->isDynamic() == AttrB->isDynamic(); 3156 }; 3157 3158 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3159 } 3160 3161 /// If necessary, adjust the semantic declaration context for a qualified 3162 /// declaration to name the correct inline namespace within the qualifier. 3163 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3164 DeclaratorDecl *OldD) { 3165 // The only case where we need to update the DeclContext is when 3166 // redeclaration lookup for a qualified name finds a declaration 3167 // in an inline namespace within the context named by the qualifier: 3168 // 3169 // inline namespace N { int f(); } 3170 // int ::f(); // Sema DC needs adjusting from :: to N::. 3171 // 3172 // For unqualified declarations, the semantic context *can* change 3173 // along the redeclaration chain (for local extern declarations, 3174 // extern "C" declarations, and friend declarations in particular). 3175 if (!NewD->getQualifier()) 3176 return; 3177 3178 // NewD is probably already in the right context. 3179 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3180 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3181 if (NamedDC->Equals(SemaDC)) 3182 return; 3183 3184 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3185 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3186 "unexpected context for redeclaration"); 3187 3188 auto *LexDC = NewD->getLexicalDeclContext(); 3189 auto FixSemaDC = [=](NamedDecl *D) { 3190 if (!D) 3191 return; 3192 D->setDeclContext(SemaDC); 3193 D->setLexicalDeclContext(LexDC); 3194 }; 3195 3196 FixSemaDC(NewD); 3197 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3198 FixSemaDC(FD->getDescribedFunctionTemplate()); 3199 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3200 FixSemaDC(VD->getDescribedVarTemplate()); 3201 } 3202 3203 /// MergeFunctionDecl - We just parsed a function 'New' from 3204 /// declarator D which has the same name and scope as a previous 3205 /// declaration 'Old'. Figure out how to resolve this situation, 3206 /// merging decls or emitting diagnostics as appropriate. 3207 /// 3208 /// In C++, New and Old must be declarations that are not 3209 /// overloaded. Use IsOverload to determine whether New and Old are 3210 /// overloaded, and to select the Old declaration that New should be 3211 /// merged with. 3212 /// 3213 /// Returns true if there was an error, false otherwise. 3214 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3215 Scope *S, bool MergeTypeWithOld) { 3216 // Verify the old decl was also a function. 3217 FunctionDecl *Old = OldD->getAsFunction(); 3218 if (!Old) { 3219 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3220 if (New->getFriendObjectKind()) { 3221 Diag(New->getLocation(), diag::err_using_decl_friend); 3222 Diag(Shadow->getTargetDecl()->getLocation(), 3223 diag::note_using_decl_target); 3224 Diag(Shadow->getUsingDecl()->getLocation(), 3225 diag::note_using_decl) << 0; 3226 return true; 3227 } 3228 3229 // Check whether the two declarations might declare the same function. 3230 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3231 return true; 3232 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3233 } else { 3234 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3235 << New->getDeclName(); 3236 notePreviousDefinition(OldD, New->getLocation()); 3237 return true; 3238 } 3239 } 3240 3241 // If the old declaration was found in an inline namespace and the new 3242 // declaration was qualified, update the DeclContext to match. 3243 adjustDeclContextForDeclaratorDecl(New, Old); 3244 3245 // If the old declaration is invalid, just give up here. 3246 if (Old->isInvalidDecl()) 3247 return true; 3248 3249 // Disallow redeclaration of some builtins. 3250 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3251 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3252 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3253 << Old << Old->getType(); 3254 return true; 3255 } 3256 3257 diag::kind PrevDiag; 3258 SourceLocation OldLocation; 3259 std::tie(PrevDiag, OldLocation) = 3260 getNoteDiagForInvalidRedeclaration(Old, New); 3261 3262 // Don't complain about this if we're in GNU89 mode and the old function 3263 // is an extern inline function. 3264 // Don't complain about specializations. They are not supposed to have 3265 // storage classes. 3266 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3267 New->getStorageClass() == SC_Static && 3268 Old->hasExternalFormalLinkage() && 3269 !New->getTemplateSpecializationInfo() && 3270 !canRedefineFunction(Old, getLangOpts())) { 3271 if (getLangOpts().MicrosoftExt) { 3272 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3273 Diag(OldLocation, PrevDiag); 3274 } else { 3275 Diag(New->getLocation(), diag::err_static_non_static) << New; 3276 Diag(OldLocation, PrevDiag); 3277 return true; 3278 } 3279 } 3280 3281 if (New->hasAttr<InternalLinkageAttr>() && 3282 !Old->hasAttr<InternalLinkageAttr>()) { 3283 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3284 << New->getDeclName(); 3285 notePreviousDefinition(Old, New->getLocation()); 3286 New->dropAttr<InternalLinkageAttr>(); 3287 } 3288 3289 if (CheckRedeclarationModuleOwnership(New, Old)) 3290 return true; 3291 3292 if (!getLangOpts().CPlusPlus) { 3293 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3294 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3295 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3296 << New << OldOvl; 3297 3298 // Try our best to find a decl that actually has the overloadable 3299 // attribute for the note. In most cases (e.g. programs with only one 3300 // broken declaration/definition), this won't matter. 3301 // 3302 // FIXME: We could do this if we juggled some extra state in 3303 // OverloadableAttr, rather than just removing it. 3304 const Decl *DiagOld = Old; 3305 if (OldOvl) { 3306 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3307 const auto *A = D->getAttr<OverloadableAttr>(); 3308 return A && !A->isImplicit(); 3309 }); 3310 // If we've implicitly added *all* of the overloadable attrs to this 3311 // chain, emitting a "previous redecl" note is pointless. 3312 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3313 } 3314 3315 if (DiagOld) 3316 Diag(DiagOld->getLocation(), 3317 diag::note_attribute_overloadable_prev_overload) 3318 << OldOvl; 3319 3320 if (OldOvl) 3321 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3322 else 3323 New->dropAttr<OverloadableAttr>(); 3324 } 3325 } 3326 3327 // If a function is first declared with a calling convention, but is later 3328 // declared or defined without one, all following decls assume the calling 3329 // convention of the first. 3330 // 3331 // It's OK if a function is first declared without a calling convention, 3332 // but is later declared or defined with the default calling convention. 3333 // 3334 // To test if either decl has an explicit calling convention, we look for 3335 // AttributedType sugar nodes on the type as written. If they are missing or 3336 // were canonicalized away, we assume the calling convention was implicit. 3337 // 3338 // Note also that we DO NOT return at this point, because we still have 3339 // other tests to run. 3340 QualType OldQType = Context.getCanonicalType(Old->getType()); 3341 QualType NewQType = Context.getCanonicalType(New->getType()); 3342 const FunctionType *OldType = cast<FunctionType>(OldQType); 3343 const FunctionType *NewType = cast<FunctionType>(NewQType); 3344 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3345 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3346 bool RequiresAdjustment = false; 3347 3348 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3349 FunctionDecl *First = Old->getFirstDecl(); 3350 const FunctionType *FT = 3351 First->getType().getCanonicalType()->castAs<FunctionType>(); 3352 FunctionType::ExtInfo FI = FT->getExtInfo(); 3353 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3354 if (!NewCCExplicit) { 3355 // Inherit the CC from the previous declaration if it was specified 3356 // there but not here. 3357 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3358 RequiresAdjustment = true; 3359 } else if (Old->getBuiltinID()) { 3360 // Builtin attribute isn't propagated to the new one yet at this point, 3361 // so we check if the old one is a builtin. 3362 3363 // Calling Conventions on a Builtin aren't really useful and setting a 3364 // default calling convention and cdecl'ing some builtin redeclarations is 3365 // common, so warn and ignore the calling convention on the redeclaration. 3366 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3367 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3368 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3369 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3370 RequiresAdjustment = true; 3371 } else { 3372 // Calling conventions aren't compatible, so complain. 3373 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3374 Diag(New->getLocation(), diag::err_cconv_change) 3375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3376 << !FirstCCExplicit 3377 << (!FirstCCExplicit ? "" : 3378 FunctionType::getNameForCallConv(FI.getCC())); 3379 3380 // Put the note on the first decl, since it is the one that matters. 3381 Diag(First->getLocation(), diag::note_previous_declaration); 3382 return true; 3383 } 3384 } 3385 3386 // FIXME: diagnose the other way around? 3387 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3388 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3389 RequiresAdjustment = true; 3390 } 3391 3392 // Merge regparm attribute. 3393 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3394 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3395 if (NewTypeInfo.getHasRegParm()) { 3396 Diag(New->getLocation(), diag::err_regparm_mismatch) 3397 << NewType->getRegParmType() 3398 << OldType->getRegParmType(); 3399 Diag(OldLocation, diag::note_previous_declaration); 3400 return true; 3401 } 3402 3403 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3404 RequiresAdjustment = true; 3405 } 3406 3407 // Merge ns_returns_retained attribute. 3408 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3409 if (NewTypeInfo.getProducesResult()) { 3410 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3411 << "'ns_returns_retained'"; 3412 Diag(OldLocation, diag::note_previous_declaration); 3413 return true; 3414 } 3415 3416 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3417 RequiresAdjustment = true; 3418 } 3419 3420 if (OldTypeInfo.getNoCallerSavedRegs() != 3421 NewTypeInfo.getNoCallerSavedRegs()) { 3422 if (NewTypeInfo.getNoCallerSavedRegs()) { 3423 AnyX86NoCallerSavedRegistersAttr *Attr = 3424 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3425 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3426 Diag(OldLocation, diag::note_previous_declaration); 3427 return true; 3428 } 3429 3430 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3431 RequiresAdjustment = true; 3432 } 3433 3434 if (RequiresAdjustment) { 3435 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3436 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3437 New->setType(QualType(AdjustedType, 0)); 3438 NewQType = Context.getCanonicalType(New->getType()); 3439 } 3440 3441 // If this redeclaration makes the function inline, we may need to add it to 3442 // UndefinedButUsed. 3443 if (!Old->isInlined() && New->isInlined() && 3444 !New->hasAttr<GNUInlineAttr>() && 3445 !getLangOpts().GNUInline && 3446 Old->isUsed(false) && 3447 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3448 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3449 SourceLocation())); 3450 3451 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3452 // about it. 3453 if (New->hasAttr<GNUInlineAttr>() && 3454 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3455 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3456 } 3457 3458 // If pass_object_size params don't match up perfectly, this isn't a valid 3459 // redeclaration. 3460 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3461 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3462 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3463 << New->getDeclName(); 3464 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3465 return true; 3466 } 3467 3468 if (getLangOpts().CPlusPlus) { 3469 // C++1z [over.load]p2 3470 // Certain function declarations cannot be overloaded: 3471 // -- Function declarations that differ only in the return type, 3472 // the exception specification, or both cannot be overloaded. 3473 3474 // Check the exception specifications match. This may recompute the type of 3475 // both Old and New if it resolved exception specifications, so grab the 3476 // types again after this. Because this updates the type, we do this before 3477 // any of the other checks below, which may update the "de facto" NewQType 3478 // but do not necessarily update the type of New. 3479 if (CheckEquivalentExceptionSpec(Old, New)) 3480 return true; 3481 OldQType = Context.getCanonicalType(Old->getType()); 3482 NewQType = Context.getCanonicalType(New->getType()); 3483 3484 // Go back to the type source info to compare the declared return types, 3485 // per C++1y [dcl.type.auto]p13: 3486 // Redeclarations or specializations of a function or function template 3487 // with a declared return type that uses a placeholder type shall also 3488 // use that placeholder, not a deduced type. 3489 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3490 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3491 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3492 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3493 OldDeclaredReturnType)) { 3494 QualType ResQT; 3495 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3496 OldDeclaredReturnType->isObjCObjectPointerType()) 3497 // FIXME: This does the wrong thing for a deduced return type. 3498 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3499 if (ResQT.isNull()) { 3500 if (New->isCXXClassMember() && New->isOutOfLine()) 3501 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3502 << New << New->getReturnTypeSourceRange(); 3503 else 3504 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3505 << New->getReturnTypeSourceRange(); 3506 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3507 << Old->getReturnTypeSourceRange(); 3508 return true; 3509 } 3510 else 3511 NewQType = ResQT; 3512 } 3513 3514 QualType OldReturnType = OldType->getReturnType(); 3515 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3516 if (OldReturnType != NewReturnType) { 3517 // If this function has a deduced return type and has already been 3518 // defined, copy the deduced value from the old declaration. 3519 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3520 if (OldAT && OldAT->isDeduced()) { 3521 New->setType( 3522 SubstAutoType(New->getType(), 3523 OldAT->isDependentType() ? Context.DependentTy 3524 : OldAT->getDeducedType())); 3525 NewQType = Context.getCanonicalType( 3526 SubstAutoType(NewQType, 3527 OldAT->isDependentType() ? Context.DependentTy 3528 : OldAT->getDeducedType())); 3529 } 3530 } 3531 3532 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3533 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3534 if (OldMethod && NewMethod) { 3535 // Preserve triviality. 3536 NewMethod->setTrivial(OldMethod->isTrivial()); 3537 3538 // MSVC allows explicit template specialization at class scope: 3539 // 2 CXXMethodDecls referring to the same function will be injected. 3540 // We don't want a redeclaration error. 3541 bool IsClassScopeExplicitSpecialization = 3542 OldMethod->isFunctionTemplateSpecialization() && 3543 NewMethod->isFunctionTemplateSpecialization(); 3544 bool isFriend = NewMethod->getFriendObjectKind(); 3545 3546 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3547 !IsClassScopeExplicitSpecialization) { 3548 // -- Member function declarations with the same name and the 3549 // same parameter types cannot be overloaded if any of them 3550 // is a static member function declaration. 3551 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3552 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3553 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3554 return true; 3555 } 3556 3557 // C++ [class.mem]p1: 3558 // [...] A member shall not be declared twice in the 3559 // member-specification, except that a nested class or member 3560 // class template can be declared and then later defined. 3561 if (!inTemplateInstantiation()) { 3562 unsigned NewDiag; 3563 if (isa<CXXConstructorDecl>(OldMethod)) 3564 NewDiag = diag::err_constructor_redeclared; 3565 else if (isa<CXXDestructorDecl>(NewMethod)) 3566 NewDiag = diag::err_destructor_redeclared; 3567 else if (isa<CXXConversionDecl>(NewMethod)) 3568 NewDiag = diag::err_conv_function_redeclared; 3569 else 3570 NewDiag = diag::err_member_redeclared; 3571 3572 Diag(New->getLocation(), NewDiag); 3573 } else { 3574 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3575 << New << New->getType(); 3576 } 3577 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3578 return true; 3579 3580 // Complain if this is an explicit declaration of a special 3581 // member that was initially declared implicitly. 3582 // 3583 // As an exception, it's okay to befriend such methods in order 3584 // to permit the implicit constructor/destructor/operator calls. 3585 } else if (OldMethod->isImplicit()) { 3586 if (isFriend) { 3587 NewMethod->setImplicit(); 3588 } else { 3589 Diag(NewMethod->getLocation(), 3590 diag::err_definition_of_implicitly_declared_member) 3591 << New << getSpecialMember(OldMethod); 3592 return true; 3593 } 3594 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3595 Diag(NewMethod->getLocation(), 3596 diag::err_definition_of_explicitly_defaulted_member) 3597 << getSpecialMember(OldMethod); 3598 return true; 3599 } 3600 } 3601 3602 // C++11 [dcl.attr.noreturn]p1: 3603 // The first declaration of a function shall specify the noreturn 3604 // attribute if any declaration of that function specifies the noreturn 3605 // attribute. 3606 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3607 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3608 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3609 Diag(Old->getFirstDecl()->getLocation(), 3610 diag::note_noreturn_missing_first_decl); 3611 } 3612 3613 // C++11 [dcl.attr.depend]p2: 3614 // The first declaration of a function shall specify the 3615 // carries_dependency attribute for its declarator-id if any declaration 3616 // of the function specifies the carries_dependency attribute. 3617 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3618 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3619 Diag(CDA->getLocation(), 3620 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3621 Diag(Old->getFirstDecl()->getLocation(), 3622 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3623 } 3624 3625 // (C++98 8.3.5p3): 3626 // All declarations for a function shall agree exactly in both the 3627 // return type and the parameter-type-list. 3628 // We also want to respect all the extended bits except noreturn. 3629 3630 // noreturn should now match unless the old type info didn't have it. 3631 QualType OldQTypeForComparison = OldQType; 3632 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3633 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3634 const FunctionType *OldTypeForComparison 3635 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3636 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3637 assert(OldQTypeForComparison.isCanonical()); 3638 } 3639 3640 if (haveIncompatibleLanguageLinkages(Old, New)) { 3641 // As a special case, retain the language linkage from previous 3642 // declarations of a friend function as an extension. 3643 // 3644 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3645 // and is useful because there's otherwise no way to specify language 3646 // linkage within class scope. 3647 // 3648 // Check cautiously as the friend object kind isn't yet complete. 3649 if (New->getFriendObjectKind() != Decl::FOK_None) { 3650 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3651 Diag(OldLocation, PrevDiag); 3652 } else { 3653 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3654 Diag(OldLocation, PrevDiag); 3655 return true; 3656 } 3657 } 3658 3659 // If the function types are compatible, merge the declarations. Ignore the 3660 // exception specifier because it was already checked above in 3661 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3662 // about incompatible types under -fms-compatibility. 3663 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3664 NewQType)) 3665 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3666 3667 // If the types are imprecise (due to dependent constructs in friends or 3668 // local extern declarations), it's OK if they differ. We'll check again 3669 // during instantiation. 3670 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3671 return false; 3672 3673 // Fall through for conflicting redeclarations and redefinitions. 3674 } 3675 3676 // C: Function types need to be compatible, not identical. This handles 3677 // duplicate function decls like "void f(int); void f(enum X);" properly. 3678 if (!getLangOpts().CPlusPlus && 3679 Context.typesAreCompatible(OldQType, NewQType)) { 3680 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3681 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3682 const FunctionProtoType *OldProto = nullptr; 3683 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3684 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3685 // The old declaration provided a function prototype, but the 3686 // new declaration does not. Merge in the prototype. 3687 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3688 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3689 NewQType = 3690 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3691 OldProto->getExtProtoInfo()); 3692 New->setType(NewQType); 3693 New->setHasInheritedPrototype(); 3694 3695 // Synthesize parameters with the same types. 3696 SmallVector<ParmVarDecl*, 16> Params; 3697 for (const auto &ParamType : OldProto->param_types()) { 3698 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3699 SourceLocation(), nullptr, 3700 ParamType, /*TInfo=*/nullptr, 3701 SC_None, nullptr); 3702 Param->setScopeInfo(0, Params.size()); 3703 Param->setImplicit(); 3704 Params.push_back(Param); 3705 } 3706 3707 New->setParams(Params); 3708 } 3709 3710 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3711 } 3712 3713 // Check if the function types are compatible when pointer size address 3714 // spaces are ignored. 3715 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3716 return false; 3717 3718 // GNU C permits a K&R definition to follow a prototype declaration 3719 // if the declared types of the parameters in the K&R definition 3720 // match the types in the prototype declaration, even when the 3721 // promoted types of the parameters from the K&R definition differ 3722 // from the types in the prototype. GCC then keeps the types from 3723 // the prototype. 3724 // 3725 // If a variadic prototype is followed by a non-variadic K&R definition, 3726 // the K&R definition becomes variadic. This is sort of an edge case, but 3727 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3728 // C99 6.9.1p8. 3729 if (!getLangOpts().CPlusPlus && 3730 Old->hasPrototype() && !New->hasPrototype() && 3731 New->getType()->getAs<FunctionProtoType>() && 3732 Old->getNumParams() == New->getNumParams()) { 3733 SmallVector<QualType, 16> ArgTypes; 3734 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3735 const FunctionProtoType *OldProto 3736 = Old->getType()->getAs<FunctionProtoType>(); 3737 const FunctionProtoType *NewProto 3738 = New->getType()->getAs<FunctionProtoType>(); 3739 3740 // Determine whether this is the GNU C extension. 3741 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3742 NewProto->getReturnType()); 3743 bool LooseCompatible = !MergedReturn.isNull(); 3744 for (unsigned Idx = 0, End = Old->getNumParams(); 3745 LooseCompatible && Idx != End; ++Idx) { 3746 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3747 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3748 if (Context.typesAreCompatible(OldParm->getType(), 3749 NewProto->getParamType(Idx))) { 3750 ArgTypes.push_back(NewParm->getType()); 3751 } else if (Context.typesAreCompatible(OldParm->getType(), 3752 NewParm->getType(), 3753 /*CompareUnqualified=*/true)) { 3754 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3755 NewProto->getParamType(Idx) }; 3756 Warnings.push_back(Warn); 3757 ArgTypes.push_back(NewParm->getType()); 3758 } else 3759 LooseCompatible = false; 3760 } 3761 3762 if (LooseCompatible) { 3763 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3764 Diag(Warnings[Warn].NewParm->getLocation(), 3765 diag::ext_param_promoted_not_compatible_with_prototype) 3766 << Warnings[Warn].PromotedType 3767 << Warnings[Warn].OldParm->getType(); 3768 if (Warnings[Warn].OldParm->getLocation().isValid()) 3769 Diag(Warnings[Warn].OldParm->getLocation(), 3770 diag::note_previous_declaration); 3771 } 3772 3773 if (MergeTypeWithOld) 3774 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3775 OldProto->getExtProtoInfo())); 3776 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3777 } 3778 3779 // Fall through to diagnose conflicting types. 3780 } 3781 3782 // A function that has already been declared has been redeclared or 3783 // defined with a different type; show an appropriate diagnostic. 3784 3785 // If the previous declaration was an implicitly-generated builtin 3786 // declaration, then at the very least we should use a specialized note. 3787 unsigned BuiltinID; 3788 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3789 // If it's actually a library-defined builtin function like 'malloc' 3790 // or 'printf', just warn about the incompatible redeclaration. 3791 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3792 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3793 Diag(OldLocation, diag::note_previous_builtin_declaration) 3794 << Old << Old->getType(); 3795 return false; 3796 } 3797 3798 PrevDiag = diag::note_previous_builtin_declaration; 3799 } 3800 3801 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3803 return true; 3804 } 3805 3806 /// Completes the merge of two function declarations that are 3807 /// known to be compatible. 3808 /// 3809 /// This routine handles the merging of attributes and other 3810 /// properties of function declarations from the old declaration to 3811 /// the new declaration, once we know that New is in fact a 3812 /// redeclaration of Old. 3813 /// 3814 /// \returns false 3815 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3816 Scope *S, bool MergeTypeWithOld) { 3817 // Merge the attributes 3818 mergeDeclAttributes(New, Old); 3819 3820 // Merge "pure" flag. 3821 if (Old->isPure()) 3822 New->setPure(); 3823 3824 // Merge "used" flag. 3825 if (Old->getMostRecentDecl()->isUsed(false)) 3826 New->setIsUsed(); 3827 3828 // Merge attributes from the parameters. These can mismatch with K&R 3829 // declarations. 3830 if (New->getNumParams() == Old->getNumParams()) 3831 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3832 ParmVarDecl *NewParam = New->getParamDecl(i); 3833 ParmVarDecl *OldParam = Old->getParamDecl(i); 3834 mergeParamDeclAttributes(NewParam, OldParam, *this); 3835 mergeParamDeclTypes(NewParam, OldParam, *this); 3836 } 3837 3838 if (getLangOpts().CPlusPlus) 3839 return MergeCXXFunctionDecl(New, Old, S); 3840 3841 // Merge the function types so the we get the composite types for the return 3842 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3843 // was visible. 3844 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3845 if (!Merged.isNull() && MergeTypeWithOld) 3846 New->setType(Merged); 3847 3848 return false; 3849 } 3850 3851 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3852 ObjCMethodDecl *oldMethod) { 3853 // Merge the attributes, including deprecated/unavailable 3854 AvailabilityMergeKind MergeKind = 3855 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3856 ? AMK_ProtocolImplementation 3857 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3858 : AMK_Override; 3859 3860 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3861 3862 // Merge attributes from the parameters. 3863 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3864 oe = oldMethod->param_end(); 3865 for (ObjCMethodDecl::param_iterator 3866 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3867 ni != ne && oi != oe; ++ni, ++oi) 3868 mergeParamDeclAttributes(*ni, *oi, *this); 3869 3870 CheckObjCMethodOverride(newMethod, oldMethod); 3871 } 3872 3873 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3874 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3875 3876 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3877 ? diag::err_redefinition_different_type 3878 : diag::err_redeclaration_different_type) 3879 << New->getDeclName() << New->getType() << Old->getType(); 3880 3881 diag::kind PrevDiag; 3882 SourceLocation OldLocation; 3883 std::tie(PrevDiag, OldLocation) 3884 = getNoteDiagForInvalidRedeclaration(Old, New); 3885 S.Diag(OldLocation, PrevDiag); 3886 New->setInvalidDecl(); 3887 } 3888 3889 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3890 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3891 /// emitting diagnostics as appropriate. 3892 /// 3893 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3894 /// to here in AddInitializerToDecl. We can't check them before the initializer 3895 /// is attached. 3896 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3897 bool MergeTypeWithOld) { 3898 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3899 return; 3900 3901 QualType MergedT; 3902 if (getLangOpts().CPlusPlus) { 3903 if (New->getType()->isUndeducedType()) { 3904 // We don't know what the new type is until the initializer is attached. 3905 return; 3906 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3907 // These could still be something that needs exception specs checked. 3908 return MergeVarDeclExceptionSpecs(New, Old); 3909 } 3910 // C++ [basic.link]p10: 3911 // [...] the types specified by all declarations referring to a given 3912 // object or function shall be identical, except that declarations for an 3913 // array object can specify array types that differ by the presence or 3914 // absence of a major array bound (8.3.4). 3915 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3916 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3917 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3918 3919 // We are merging a variable declaration New into Old. If it has an array 3920 // bound, and that bound differs from Old's bound, we should diagnose the 3921 // mismatch. 3922 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3923 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3924 PrevVD = PrevVD->getPreviousDecl()) { 3925 QualType PrevVDTy = PrevVD->getType(); 3926 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3927 continue; 3928 3929 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3930 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3931 } 3932 } 3933 3934 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3935 if (Context.hasSameType(OldArray->getElementType(), 3936 NewArray->getElementType())) 3937 MergedT = New->getType(); 3938 } 3939 // FIXME: Check visibility. New is hidden but has a complete type. If New 3940 // has no array bound, it should not inherit one from Old, if Old is not 3941 // visible. 3942 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3943 if (Context.hasSameType(OldArray->getElementType(), 3944 NewArray->getElementType())) 3945 MergedT = Old->getType(); 3946 } 3947 } 3948 else if (New->getType()->isObjCObjectPointerType() && 3949 Old->getType()->isObjCObjectPointerType()) { 3950 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3951 Old->getType()); 3952 } 3953 } else { 3954 // C 6.2.7p2: 3955 // All declarations that refer to the same object or function shall have 3956 // compatible type. 3957 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3958 } 3959 if (MergedT.isNull()) { 3960 // It's OK if we couldn't merge types if either type is dependent, for a 3961 // block-scope variable. In other cases (static data members of class 3962 // templates, variable templates, ...), we require the types to be 3963 // equivalent. 3964 // FIXME: The C++ standard doesn't say anything about this. 3965 if ((New->getType()->isDependentType() || 3966 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3967 // If the old type was dependent, we can't merge with it, so the new type 3968 // becomes dependent for now. We'll reproduce the original type when we 3969 // instantiate the TypeSourceInfo for the variable. 3970 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3971 New->setType(Context.DependentTy); 3972 return; 3973 } 3974 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3975 } 3976 3977 // Don't actually update the type on the new declaration if the old 3978 // declaration was an extern declaration in a different scope. 3979 if (MergeTypeWithOld) 3980 New->setType(MergedT); 3981 } 3982 3983 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3984 LookupResult &Previous) { 3985 // C11 6.2.7p4: 3986 // For an identifier with internal or external linkage declared 3987 // in a scope in which a prior declaration of that identifier is 3988 // visible, if the prior declaration specifies internal or 3989 // external linkage, the type of the identifier at the later 3990 // declaration becomes the composite type. 3991 // 3992 // If the variable isn't visible, we do not merge with its type. 3993 if (Previous.isShadowed()) 3994 return false; 3995 3996 if (S.getLangOpts().CPlusPlus) { 3997 // C++11 [dcl.array]p3: 3998 // If there is a preceding declaration of the entity in the same 3999 // scope in which the bound was specified, an omitted array bound 4000 // is taken to be the same as in that earlier declaration. 4001 return NewVD->isPreviousDeclInSameBlockScope() || 4002 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4003 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4004 } else { 4005 // If the old declaration was function-local, don't merge with its 4006 // type unless we're in the same function. 4007 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4008 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4009 } 4010 } 4011 4012 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4013 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4014 /// situation, merging decls or emitting diagnostics as appropriate. 4015 /// 4016 /// Tentative definition rules (C99 6.9.2p2) are checked by 4017 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4018 /// definitions here, since the initializer hasn't been attached. 4019 /// 4020 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4021 // If the new decl is already invalid, don't do any other checking. 4022 if (New->isInvalidDecl()) 4023 return; 4024 4025 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4026 return; 4027 4028 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4029 4030 // Verify the old decl was also a variable or variable template. 4031 VarDecl *Old = nullptr; 4032 VarTemplateDecl *OldTemplate = nullptr; 4033 if (Previous.isSingleResult()) { 4034 if (NewTemplate) { 4035 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4036 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4037 4038 if (auto *Shadow = 4039 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4040 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4041 return New->setInvalidDecl(); 4042 } else { 4043 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4044 4045 if (auto *Shadow = 4046 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4047 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4048 return New->setInvalidDecl(); 4049 } 4050 } 4051 if (!Old) { 4052 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4053 << New->getDeclName(); 4054 notePreviousDefinition(Previous.getRepresentativeDecl(), 4055 New->getLocation()); 4056 return New->setInvalidDecl(); 4057 } 4058 4059 // If the old declaration was found in an inline namespace and the new 4060 // declaration was qualified, update the DeclContext to match. 4061 adjustDeclContextForDeclaratorDecl(New, Old); 4062 4063 // Ensure the template parameters are compatible. 4064 if (NewTemplate && 4065 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4066 OldTemplate->getTemplateParameters(), 4067 /*Complain=*/true, TPL_TemplateMatch)) 4068 return New->setInvalidDecl(); 4069 4070 // C++ [class.mem]p1: 4071 // A member shall not be declared twice in the member-specification [...] 4072 // 4073 // Here, we need only consider static data members. 4074 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4075 Diag(New->getLocation(), diag::err_duplicate_member) 4076 << New->getIdentifier(); 4077 Diag(Old->getLocation(), diag::note_previous_declaration); 4078 New->setInvalidDecl(); 4079 } 4080 4081 mergeDeclAttributes(New, Old); 4082 // Warn if an already-declared variable is made a weak_import in a subsequent 4083 // declaration 4084 if (New->hasAttr<WeakImportAttr>() && 4085 Old->getStorageClass() == SC_None && 4086 !Old->hasAttr<WeakImportAttr>()) { 4087 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4088 notePreviousDefinition(Old, New->getLocation()); 4089 // Remove weak_import attribute on new declaration. 4090 New->dropAttr<WeakImportAttr>(); 4091 } 4092 4093 if (New->hasAttr<InternalLinkageAttr>() && 4094 !Old->hasAttr<InternalLinkageAttr>()) { 4095 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4096 << New->getDeclName(); 4097 notePreviousDefinition(Old, New->getLocation()); 4098 New->dropAttr<InternalLinkageAttr>(); 4099 } 4100 4101 // Merge the types. 4102 VarDecl *MostRecent = Old->getMostRecentDecl(); 4103 if (MostRecent != Old) { 4104 MergeVarDeclTypes(New, MostRecent, 4105 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4106 if (New->isInvalidDecl()) 4107 return; 4108 } 4109 4110 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4111 if (New->isInvalidDecl()) 4112 return; 4113 4114 diag::kind PrevDiag; 4115 SourceLocation OldLocation; 4116 std::tie(PrevDiag, OldLocation) = 4117 getNoteDiagForInvalidRedeclaration(Old, New); 4118 4119 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4120 if (New->getStorageClass() == SC_Static && 4121 !New->isStaticDataMember() && 4122 Old->hasExternalFormalLinkage()) { 4123 if (getLangOpts().MicrosoftExt) { 4124 Diag(New->getLocation(), diag::ext_static_non_static) 4125 << New->getDeclName(); 4126 Diag(OldLocation, PrevDiag); 4127 } else { 4128 Diag(New->getLocation(), diag::err_static_non_static) 4129 << New->getDeclName(); 4130 Diag(OldLocation, PrevDiag); 4131 return New->setInvalidDecl(); 4132 } 4133 } 4134 // C99 6.2.2p4: 4135 // For an identifier declared with the storage-class specifier 4136 // extern in a scope in which a prior declaration of that 4137 // identifier is visible,23) if the prior declaration specifies 4138 // internal or external linkage, the linkage of the identifier at 4139 // the later declaration is the same as the linkage specified at 4140 // the prior declaration. If no prior declaration is visible, or 4141 // if the prior declaration specifies no linkage, then the 4142 // identifier has external linkage. 4143 if (New->hasExternalStorage() && Old->hasLinkage()) 4144 /* Okay */; 4145 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4146 !New->isStaticDataMember() && 4147 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4148 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4149 Diag(OldLocation, PrevDiag); 4150 return New->setInvalidDecl(); 4151 } 4152 4153 // Check if extern is followed by non-extern and vice-versa. 4154 if (New->hasExternalStorage() && 4155 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4156 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4157 Diag(OldLocation, PrevDiag); 4158 return New->setInvalidDecl(); 4159 } 4160 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4161 !New->hasExternalStorage()) { 4162 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4163 Diag(OldLocation, PrevDiag); 4164 return New->setInvalidDecl(); 4165 } 4166 4167 if (CheckRedeclarationModuleOwnership(New, Old)) 4168 return; 4169 4170 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4171 4172 // FIXME: The test for external storage here seems wrong? We still 4173 // need to check for mismatches. 4174 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4175 // Don't complain about out-of-line definitions of static members. 4176 !(Old->getLexicalDeclContext()->isRecord() && 4177 !New->getLexicalDeclContext()->isRecord())) { 4178 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4179 Diag(OldLocation, PrevDiag); 4180 return New->setInvalidDecl(); 4181 } 4182 4183 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4184 if (VarDecl *Def = Old->getDefinition()) { 4185 // C++1z [dcl.fcn.spec]p4: 4186 // If the definition of a variable appears in a translation unit before 4187 // its first declaration as inline, the program is ill-formed. 4188 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4189 Diag(Def->getLocation(), diag::note_previous_definition); 4190 } 4191 } 4192 4193 // If this redeclaration makes the variable inline, we may need to add it to 4194 // UndefinedButUsed. 4195 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4196 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4197 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4198 SourceLocation())); 4199 4200 if (New->getTLSKind() != Old->getTLSKind()) { 4201 if (!Old->getTLSKind()) { 4202 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4203 Diag(OldLocation, PrevDiag); 4204 } else if (!New->getTLSKind()) { 4205 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4206 Diag(OldLocation, PrevDiag); 4207 } else { 4208 // Do not allow redeclaration to change the variable between requiring 4209 // static and dynamic initialization. 4210 // FIXME: GCC allows this, but uses the TLS keyword on the first 4211 // declaration to determine the kind. Do we need to be compatible here? 4212 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4213 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4214 Diag(OldLocation, PrevDiag); 4215 } 4216 } 4217 4218 // C++ doesn't have tentative definitions, so go right ahead and check here. 4219 if (getLangOpts().CPlusPlus && 4220 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4221 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4222 Old->getCanonicalDecl()->isConstexpr()) { 4223 // This definition won't be a definition any more once it's been merged. 4224 Diag(New->getLocation(), 4225 diag::warn_deprecated_redundant_constexpr_static_def); 4226 } else if (VarDecl *Def = Old->getDefinition()) { 4227 if (checkVarDeclRedefinition(Def, New)) 4228 return; 4229 } 4230 } 4231 4232 if (haveIncompatibleLanguageLinkages(Old, New)) { 4233 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4234 Diag(OldLocation, PrevDiag); 4235 New->setInvalidDecl(); 4236 return; 4237 } 4238 4239 // Merge "used" flag. 4240 if (Old->getMostRecentDecl()->isUsed(false)) 4241 New->setIsUsed(); 4242 4243 // Keep a chain of previous declarations. 4244 New->setPreviousDecl(Old); 4245 if (NewTemplate) 4246 NewTemplate->setPreviousDecl(OldTemplate); 4247 4248 // Inherit access appropriately. 4249 New->setAccess(Old->getAccess()); 4250 if (NewTemplate) 4251 NewTemplate->setAccess(New->getAccess()); 4252 4253 if (Old->isInline()) 4254 New->setImplicitlyInline(); 4255 } 4256 4257 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4258 SourceManager &SrcMgr = getSourceManager(); 4259 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4260 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4261 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4262 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4263 auto &HSI = PP.getHeaderSearchInfo(); 4264 StringRef HdrFilename = 4265 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4266 4267 auto noteFromModuleOrInclude = [&](Module *Mod, 4268 SourceLocation IncLoc) -> bool { 4269 // Redefinition errors with modules are common with non modular mapped 4270 // headers, example: a non-modular header H in module A that also gets 4271 // included directly in a TU. Pointing twice to the same header/definition 4272 // is confusing, try to get better diagnostics when modules is on. 4273 if (IncLoc.isValid()) { 4274 if (Mod) { 4275 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4276 << HdrFilename.str() << Mod->getFullModuleName(); 4277 if (!Mod->DefinitionLoc.isInvalid()) 4278 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4279 << Mod->getFullModuleName(); 4280 } else { 4281 Diag(IncLoc, diag::note_redefinition_include_same_file) 4282 << HdrFilename.str(); 4283 } 4284 return true; 4285 } 4286 4287 return false; 4288 }; 4289 4290 // Is it the same file and same offset? Provide more information on why 4291 // this leads to a redefinition error. 4292 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4293 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4294 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4295 bool EmittedDiag = 4296 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4297 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4298 4299 // If the header has no guards, emit a note suggesting one. 4300 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4301 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4302 4303 if (EmittedDiag) 4304 return; 4305 } 4306 4307 // Redefinition coming from different files or couldn't do better above. 4308 if (Old->getLocation().isValid()) 4309 Diag(Old->getLocation(), diag::note_previous_definition); 4310 } 4311 4312 /// We've just determined that \p Old and \p New both appear to be definitions 4313 /// of the same variable. Either diagnose or fix the problem. 4314 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4315 if (!hasVisibleDefinition(Old) && 4316 (New->getFormalLinkage() == InternalLinkage || 4317 New->isInline() || 4318 New->getDescribedVarTemplate() || 4319 New->getNumTemplateParameterLists() || 4320 New->getDeclContext()->isDependentContext())) { 4321 // The previous definition is hidden, and multiple definitions are 4322 // permitted (in separate TUs). Demote this to a declaration. 4323 New->demoteThisDefinitionToDeclaration(); 4324 4325 // Make the canonical definition visible. 4326 if (auto *OldTD = Old->getDescribedVarTemplate()) 4327 makeMergedDefinitionVisible(OldTD); 4328 makeMergedDefinitionVisible(Old); 4329 return false; 4330 } else { 4331 Diag(New->getLocation(), diag::err_redefinition) << New; 4332 notePreviousDefinition(Old, New->getLocation()); 4333 New->setInvalidDecl(); 4334 return true; 4335 } 4336 } 4337 4338 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4339 /// no declarator (e.g. "struct foo;") is parsed. 4340 Decl * 4341 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4342 RecordDecl *&AnonRecord) { 4343 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4344 AnonRecord); 4345 } 4346 4347 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4348 // disambiguate entities defined in different scopes. 4349 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4350 // compatibility. 4351 // We will pick our mangling number depending on which version of MSVC is being 4352 // targeted. 4353 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4354 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4355 ? S->getMSCurManglingNumber() 4356 : S->getMSLastManglingNumber(); 4357 } 4358 4359 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4360 if (!Context.getLangOpts().CPlusPlus) 4361 return; 4362 4363 if (isa<CXXRecordDecl>(Tag->getParent())) { 4364 // If this tag is the direct child of a class, number it if 4365 // it is anonymous. 4366 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4367 return; 4368 MangleNumberingContext &MCtx = 4369 Context.getManglingNumberContext(Tag->getParent()); 4370 Context.setManglingNumber( 4371 Tag, MCtx.getManglingNumber( 4372 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4373 return; 4374 } 4375 4376 // If this tag isn't a direct child of a class, number it if it is local. 4377 MangleNumberingContext *MCtx; 4378 Decl *ManglingContextDecl; 4379 std::tie(MCtx, ManglingContextDecl) = 4380 getCurrentMangleNumberContext(Tag->getDeclContext()); 4381 if (MCtx) { 4382 Context.setManglingNumber( 4383 Tag, MCtx->getManglingNumber( 4384 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4385 } 4386 } 4387 4388 namespace { 4389 struct NonCLikeKind { 4390 enum { 4391 None, 4392 BaseClass, 4393 DefaultMemberInit, 4394 Lambda, 4395 Friend, 4396 OtherMember, 4397 Invalid, 4398 } Kind = None; 4399 SourceRange Range; 4400 4401 explicit operator bool() { return Kind != None; } 4402 }; 4403 } 4404 4405 /// Determine whether a class is C-like, according to the rules of C++ 4406 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4407 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4408 if (RD->isInvalidDecl()) 4409 return {NonCLikeKind::Invalid, {}}; 4410 4411 // C++ [dcl.typedef]p9: [P1766R1] 4412 // An unnamed class with a typedef name for linkage purposes shall not 4413 // 4414 // -- have any base classes 4415 if (RD->getNumBases()) 4416 return {NonCLikeKind::BaseClass, 4417 SourceRange(RD->bases_begin()->getBeginLoc(), 4418 RD->bases_end()[-1].getEndLoc())}; 4419 bool Invalid = false; 4420 for (Decl *D : RD->decls()) { 4421 // Don't complain about things we already diagnosed. 4422 if (D->isInvalidDecl()) { 4423 Invalid = true; 4424 continue; 4425 } 4426 4427 // -- have any [...] default member initializers 4428 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4429 if (FD->hasInClassInitializer()) { 4430 auto *Init = FD->getInClassInitializer(); 4431 return {NonCLikeKind::DefaultMemberInit, 4432 Init ? Init->getSourceRange() : D->getSourceRange()}; 4433 } 4434 continue; 4435 } 4436 4437 // FIXME: We don't allow friend declarations. This violates the wording of 4438 // P1766, but not the intent. 4439 if (isa<FriendDecl>(D)) 4440 return {NonCLikeKind::Friend, D->getSourceRange()}; 4441 4442 // -- declare any members other than non-static data members, member 4443 // enumerations, or member classes, 4444 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4445 isa<EnumDecl>(D)) 4446 continue; 4447 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4448 if (!MemberRD) { 4449 if (D->isImplicit()) 4450 continue; 4451 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4452 } 4453 4454 // -- contain a lambda-expression, 4455 if (MemberRD->isLambda()) 4456 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4457 4458 // and all member classes shall also satisfy these requirements 4459 // (recursively). 4460 if (MemberRD->isThisDeclarationADefinition()) { 4461 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4462 return Kind; 4463 } 4464 } 4465 4466 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4467 } 4468 4469 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4470 TypedefNameDecl *NewTD) { 4471 if (TagFromDeclSpec->isInvalidDecl()) 4472 return; 4473 4474 // Do nothing if the tag already has a name for linkage purposes. 4475 if (TagFromDeclSpec->hasNameForLinkage()) 4476 return; 4477 4478 // A well-formed anonymous tag must always be a TUK_Definition. 4479 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4480 4481 // The type must match the tag exactly; no qualifiers allowed. 4482 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4483 Context.getTagDeclType(TagFromDeclSpec))) { 4484 if (getLangOpts().CPlusPlus) 4485 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4486 return; 4487 } 4488 4489 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4490 // An unnamed class with a typedef name for linkage purposes shall [be 4491 // C-like]. 4492 // 4493 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4494 // shouldn't happen, but there are constructs that the language rule doesn't 4495 // disallow for which we can't reasonably avoid computing linkage early. 4496 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4497 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4498 : NonCLikeKind(); 4499 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4500 if (NonCLike || ChangesLinkage) { 4501 if (NonCLike.Kind == NonCLikeKind::Invalid) 4502 return; 4503 4504 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4505 if (ChangesLinkage) { 4506 // If the linkage changes, we can't accept this as an extension. 4507 if (NonCLike.Kind == NonCLikeKind::None) 4508 DiagID = diag::err_typedef_changes_linkage; 4509 else 4510 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4511 } 4512 4513 SourceLocation FixitLoc = 4514 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4515 llvm::SmallString<40> TextToInsert; 4516 TextToInsert += ' '; 4517 TextToInsert += NewTD->getIdentifier()->getName(); 4518 4519 Diag(FixitLoc, DiagID) 4520 << isa<TypeAliasDecl>(NewTD) 4521 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4522 if (NonCLike.Kind != NonCLikeKind::None) { 4523 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4524 << NonCLike.Kind - 1 << NonCLike.Range; 4525 } 4526 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4527 << NewTD << isa<TypeAliasDecl>(NewTD); 4528 4529 if (ChangesLinkage) 4530 return; 4531 } 4532 4533 // Otherwise, set this as the anon-decl typedef for the tag. 4534 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4535 } 4536 4537 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4538 switch (T) { 4539 case DeclSpec::TST_class: 4540 return 0; 4541 case DeclSpec::TST_struct: 4542 return 1; 4543 case DeclSpec::TST_interface: 4544 return 2; 4545 case DeclSpec::TST_union: 4546 return 3; 4547 case DeclSpec::TST_enum: 4548 return 4; 4549 default: 4550 llvm_unreachable("unexpected type specifier"); 4551 } 4552 } 4553 4554 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4555 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4556 /// parameters to cope with template friend declarations. 4557 Decl * 4558 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4559 MultiTemplateParamsArg TemplateParams, 4560 bool IsExplicitInstantiation, 4561 RecordDecl *&AnonRecord) { 4562 Decl *TagD = nullptr; 4563 TagDecl *Tag = nullptr; 4564 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4565 DS.getTypeSpecType() == DeclSpec::TST_struct || 4566 DS.getTypeSpecType() == DeclSpec::TST_interface || 4567 DS.getTypeSpecType() == DeclSpec::TST_union || 4568 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4569 TagD = DS.getRepAsDecl(); 4570 4571 if (!TagD) // We probably had an error 4572 return nullptr; 4573 4574 // Note that the above type specs guarantee that the 4575 // type rep is a Decl, whereas in many of the others 4576 // it's a Type. 4577 if (isa<TagDecl>(TagD)) 4578 Tag = cast<TagDecl>(TagD); 4579 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4580 Tag = CTD->getTemplatedDecl(); 4581 } 4582 4583 if (Tag) { 4584 handleTagNumbering(Tag, S); 4585 Tag->setFreeStanding(); 4586 if (Tag->isInvalidDecl()) 4587 return Tag; 4588 } 4589 4590 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4591 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4592 // or incomplete types shall not be restrict-qualified." 4593 if (TypeQuals & DeclSpec::TQ_restrict) 4594 Diag(DS.getRestrictSpecLoc(), 4595 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4596 << DS.getSourceRange(); 4597 } 4598 4599 if (DS.isInlineSpecified()) 4600 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4601 << getLangOpts().CPlusPlus17; 4602 4603 if (DS.hasConstexprSpecifier()) { 4604 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4605 // and definitions of functions and variables. 4606 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4607 // the declaration of a function or function template 4608 if (Tag) 4609 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4610 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4611 << static_cast<int>(DS.getConstexprSpecifier()); 4612 else 4613 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4614 << static_cast<int>(DS.getConstexprSpecifier()); 4615 // Don't emit warnings after this error. 4616 return TagD; 4617 } 4618 4619 DiagnoseFunctionSpecifiers(DS); 4620 4621 if (DS.isFriendSpecified()) { 4622 // If we're dealing with a decl but not a TagDecl, assume that 4623 // whatever routines created it handled the friendship aspect. 4624 if (TagD && !Tag) 4625 return nullptr; 4626 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4627 } 4628 4629 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4630 bool IsExplicitSpecialization = 4631 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4632 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4633 !IsExplicitInstantiation && !IsExplicitSpecialization && 4634 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4635 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4636 // nested-name-specifier unless it is an explicit instantiation 4637 // or an explicit specialization. 4638 // 4639 // FIXME: We allow class template partial specializations here too, per the 4640 // obvious intent of DR1819. 4641 // 4642 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4643 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4644 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4645 return nullptr; 4646 } 4647 4648 // Track whether this decl-specifier declares anything. 4649 bool DeclaresAnything = true; 4650 4651 // Handle anonymous struct definitions. 4652 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4653 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4654 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4655 if (getLangOpts().CPlusPlus || 4656 Record->getDeclContext()->isRecord()) { 4657 // If CurContext is a DeclContext that can contain statements, 4658 // RecursiveASTVisitor won't visit the decls that 4659 // BuildAnonymousStructOrUnion() will put into CurContext. 4660 // Also store them here so that they can be part of the 4661 // DeclStmt that gets created in this case. 4662 // FIXME: Also return the IndirectFieldDecls created by 4663 // BuildAnonymousStructOr union, for the same reason? 4664 if (CurContext->isFunctionOrMethod()) 4665 AnonRecord = Record; 4666 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4667 Context.getPrintingPolicy()); 4668 } 4669 4670 DeclaresAnything = false; 4671 } 4672 } 4673 4674 // C11 6.7.2.1p2: 4675 // A struct-declaration that does not declare an anonymous structure or 4676 // anonymous union shall contain a struct-declarator-list. 4677 // 4678 // This rule also existed in C89 and C99; the grammar for struct-declaration 4679 // did not permit a struct-declaration without a struct-declarator-list. 4680 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4681 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4682 // Check for Microsoft C extension: anonymous struct/union member. 4683 // Handle 2 kinds of anonymous struct/union: 4684 // struct STRUCT; 4685 // union UNION; 4686 // and 4687 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4688 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4689 if ((Tag && Tag->getDeclName()) || 4690 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4691 RecordDecl *Record = nullptr; 4692 if (Tag) 4693 Record = dyn_cast<RecordDecl>(Tag); 4694 else if (const RecordType *RT = 4695 DS.getRepAsType().get()->getAsStructureType()) 4696 Record = RT->getDecl(); 4697 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4698 Record = UT->getDecl(); 4699 4700 if (Record && getLangOpts().MicrosoftExt) { 4701 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4702 << Record->isUnion() << DS.getSourceRange(); 4703 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4704 } 4705 4706 DeclaresAnything = false; 4707 } 4708 } 4709 4710 // Skip all the checks below if we have a type error. 4711 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4712 (TagD && TagD->isInvalidDecl())) 4713 return TagD; 4714 4715 if (getLangOpts().CPlusPlus && 4716 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4717 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4718 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4719 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4720 DeclaresAnything = false; 4721 4722 if (!DS.isMissingDeclaratorOk()) { 4723 // Customize diagnostic for a typedef missing a name. 4724 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4725 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4726 << DS.getSourceRange(); 4727 else 4728 DeclaresAnything = false; 4729 } 4730 4731 if (DS.isModulePrivateSpecified() && 4732 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4733 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4734 << Tag->getTagKind() 4735 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4736 4737 ActOnDocumentableDecl(TagD); 4738 4739 // C 6.7/2: 4740 // A declaration [...] shall declare at least a declarator [...], a tag, 4741 // or the members of an enumeration. 4742 // C++ [dcl.dcl]p3: 4743 // [If there are no declarators], and except for the declaration of an 4744 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4745 // names into the program, or shall redeclare a name introduced by a 4746 // previous declaration. 4747 if (!DeclaresAnything) { 4748 // In C, we allow this as a (popular) extension / bug. Don't bother 4749 // producing further diagnostics for redundant qualifiers after this. 4750 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4751 ? diag::err_no_declarators 4752 : diag::ext_no_declarators) 4753 << DS.getSourceRange(); 4754 return TagD; 4755 } 4756 4757 // C++ [dcl.stc]p1: 4758 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4759 // init-declarator-list of the declaration shall not be empty. 4760 // C++ [dcl.fct.spec]p1: 4761 // If a cv-qualifier appears in a decl-specifier-seq, the 4762 // init-declarator-list of the declaration shall not be empty. 4763 // 4764 // Spurious qualifiers here appear to be valid in C. 4765 unsigned DiagID = diag::warn_standalone_specifier; 4766 if (getLangOpts().CPlusPlus) 4767 DiagID = diag::ext_standalone_specifier; 4768 4769 // Note that a linkage-specification sets a storage class, but 4770 // 'extern "C" struct foo;' is actually valid and not theoretically 4771 // useless. 4772 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4773 if (SCS == DeclSpec::SCS_mutable) 4774 // Since mutable is not a viable storage class specifier in C, there is 4775 // no reason to treat it as an extension. Instead, diagnose as an error. 4776 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4777 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4778 Diag(DS.getStorageClassSpecLoc(), DiagID) 4779 << DeclSpec::getSpecifierName(SCS); 4780 } 4781 4782 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4783 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4784 << DeclSpec::getSpecifierName(TSCS); 4785 if (DS.getTypeQualifiers()) { 4786 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4787 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4788 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4789 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4790 // Restrict is covered above. 4791 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4792 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4793 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4794 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4795 } 4796 4797 // Warn about ignored type attributes, for example: 4798 // __attribute__((aligned)) struct A; 4799 // Attributes should be placed after tag to apply to type declaration. 4800 if (!DS.getAttributes().empty()) { 4801 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4802 if (TypeSpecType == DeclSpec::TST_class || 4803 TypeSpecType == DeclSpec::TST_struct || 4804 TypeSpecType == DeclSpec::TST_interface || 4805 TypeSpecType == DeclSpec::TST_union || 4806 TypeSpecType == DeclSpec::TST_enum) { 4807 for (const ParsedAttr &AL : DS.getAttributes()) 4808 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4809 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4810 } 4811 } 4812 4813 return TagD; 4814 } 4815 4816 /// We are trying to inject an anonymous member into the given scope; 4817 /// check if there's an existing declaration that can't be overloaded. 4818 /// 4819 /// \return true if this is a forbidden redeclaration 4820 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4821 Scope *S, 4822 DeclContext *Owner, 4823 DeclarationName Name, 4824 SourceLocation NameLoc, 4825 bool IsUnion) { 4826 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4827 Sema::ForVisibleRedeclaration); 4828 if (!SemaRef.LookupName(R, S)) return false; 4829 4830 // Pick a representative declaration. 4831 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4832 assert(PrevDecl && "Expected a non-null Decl"); 4833 4834 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4835 return false; 4836 4837 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4838 << IsUnion << Name; 4839 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4840 4841 return true; 4842 } 4843 4844 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4845 /// anonymous struct or union AnonRecord into the owning context Owner 4846 /// and scope S. This routine will be invoked just after we realize 4847 /// that an unnamed union or struct is actually an anonymous union or 4848 /// struct, e.g., 4849 /// 4850 /// @code 4851 /// union { 4852 /// int i; 4853 /// float f; 4854 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4855 /// // f into the surrounding scope.x 4856 /// @endcode 4857 /// 4858 /// This routine is recursive, injecting the names of nested anonymous 4859 /// structs/unions into the owning context and scope as well. 4860 static bool 4861 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4862 RecordDecl *AnonRecord, AccessSpecifier AS, 4863 SmallVectorImpl<NamedDecl *> &Chaining) { 4864 bool Invalid = false; 4865 4866 // Look every FieldDecl and IndirectFieldDecl with a name. 4867 for (auto *D : AnonRecord->decls()) { 4868 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4869 cast<NamedDecl>(D)->getDeclName()) { 4870 ValueDecl *VD = cast<ValueDecl>(D); 4871 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4872 VD->getLocation(), 4873 AnonRecord->isUnion())) { 4874 // C++ [class.union]p2: 4875 // The names of the members of an anonymous union shall be 4876 // distinct from the names of any other entity in the 4877 // scope in which the anonymous union is declared. 4878 Invalid = true; 4879 } else { 4880 // C++ [class.union]p2: 4881 // For the purpose of name lookup, after the anonymous union 4882 // definition, the members of the anonymous union are 4883 // considered to have been defined in the scope in which the 4884 // anonymous union is declared. 4885 unsigned OldChainingSize = Chaining.size(); 4886 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4887 Chaining.append(IF->chain_begin(), IF->chain_end()); 4888 else 4889 Chaining.push_back(VD); 4890 4891 assert(Chaining.size() >= 2); 4892 NamedDecl **NamedChain = 4893 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4894 for (unsigned i = 0; i < Chaining.size(); i++) 4895 NamedChain[i] = Chaining[i]; 4896 4897 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4898 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4899 VD->getType(), {NamedChain, Chaining.size()}); 4900 4901 for (const auto *Attr : VD->attrs()) 4902 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4903 4904 IndirectField->setAccess(AS); 4905 IndirectField->setImplicit(); 4906 SemaRef.PushOnScopeChains(IndirectField, S); 4907 4908 // That includes picking up the appropriate access specifier. 4909 if (AS != AS_none) IndirectField->setAccess(AS); 4910 4911 Chaining.resize(OldChainingSize); 4912 } 4913 } 4914 } 4915 4916 return Invalid; 4917 } 4918 4919 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4920 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4921 /// illegal input values are mapped to SC_None. 4922 static StorageClass 4923 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4924 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4925 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4926 "Parser allowed 'typedef' as storage class VarDecl."); 4927 switch (StorageClassSpec) { 4928 case DeclSpec::SCS_unspecified: return SC_None; 4929 case DeclSpec::SCS_extern: 4930 if (DS.isExternInLinkageSpec()) 4931 return SC_None; 4932 return SC_Extern; 4933 case DeclSpec::SCS_static: return SC_Static; 4934 case DeclSpec::SCS_auto: return SC_Auto; 4935 case DeclSpec::SCS_register: return SC_Register; 4936 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4937 // Illegal SCSs map to None: error reporting is up to the caller. 4938 case DeclSpec::SCS_mutable: // Fall through. 4939 case DeclSpec::SCS_typedef: return SC_None; 4940 } 4941 llvm_unreachable("unknown storage class specifier"); 4942 } 4943 4944 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4945 assert(Record->hasInClassInitializer()); 4946 4947 for (const auto *I : Record->decls()) { 4948 const auto *FD = dyn_cast<FieldDecl>(I); 4949 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4950 FD = IFD->getAnonField(); 4951 if (FD && FD->hasInClassInitializer()) 4952 return FD->getLocation(); 4953 } 4954 4955 llvm_unreachable("couldn't find in-class initializer"); 4956 } 4957 4958 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4959 SourceLocation DefaultInitLoc) { 4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4961 return; 4962 4963 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4964 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4965 } 4966 4967 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4968 CXXRecordDecl *AnonUnion) { 4969 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4970 return; 4971 4972 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4973 } 4974 4975 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4976 /// anonymous structure or union. Anonymous unions are a C++ feature 4977 /// (C++ [class.union]) and a C11 feature; anonymous structures 4978 /// are a C11 feature and GNU C++ extension. 4979 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4980 AccessSpecifier AS, 4981 RecordDecl *Record, 4982 const PrintingPolicy &Policy) { 4983 DeclContext *Owner = Record->getDeclContext(); 4984 4985 // Diagnose whether this anonymous struct/union is an extension. 4986 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4987 Diag(Record->getLocation(), diag::ext_anonymous_union); 4988 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4989 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4990 else if (!Record->isUnion() && !getLangOpts().C11) 4991 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4992 4993 // C and C++ require different kinds of checks for anonymous 4994 // structs/unions. 4995 bool Invalid = false; 4996 if (getLangOpts().CPlusPlus) { 4997 const char *PrevSpec = nullptr; 4998 if (Record->isUnion()) { 4999 // C++ [class.union]p6: 5000 // C++17 [class.union.anon]p2: 5001 // Anonymous unions declared in a named namespace or in the 5002 // global namespace shall be declared static. 5003 unsigned DiagID; 5004 DeclContext *OwnerScope = Owner->getRedeclContext(); 5005 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5006 (OwnerScope->isTranslationUnit() || 5007 (OwnerScope->isNamespace() && 5008 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5009 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5010 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5011 5012 // Recover by adding 'static'. 5013 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5014 PrevSpec, DiagID, Policy); 5015 } 5016 // C++ [class.union]p6: 5017 // A storage class is not allowed in a declaration of an 5018 // anonymous union in a class scope. 5019 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5020 isa<RecordDecl>(Owner)) { 5021 Diag(DS.getStorageClassSpecLoc(), 5022 diag::err_anonymous_union_with_storage_spec) 5023 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5024 5025 // Recover by removing the storage specifier. 5026 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5027 SourceLocation(), 5028 PrevSpec, DiagID, Context.getPrintingPolicy()); 5029 } 5030 } 5031 5032 // Ignore const/volatile/restrict qualifiers. 5033 if (DS.getTypeQualifiers()) { 5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5035 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5036 << Record->isUnion() << "const" 5037 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5038 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5039 Diag(DS.getVolatileSpecLoc(), 5040 diag::ext_anonymous_struct_union_qualified) 5041 << Record->isUnion() << "volatile" 5042 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5044 Diag(DS.getRestrictSpecLoc(), 5045 diag::ext_anonymous_struct_union_qualified) 5046 << Record->isUnion() << "restrict" 5047 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5049 Diag(DS.getAtomicSpecLoc(), 5050 diag::ext_anonymous_struct_union_qualified) 5051 << Record->isUnion() << "_Atomic" 5052 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5053 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5054 Diag(DS.getUnalignedSpecLoc(), 5055 diag::ext_anonymous_struct_union_qualified) 5056 << Record->isUnion() << "__unaligned" 5057 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5058 5059 DS.ClearTypeQualifiers(); 5060 } 5061 5062 // C++ [class.union]p2: 5063 // The member-specification of an anonymous union shall only 5064 // define non-static data members. [Note: nested types and 5065 // functions cannot be declared within an anonymous union. ] 5066 for (auto *Mem : Record->decls()) { 5067 // Ignore invalid declarations; we already diagnosed them. 5068 if (Mem->isInvalidDecl()) 5069 continue; 5070 5071 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5072 // C++ [class.union]p3: 5073 // An anonymous union shall not have private or protected 5074 // members (clause 11). 5075 assert(FD->getAccess() != AS_none); 5076 if (FD->getAccess() != AS_public) { 5077 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5078 << Record->isUnion() << (FD->getAccess() == AS_protected); 5079 Invalid = true; 5080 } 5081 5082 // C++ [class.union]p1 5083 // An object of a class with a non-trivial constructor, a non-trivial 5084 // copy constructor, a non-trivial destructor, or a non-trivial copy 5085 // assignment operator cannot be a member of a union, nor can an 5086 // array of such objects. 5087 if (CheckNontrivialField(FD)) 5088 Invalid = true; 5089 } else if (Mem->isImplicit()) { 5090 // Any implicit members are fine. 5091 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5092 // This is a type that showed up in an 5093 // elaborated-type-specifier inside the anonymous struct or 5094 // union, but which actually declares a type outside of the 5095 // anonymous struct or union. It's okay. 5096 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5097 if (!MemRecord->isAnonymousStructOrUnion() && 5098 MemRecord->getDeclName()) { 5099 // Visual C++ allows type definition in anonymous struct or union. 5100 if (getLangOpts().MicrosoftExt) 5101 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5102 << Record->isUnion(); 5103 else { 5104 // This is a nested type declaration. 5105 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5106 << Record->isUnion(); 5107 Invalid = true; 5108 } 5109 } else { 5110 // This is an anonymous type definition within another anonymous type. 5111 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5112 // not part of standard C++. 5113 Diag(MemRecord->getLocation(), 5114 diag::ext_anonymous_record_with_anonymous_type) 5115 << Record->isUnion(); 5116 } 5117 } else if (isa<AccessSpecDecl>(Mem)) { 5118 // Any access specifier is fine. 5119 } else if (isa<StaticAssertDecl>(Mem)) { 5120 // In C++1z, static_assert declarations are also fine. 5121 } else { 5122 // We have something that isn't a non-static data 5123 // member. Complain about it. 5124 unsigned DK = diag::err_anonymous_record_bad_member; 5125 if (isa<TypeDecl>(Mem)) 5126 DK = diag::err_anonymous_record_with_type; 5127 else if (isa<FunctionDecl>(Mem)) 5128 DK = diag::err_anonymous_record_with_function; 5129 else if (isa<VarDecl>(Mem)) 5130 DK = diag::err_anonymous_record_with_static; 5131 5132 // Visual C++ allows type definition in anonymous struct or union. 5133 if (getLangOpts().MicrosoftExt && 5134 DK == diag::err_anonymous_record_with_type) 5135 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5136 << Record->isUnion(); 5137 else { 5138 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5139 Invalid = true; 5140 } 5141 } 5142 } 5143 5144 // C++11 [class.union]p8 (DR1460): 5145 // At most one variant member of a union may have a 5146 // brace-or-equal-initializer. 5147 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5148 Owner->isRecord()) 5149 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5150 cast<CXXRecordDecl>(Record)); 5151 } 5152 5153 if (!Record->isUnion() && !Owner->isRecord()) { 5154 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5155 << getLangOpts().CPlusPlus; 5156 Invalid = true; 5157 } 5158 5159 // C++ [dcl.dcl]p3: 5160 // [If there are no declarators], and except for the declaration of an 5161 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5162 // names into the program 5163 // C++ [class.mem]p2: 5164 // each such member-declaration shall either declare at least one member 5165 // name of the class or declare at least one unnamed bit-field 5166 // 5167 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5168 if (getLangOpts().CPlusPlus && Record->field_empty()) 5169 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5170 5171 // Mock up a declarator. 5172 Declarator Dc(DS, DeclaratorContext::Member); 5173 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5174 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5175 5176 // Create a declaration for this anonymous struct/union. 5177 NamedDecl *Anon = nullptr; 5178 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5179 Anon = FieldDecl::Create( 5180 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5181 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5182 /*BitWidth=*/nullptr, /*Mutable=*/false, 5183 /*InitStyle=*/ICIS_NoInit); 5184 Anon->setAccess(AS); 5185 ProcessDeclAttributes(S, Anon, Dc); 5186 5187 if (getLangOpts().CPlusPlus) 5188 FieldCollector->Add(cast<FieldDecl>(Anon)); 5189 } else { 5190 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5191 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5192 if (SCSpec == DeclSpec::SCS_mutable) { 5193 // mutable can only appear on non-static class members, so it's always 5194 // an error here 5195 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5196 Invalid = true; 5197 SC = SC_None; 5198 } 5199 5200 assert(DS.getAttributes().empty() && "No attribute expected"); 5201 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5202 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5203 Context.getTypeDeclType(Record), TInfo, SC); 5204 5205 // Default-initialize the implicit variable. This initialization will be 5206 // trivial in almost all cases, except if a union member has an in-class 5207 // initializer: 5208 // union { int n = 0; }; 5209 ActOnUninitializedDecl(Anon); 5210 } 5211 Anon->setImplicit(); 5212 5213 // Mark this as an anonymous struct/union type. 5214 Record->setAnonymousStructOrUnion(true); 5215 5216 // Add the anonymous struct/union object to the current 5217 // context. We'll be referencing this object when we refer to one of 5218 // its members. 5219 Owner->addDecl(Anon); 5220 5221 // Inject the members of the anonymous struct/union into the owning 5222 // context and into the identifier resolver chain for name lookup 5223 // purposes. 5224 SmallVector<NamedDecl*, 2> Chain; 5225 Chain.push_back(Anon); 5226 5227 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5228 Invalid = true; 5229 5230 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5231 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5232 MangleNumberingContext *MCtx; 5233 Decl *ManglingContextDecl; 5234 std::tie(MCtx, ManglingContextDecl) = 5235 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5236 if (MCtx) { 5237 Context.setManglingNumber( 5238 NewVD, MCtx->getManglingNumber( 5239 NewVD, getMSManglingNumber(getLangOpts(), S))); 5240 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5241 } 5242 } 5243 } 5244 5245 if (Invalid) 5246 Anon->setInvalidDecl(); 5247 5248 return Anon; 5249 } 5250 5251 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5252 /// Microsoft C anonymous structure. 5253 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5254 /// Example: 5255 /// 5256 /// struct A { int a; }; 5257 /// struct B { struct A; int b; }; 5258 /// 5259 /// void foo() { 5260 /// B var; 5261 /// var.a = 3; 5262 /// } 5263 /// 5264 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5265 RecordDecl *Record) { 5266 assert(Record && "expected a record!"); 5267 5268 // Mock up a declarator. 5269 Declarator Dc(DS, DeclaratorContext::TypeName); 5270 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5271 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5272 5273 auto *ParentDecl = cast<RecordDecl>(CurContext); 5274 QualType RecTy = Context.getTypeDeclType(Record); 5275 5276 // Create a declaration for this anonymous struct. 5277 NamedDecl *Anon = 5278 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5279 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5280 /*BitWidth=*/nullptr, /*Mutable=*/false, 5281 /*InitStyle=*/ICIS_NoInit); 5282 Anon->setImplicit(); 5283 5284 // Add the anonymous struct object to the current context. 5285 CurContext->addDecl(Anon); 5286 5287 // Inject the members of the anonymous struct into the current 5288 // context and into the identifier resolver chain for name lookup 5289 // purposes. 5290 SmallVector<NamedDecl*, 2> Chain; 5291 Chain.push_back(Anon); 5292 5293 RecordDecl *RecordDef = Record->getDefinition(); 5294 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5295 diag::err_field_incomplete_or_sizeless) || 5296 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5297 AS_none, Chain)) { 5298 Anon->setInvalidDecl(); 5299 ParentDecl->setInvalidDecl(); 5300 } 5301 5302 return Anon; 5303 } 5304 5305 /// GetNameForDeclarator - Determine the full declaration name for the 5306 /// given Declarator. 5307 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5308 return GetNameFromUnqualifiedId(D.getName()); 5309 } 5310 5311 /// Retrieves the declaration name from a parsed unqualified-id. 5312 DeclarationNameInfo 5313 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5314 DeclarationNameInfo NameInfo; 5315 NameInfo.setLoc(Name.StartLocation); 5316 5317 switch (Name.getKind()) { 5318 5319 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5320 case UnqualifiedIdKind::IK_Identifier: 5321 NameInfo.setName(Name.Identifier); 5322 return NameInfo; 5323 5324 case UnqualifiedIdKind::IK_DeductionGuideName: { 5325 // C++ [temp.deduct.guide]p3: 5326 // The simple-template-id shall name a class template specialization. 5327 // The template-name shall be the same identifier as the template-name 5328 // of the simple-template-id. 5329 // These together intend to imply that the template-name shall name a 5330 // class template. 5331 // FIXME: template<typename T> struct X {}; 5332 // template<typename T> using Y = X<T>; 5333 // Y(int) -> Y<int>; 5334 // satisfies these rules but does not name a class template. 5335 TemplateName TN = Name.TemplateName.get().get(); 5336 auto *Template = TN.getAsTemplateDecl(); 5337 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5338 Diag(Name.StartLocation, 5339 diag::err_deduction_guide_name_not_class_template) 5340 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5341 if (Template) 5342 Diag(Template->getLocation(), diag::note_template_decl_here); 5343 return DeclarationNameInfo(); 5344 } 5345 5346 NameInfo.setName( 5347 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5348 return NameInfo; 5349 } 5350 5351 case UnqualifiedIdKind::IK_OperatorFunctionId: 5352 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5353 Name.OperatorFunctionId.Operator)); 5354 NameInfo.setCXXOperatorNameRange(SourceRange( 5355 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5356 return NameInfo; 5357 5358 case UnqualifiedIdKind::IK_LiteralOperatorId: 5359 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5360 Name.Identifier)); 5361 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5362 return NameInfo; 5363 5364 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5365 TypeSourceInfo *TInfo; 5366 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5367 if (Ty.isNull()) 5368 return DeclarationNameInfo(); 5369 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5370 Context.getCanonicalType(Ty))); 5371 NameInfo.setNamedTypeInfo(TInfo); 5372 return NameInfo; 5373 } 5374 5375 case UnqualifiedIdKind::IK_ConstructorName: { 5376 TypeSourceInfo *TInfo; 5377 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5378 if (Ty.isNull()) 5379 return DeclarationNameInfo(); 5380 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5381 Context.getCanonicalType(Ty))); 5382 NameInfo.setNamedTypeInfo(TInfo); 5383 return NameInfo; 5384 } 5385 5386 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5387 // In well-formed code, we can only have a constructor 5388 // template-id that refers to the current context, so go there 5389 // to find the actual type being constructed. 5390 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5391 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5392 return DeclarationNameInfo(); 5393 5394 // Determine the type of the class being constructed. 5395 QualType CurClassType = Context.getTypeDeclType(CurClass); 5396 5397 // FIXME: Check two things: that the template-id names the same type as 5398 // CurClassType, and that the template-id does not occur when the name 5399 // was qualified. 5400 5401 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5402 Context.getCanonicalType(CurClassType))); 5403 // FIXME: should we retrieve TypeSourceInfo? 5404 NameInfo.setNamedTypeInfo(nullptr); 5405 return NameInfo; 5406 } 5407 5408 case UnqualifiedIdKind::IK_DestructorName: { 5409 TypeSourceInfo *TInfo; 5410 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5411 if (Ty.isNull()) 5412 return DeclarationNameInfo(); 5413 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5414 Context.getCanonicalType(Ty))); 5415 NameInfo.setNamedTypeInfo(TInfo); 5416 return NameInfo; 5417 } 5418 5419 case UnqualifiedIdKind::IK_TemplateId: { 5420 TemplateName TName = Name.TemplateId->Template.get(); 5421 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5422 return Context.getNameForTemplate(TName, TNameLoc); 5423 } 5424 5425 } // switch (Name.getKind()) 5426 5427 llvm_unreachable("Unknown name kind"); 5428 } 5429 5430 static QualType getCoreType(QualType Ty) { 5431 do { 5432 if (Ty->isPointerType() || Ty->isReferenceType()) 5433 Ty = Ty->getPointeeType(); 5434 else if (Ty->isArrayType()) 5435 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5436 else 5437 return Ty.withoutLocalFastQualifiers(); 5438 } while (true); 5439 } 5440 5441 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5442 /// and Definition have "nearly" matching parameters. This heuristic is 5443 /// used to improve diagnostics in the case where an out-of-line function 5444 /// definition doesn't match any declaration within the class or namespace. 5445 /// Also sets Params to the list of indices to the parameters that differ 5446 /// between the declaration and the definition. If hasSimilarParameters 5447 /// returns true and Params is empty, then all of the parameters match. 5448 static bool hasSimilarParameters(ASTContext &Context, 5449 FunctionDecl *Declaration, 5450 FunctionDecl *Definition, 5451 SmallVectorImpl<unsigned> &Params) { 5452 Params.clear(); 5453 if (Declaration->param_size() != Definition->param_size()) 5454 return false; 5455 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5456 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5457 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5458 5459 // The parameter types are identical 5460 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5461 continue; 5462 5463 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5464 QualType DefParamBaseTy = getCoreType(DefParamTy); 5465 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5466 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5467 5468 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5469 (DeclTyName && DeclTyName == DefTyName)) 5470 Params.push_back(Idx); 5471 else // The two parameters aren't even close 5472 return false; 5473 } 5474 5475 return true; 5476 } 5477 5478 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5479 /// declarator needs to be rebuilt in the current instantiation. 5480 /// Any bits of declarator which appear before the name are valid for 5481 /// consideration here. That's specifically the type in the decl spec 5482 /// and the base type in any member-pointer chunks. 5483 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5484 DeclarationName Name) { 5485 // The types we specifically need to rebuild are: 5486 // - typenames, typeofs, and decltypes 5487 // - types which will become injected class names 5488 // Of course, we also need to rebuild any type referencing such a 5489 // type. It's safest to just say "dependent", but we call out a 5490 // few cases here. 5491 5492 DeclSpec &DS = D.getMutableDeclSpec(); 5493 switch (DS.getTypeSpecType()) { 5494 case DeclSpec::TST_typename: 5495 case DeclSpec::TST_typeofType: 5496 case DeclSpec::TST_underlyingType: 5497 case DeclSpec::TST_atomic: { 5498 // Grab the type from the parser. 5499 TypeSourceInfo *TSI = nullptr; 5500 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5501 if (T.isNull() || !T->isInstantiationDependentType()) break; 5502 5503 // Make sure there's a type source info. This isn't really much 5504 // of a waste; most dependent types should have type source info 5505 // attached already. 5506 if (!TSI) 5507 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5508 5509 // Rebuild the type in the current instantiation. 5510 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5511 if (!TSI) return true; 5512 5513 // Store the new type back in the decl spec. 5514 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5515 DS.UpdateTypeRep(LocType); 5516 break; 5517 } 5518 5519 case DeclSpec::TST_decltype: 5520 case DeclSpec::TST_typeofExpr: { 5521 Expr *E = DS.getRepAsExpr(); 5522 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5523 if (Result.isInvalid()) return true; 5524 DS.UpdateExprRep(Result.get()); 5525 break; 5526 } 5527 5528 default: 5529 // Nothing to do for these decl specs. 5530 break; 5531 } 5532 5533 // It doesn't matter what order we do this in. 5534 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5535 DeclaratorChunk &Chunk = D.getTypeObject(I); 5536 5537 // The only type information in the declarator which can come 5538 // before the declaration name is the base type of a member 5539 // pointer. 5540 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5541 continue; 5542 5543 // Rebuild the scope specifier in-place. 5544 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5545 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5546 return true; 5547 } 5548 5549 return false; 5550 } 5551 5552 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5553 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5554 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5555 5556 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5557 Dcl && Dcl->getDeclContext()->isFileContext()) 5558 Dcl->setTopLevelDeclInObjCContainer(); 5559 5560 if (getLangOpts().OpenCL) 5561 setCurrentOpenCLExtensionForDecl(Dcl); 5562 5563 return Dcl; 5564 } 5565 5566 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5567 /// If T is the name of a class, then each of the following shall have a 5568 /// name different from T: 5569 /// - every static data member of class T; 5570 /// - every member function of class T 5571 /// - every member of class T that is itself a type; 5572 /// \returns true if the declaration name violates these rules. 5573 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5574 DeclarationNameInfo NameInfo) { 5575 DeclarationName Name = NameInfo.getName(); 5576 5577 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5578 while (Record && Record->isAnonymousStructOrUnion()) 5579 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5580 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5581 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5582 return true; 5583 } 5584 5585 return false; 5586 } 5587 5588 /// Diagnose a declaration whose declarator-id has the given 5589 /// nested-name-specifier. 5590 /// 5591 /// \param SS The nested-name-specifier of the declarator-id. 5592 /// 5593 /// \param DC The declaration context to which the nested-name-specifier 5594 /// resolves. 5595 /// 5596 /// \param Name The name of the entity being declared. 5597 /// 5598 /// \param Loc The location of the name of the entity being declared. 5599 /// 5600 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5601 /// we're declaring an explicit / partial specialization / instantiation. 5602 /// 5603 /// \returns true if we cannot safely recover from this error, false otherwise. 5604 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5605 DeclarationName Name, 5606 SourceLocation Loc, bool IsTemplateId) { 5607 DeclContext *Cur = CurContext; 5608 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5609 Cur = Cur->getParent(); 5610 5611 // If the user provided a superfluous scope specifier that refers back to the 5612 // class in which the entity is already declared, diagnose and ignore it. 5613 // 5614 // class X { 5615 // void X::f(); 5616 // }; 5617 // 5618 // Note, it was once ill-formed to give redundant qualification in all 5619 // contexts, but that rule was removed by DR482. 5620 if (Cur->Equals(DC)) { 5621 if (Cur->isRecord()) { 5622 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5623 : diag::err_member_extra_qualification) 5624 << Name << FixItHint::CreateRemoval(SS.getRange()); 5625 SS.clear(); 5626 } else { 5627 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5628 } 5629 return false; 5630 } 5631 5632 // Check whether the qualifying scope encloses the scope of the original 5633 // declaration. For a template-id, we perform the checks in 5634 // CheckTemplateSpecializationScope. 5635 if (!Cur->Encloses(DC) && !IsTemplateId) { 5636 if (Cur->isRecord()) 5637 Diag(Loc, diag::err_member_qualification) 5638 << Name << SS.getRange(); 5639 else if (isa<TranslationUnitDecl>(DC)) 5640 Diag(Loc, diag::err_invalid_declarator_global_scope) 5641 << Name << SS.getRange(); 5642 else if (isa<FunctionDecl>(Cur)) 5643 Diag(Loc, diag::err_invalid_declarator_in_function) 5644 << Name << SS.getRange(); 5645 else if (isa<BlockDecl>(Cur)) 5646 Diag(Loc, diag::err_invalid_declarator_in_block) 5647 << Name << SS.getRange(); 5648 else 5649 Diag(Loc, diag::err_invalid_declarator_scope) 5650 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5651 5652 return true; 5653 } 5654 5655 if (Cur->isRecord()) { 5656 // Cannot qualify members within a class. 5657 Diag(Loc, diag::err_member_qualification) 5658 << Name << SS.getRange(); 5659 SS.clear(); 5660 5661 // C++ constructors and destructors with incorrect scopes can break 5662 // our AST invariants by having the wrong underlying types. If 5663 // that's the case, then drop this declaration entirely. 5664 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5665 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5666 !Context.hasSameType(Name.getCXXNameType(), 5667 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5668 return true; 5669 5670 return false; 5671 } 5672 5673 // C++11 [dcl.meaning]p1: 5674 // [...] "The nested-name-specifier of the qualified declarator-id shall 5675 // not begin with a decltype-specifer" 5676 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5677 while (SpecLoc.getPrefix()) 5678 SpecLoc = SpecLoc.getPrefix(); 5679 if (dyn_cast_or_null<DecltypeType>( 5680 SpecLoc.getNestedNameSpecifier()->getAsType())) 5681 Diag(Loc, diag::err_decltype_in_declarator) 5682 << SpecLoc.getTypeLoc().getSourceRange(); 5683 5684 return false; 5685 } 5686 5687 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5688 MultiTemplateParamsArg TemplateParamLists) { 5689 // TODO: consider using NameInfo for diagnostic. 5690 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5691 DeclarationName Name = NameInfo.getName(); 5692 5693 // All of these full declarators require an identifier. If it doesn't have 5694 // one, the ParsedFreeStandingDeclSpec action should be used. 5695 if (D.isDecompositionDeclarator()) { 5696 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5697 } else if (!Name) { 5698 if (!D.isInvalidType()) // Reject this if we think it is valid. 5699 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5700 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5701 return nullptr; 5702 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5703 return nullptr; 5704 5705 // The scope passed in may not be a decl scope. Zip up the scope tree until 5706 // we find one that is. 5707 while ((S->getFlags() & Scope::DeclScope) == 0 || 5708 (S->getFlags() & Scope::TemplateParamScope) != 0) 5709 S = S->getParent(); 5710 5711 DeclContext *DC = CurContext; 5712 if (D.getCXXScopeSpec().isInvalid()) 5713 D.setInvalidType(); 5714 else if (D.getCXXScopeSpec().isSet()) { 5715 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5716 UPPC_DeclarationQualifier)) 5717 return nullptr; 5718 5719 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5720 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5721 if (!DC || isa<EnumDecl>(DC)) { 5722 // If we could not compute the declaration context, it's because the 5723 // declaration context is dependent but does not refer to a class, 5724 // class template, or class template partial specialization. Complain 5725 // and return early, to avoid the coming semantic disaster. 5726 Diag(D.getIdentifierLoc(), 5727 diag::err_template_qualified_declarator_no_match) 5728 << D.getCXXScopeSpec().getScopeRep() 5729 << D.getCXXScopeSpec().getRange(); 5730 return nullptr; 5731 } 5732 bool IsDependentContext = DC->isDependentContext(); 5733 5734 if (!IsDependentContext && 5735 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5736 return nullptr; 5737 5738 // If a class is incomplete, do not parse entities inside it. 5739 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5740 Diag(D.getIdentifierLoc(), 5741 diag::err_member_def_undefined_record) 5742 << Name << DC << D.getCXXScopeSpec().getRange(); 5743 return nullptr; 5744 } 5745 if (!D.getDeclSpec().isFriendSpecified()) { 5746 if (diagnoseQualifiedDeclaration( 5747 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5748 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5749 if (DC->isRecord()) 5750 return nullptr; 5751 5752 D.setInvalidType(); 5753 } 5754 } 5755 5756 // Check whether we need to rebuild the type of the given 5757 // declaration in the current instantiation. 5758 if (EnteringContext && IsDependentContext && 5759 TemplateParamLists.size() != 0) { 5760 ContextRAII SavedContext(*this, DC); 5761 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5762 D.setInvalidType(); 5763 } 5764 } 5765 5766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5767 QualType R = TInfo->getType(); 5768 5769 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5770 UPPC_DeclarationType)) 5771 D.setInvalidType(); 5772 5773 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5774 forRedeclarationInCurContext()); 5775 5776 // See if this is a redefinition of a variable in the same scope. 5777 if (!D.getCXXScopeSpec().isSet()) { 5778 bool IsLinkageLookup = false; 5779 bool CreateBuiltins = false; 5780 5781 // If the declaration we're planning to build will be a function 5782 // or object with linkage, then look for another declaration with 5783 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5784 // 5785 // If the declaration we're planning to build will be declared with 5786 // external linkage in the translation unit, create any builtin with 5787 // the same name. 5788 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5789 /* Do nothing*/; 5790 else if (CurContext->isFunctionOrMethod() && 5791 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5792 R->isFunctionType())) { 5793 IsLinkageLookup = true; 5794 CreateBuiltins = 5795 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5796 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5797 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5798 CreateBuiltins = true; 5799 5800 if (IsLinkageLookup) { 5801 Previous.clear(LookupRedeclarationWithLinkage); 5802 Previous.setRedeclarationKind(ForExternalRedeclaration); 5803 } 5804 5805 LookupName(Previous, S, CreateBuiltins); 5806 } else { // Something like "int foo::x;" 5807 LookupQualifiedName(Previous, DC); 5808 5809 // C++ [dcl.meaning]p1: 5810 // When the declarator-id is qualified, the declaration shall refer to a 5811 // previously declared member of the class or namespace to which the 5812 // qualifier refers (or, in the case of a namespace, of an element of the 5813 // inline namespace set of that namespace (7.3.1)) or to a specialization 5814 // thereof; [...] 5815 // 5816 // Note that we already checked the context above, and that we do not have 5817 // enough information to make sure that Previous contains the declaration 5818 // we want to match. For example, given: 5819 // 5820 // class X { 5821 // void f(); 5822 // void f(float); 5823 // }; 5824 // 5825 // void X::f(int) { } // ill-formed 5826 // 5827 // In this case, Previous will point to the overload set 5828 // containing the two f's declared in X, but neither of them 5829 // matches. 5830 5831 // C++ [dcl.meaning]p1: 5832 // [...] the member shall not merely have been introduced by a 5833 // using-declaration in the scope of the class or namespace nominated by 5834 // the nested-name-specifier of the declarator-id. 5835 RemoveUsingDecls(Previous); 5836 } 5837 5838 if (Previous.isSingleResult() && 5839 Previous.getFoundDecl()->isTemplateParameter()) { 5840 // Maybe we will complain about the shadowed template parameter. 5841 if (!D.isInvalidType()) 5842 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5843 Previous.getFoundDecl()); 5844 5845 // Just pretend that we didn't see the previous declaration. 5846 Previous.clear(); 5847 } 5848 5849 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5850 // Forget that the previous declaration is the injected-class-name. 5851 Previous.clear(); 5852 5853 // In C++, the previous declaration we find might be a tag type 5854 // (class or enum). In this case, the new declaration will hide the 5855 // tag type. Note that this applies to functions, function templates, and 5856 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5857 if (Previous.isSingleTagDecl() && 5858 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5859 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5860 Previous.clear(); 5861 5862 // Check that there are no default arguments other than in the parameters 5863 // of a function declaration (C++ only). 5864 if (getLangOpts().CPlusPlus) 5865 CheckExtraCXXDefaultArguments(D); 5866 5867 NamedDecl *New; 5868 5869 bool AddToScope = true; 5870 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5871 if (TemplateParamLists.size()) { 5872 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5873 return nullptr; 5874 } 5875 5876 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5877 } else if (R->isFunctionType()) { 5878 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5879 TemplateParamLists, 5880 AddToScope); 5881 } else { 5882 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5883 AddToScope); 5884 } 5885 5886 if (!New) 5887 return nullptr; 5888 5889 // If this has an identifier and is not a function template specialization, 5890 // add it to the scope stack. 5891 if (New->getDeclName() && AddToScope) 5892 PushOnScopeChains(New, S); 5893 5894 if (isInOpenMPDeclareTargetContext()) 5895 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5896 5897 return New; 5898 } 5899 5900 /// Helper method to turn variable array types into constant array 5901 /// types in certain situations which would otherwise be errors (for 5902 /// GCC compatibility). 5903 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5904 ASTContext &Context, 5905 bool &SizeIsNegative, 5906 llvm::APSInt &Oversized) { 5907 // This method tries to turn a variable array into a constant 5908 // array even when the size isn't an ICE. This is necessary 5909 // for compatibility with code that depends on gcc's buggy 5910 // constant expression folding, like struct {char x[(int)(char*)2];} 5911 SizeIsNegative = false; 5912 Oversized = 0; 5913 5914 if (T->isDependentType()) 5915 return QualType(); 5916 5917 QualifierCollector Qs; 5918 const Type *Ty = Qs.strip(T); 5919 5920 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5921 QualType Pointee = PTy->getPointeeType(); 5922 QualType FixedType = 5923 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5924 Oversized); 5925 if (FixedType.isNull()) return FixedType; 5926 FixedType = Context.getPointerType(FixedType); 5927 return Qs.apply(Context, FixedType); 5928 } 5929 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5930 QualType Inner = PTy->getInnerType(); 5931 QualType FixedType = 5932 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5933 Oversized); 5934 if (FixedType.isNull()) return FixedType; 5935 FixedType = Context.getParenType(FixedType); 5936 return Qs.apply(Context, FixedType); 5937 } 5938 5939 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5940 if (!VLATy) 5941 return QualType(); 5942 5943 QualType ElemTy = VLATy->getElementType(); 5944 if (ElemTy->isVariablyModifiedType()) { 5945 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5946 SizeIsNegative, Oversized); 5947 if (ElemTy.isNull()) 5948 return QualType(); 5949 } 5950 5951 Expr::EvalResult Result; 5952 if (!VLATy->getSizeExpr() || 5953 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5954 return QualType(); 5955 5956 llvm::APSInt Res = Result.Val.getInt(); 5957 5958 // Check whether the array size is negative. 5959 if (Res.isSigned() && Res.isNegative()) { 5960 SizeIsNegative = true; 5961 return QualType(); 5962 } 5963 5964 // Check whether the array is too large to be addressed. 5965 unsigned ActiveSizeBits = 5966 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5967 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5968 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5969 : Res.getActiveBits(); 5970 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5971 Oversized = Res; 5972 return QualType(); 5973 } 5974 5975 QualType FoldedArrayType = Context.getConstantArrayType( 5976 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5977 return Qs.apply(Context, FoldedArrayType); 5978 } 5979 5980 static void 5981 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5982 SrcTL = SrcTL.getUnqualifiedLoc(); 5983 DstTL = DstTL.getUnqualifiedLoc(); 5984 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5985 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5986 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5987 DstPTL.getPointeeLoc()); 5988 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5989 return; 5990 } 5991 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5992 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5993 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5994 DstPTL.getInnerLoc()); 5995 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5996 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5997 return; 5998 } 5999 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6000 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6001 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6002 TypeLoc DstElemTL = DstATL.getElementLoc(); 6003 if (VariableArrayTypeLoc SrcElemATL = 6004 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6005 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6006 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6007 } else { 6008 DstElemTL.initializeFullCopy(SrcElemTL); 6009 } 6010 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6011 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6012 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6013 } 6014 6015 /// Helper method to turn variable array types into constant array 6016 /// types in certain situations which would otherwise be errors (for 6017 /// GCC compatibility). 6018 static TypeSourceInfo* 6019 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6020 ASTContext &Context, 6021 bool &SizeIsNegative, 6022 llvm::APSInt &Oversized) { 6023 QualType FixedTy 6024 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6025 SizeIsNegative, Oversized); 6026 if (FixedTy.isNull()) 6027 return nullptr; 6028 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6029 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6030 FixedTInfo->getTypeLoc()); 6031 return FixedTInfo; 6032 } 6033 6034 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6035 /// true if we were successful. 6036 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6037 QualType &T, SourceLocation Loc, 6038 unsigned FailedFoldDiagID) { 6039 bool SizeIsNegative; 6040 llvm::APSInt Oversized; 6041 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6042 TInfo, S.Context, SizeIsNegative, Oversized); 6043 if (FixedTInfo) { 6044 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6045 TInfo = FixedTInfo; 6046 T = FixedTInfo->getType(); 6047 return true; 6048 } 6049 6050 if (SizeIsNegative) 6051 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6052 else if (Oversized.getBoolValue()) 6053 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6054 else if (FailedFoldDiagID) 6055 S.Diag(Loc, FailedFoldDiagID); 6056 return false; 6057 } 6058 6059 /// Register the given locally-scoped extern "C" declaration so 6060 /// that it can be found later for redeclarations. We include any extern "C" 6061 /// declaration that is not visible in the translation unit here, not just 6062 /// function-scope declarations. 6063 void 6064 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6065 if (!getLangOpts().CPlusPlus && 6066 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6067 // Don't need to track declarations in the TU in C. 6068 return; 6069 6070 // Note that we have a locally-scoped external with this name. 6071 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6072 } 6073 6074 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6075 // FIXME: We can have multiple results via __attribute__((overloadable)). 6076 auto Result = Context.getExternCContextDecl()->lookup(Name); 6077 return Result.empty() ? nullptr : *Result.begin(); 6078 } 6079 6080 /// Diagnose function specifiers on a declaration of an identifier that 6081 /// does not identify a function. 6082 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6083 // FIXME: We should probably indicate the identifier in question to avoid 6084 // confusion for constructs like "virtual int a(), b;" 6085 if (DS.isVirtualSpecified()) 6086 Diag(DS.getVirtualSpecLoc(), 6087 diag::err_virtual_non_function); 6088 6089 if (DS.hasExplicitSpecifier()) 6090 Diag(DS.getExplicitSpecLoc(), 6091 diag::err_explicit_non_function); 6092 6093 if (DS.isNoreturnSpecified()) 6094 Diag(DS.getNoreturnSpecLoc(), 6095 diag::err_noreturn_non_function); 6096 } 6097 6098 NamedDecl* 6099 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6100 TypeSourceInfo *TInfo, LookupResult &Previous) { 6101 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6102 if (D.getCXXScopeSpec().isSet()) { 6103 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6104 << D.getCXXScopeSpec().getRange(); 6105 D.setInvalidType(); 6106 // Pretend we didn't see the scope specifier. 6107 DC = CurContext; 6108 Previous.clear(); 6109 } 6110 6111 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6112 6113 if (D.getDeclSpec().isInlineSpecified()) 6114 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6115 << getLangOpts().CPlusPlus17; 6116 if (D.getDeclSpec().hasConstexprSpecifier()) 6117 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6118 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6119 6120 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6121 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6122 Diag(D.getName().StartLocation, 6123 diag::err_deduction_guide_invalid_specifier) 6124 << "typedef"; 6125 else 6126 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6127 << D.getName().getSourceRange(); 6128 return nullptr; 6129 } 6130 6131 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6132 if (!NewTD) return nullptr; 6133 6134 // Handle attributes prior to checking for duplicates in MergeVarDecl 6135 ProcessDeclAttributes(S, NewTD, D); 6136 6137 CheckTypedefForVariablyModifiedType(S, NewTD); 6138 6139 bool Redeclaration = D.isRedeclaration(); 6140 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6141 D.setRedeclaration(Redeclaration); 6142 return ND; 6143 } 6144 6145 void 6146 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6147 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6148 // then it shall have block scope. 6149 // Note that variably modified types must be fixed before merging the decl so 6150 // that redeclarations will match. 6151 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6152 QualType T = TInfo->getType(); 6153 if (T->isVariablyModifiedType()) { 6154 setFunctionHasBranchProtectedScope(); 6155 6156 if (S->getFnParent() == nullptr) { 6157 bool SizeIsNegative; 6158 llvm::APSInt Oversized; 6159 TypeSourceInfo *FixedTInfo = 6160 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6161 SizeIsNegative, 6162 Oversized); 6163 if (FixedTInfo) { 6164 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6165 NewTD->setTypeSourceInfo(FixedTInfo); 6166 } else { 6167 if (SizeIsNegative) 6168 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6169 else if (T->isVariableArrayType()) 6170 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6171 else if (Oversized.getBoolValue()) 6172 Diag(NewTD->getLocation(), diag::err_array_too_large) 6173 << Oversized.toString(10); 6174 else 6175 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6176 NewTD->setInvalidDecl(); 6177 } 6178 } 6179 } 6180 } 6181 6182 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6183 /// declares a typedef-name, either using the 'typedef' type specifier or via 6184 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6185 NamedDecl* 6186 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6187 LookupResult &Previous, bool &Redeclaration) { 6188 6189 // Find the shadowed declaration before filtering for scope. 6190 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6191 6192 // Merge the decl with the existing one if appropriate. If the decl is 6193 // in an outer scope, it isn't the same thing. 6194 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6195 /*AllowInlineNamespace*/false); 6196 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6197 if (!Previous.empty()) { 6198 Redeclaration = true; 6199 MergeTypedefNameDecl(S, NewTD, Previous); 6200 } else { 6201 inferGslPointerAttribute(NewTD); 6202 } 6203 6204 if (ShadowedDecl && !Redeclaration) 6205 CheckShadow(NewTD, ShadowedDecl, Previous); 6206 6207 // If this is the C FILE type, notify the AST context. 6208 if (IdentifierInfo *II = NewTD->getIdentifier()) 6209 if (!NewTD->isInvalidDecl() && 6210 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6211 if (II->isStr("FILE")) 6212 Context.setFILEDecl(NewTD); 6213 else if (II->isStr("jmp_buf")) 6214 Context.setjmp_bufDecl(NewTD); 6215 else if (II->isStr("sigjmp_buf")) 6216 Context.setsigjmp_bufDecl(NewTD); 6217 else if (II->isStr("ucontext_t")) 6218 Context.setucontext_tDecl(NewTD); 6219 } 6220 6221 return NewTD; 6222 } 6223 6224 /// Determines whether the given declaration is an out-of-scope 6225 /// previous declaration. 6226 /// 6227 /// This routine should be invoked when name lookup has found a 6228 /// previous declaration (PrevDecl) that is not in the scope where a 6229 /// new declaration by the same name is being introduced. If the new 6230 /// declaration occurs in a local scope, previous declarations with 6231 /// linkage may still be considered previous declarations (C99 6232 /// 6.2.2p4-5, C++ [basic.link]p6). 6233 /// 6234 /// \param PrevDecl the previous declaration found by name 6235 /// lookup 6236 /// 6237 /// \param DC the context in which the new declaration is being 6238 /// declared. 6239 /// 6240 /// \returns true if PrevDecl is an out-of-scope previous declaration 6241 /// for a new delcaration with the same name. 6242 static bool 6243 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6244 ASTContext &Context) { 6245 if (!PrevDecl) 6246 return false; 6247 6248 if (!PrevDecl->hasLinkage()) 6249 return false; 6250 6251 if (Context.getLangOpts().CPlusPlus) { 6252 // C++ [basic.link]p6: 6253 // If there is a visible declaration of an entity with linkage 6254 // having the same name and type, ignoring entities declared 6255 // outside the innermost enclosing namespace scope, the block 6256 // scope declaration declares that same entity and receives the 6257 // linkage of the previous declaration. 6258 DeclContext *OuterContext = DC->getRedeclContext(); 6259 if (!OuterContext->isFunctionOrMethod()) 6260 // This rule only applies to block-scope declarations. 6261 return false; 6262 6263 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6264 if (PrevOuterContext->isRecord()) 6265 // We found a member function: ignore it. 6266 return false; 6267 6268 // Find the innermost enclosing namespace for the new and 6269 // previous declarations. 6270 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6271 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6272 6273 // The previous declaration is in a different namespace, so it 6274 // isn't the same function. 6275 if (!OuterContext->Equals(PrevOuterContext)) 6276 return false; 6277 } 6278 6279 return true; 6280 } 6281 6282 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6283 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6284 if (!SS.isSet()) return; 6285 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6286 } 6287 6288 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6289 QualType type = decl->getType(); 6290 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6291 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6292 // Various kinds of declaration aren't allowed to be __autoreleasing. 6293 unsigned kind = -1U; 6294 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6295 if (var->hasAttr<BlocksAttr>()) 6296 kind = 0; // __block 6297 else if (!var->hasLocalStorage()) 6298 kind = 1; // global 6299 } else if (isa<ObjCIvarDecl>(decl)) { 6300 kind = 3; // ivar 6301 } else if (isa<FieldDecl>(decl)) { 6302 kind = 2; // field 6303 } 6304 6305 if (kind != -1U) { 6306 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6307 << kind; 6308 } 6309 } else if (lifetime == Qualifiers::OCL_None) { 6310 // Try to infer lifetime. 6311 if (!type->isObjCLifetimeType()) 6312 return false; 6313 6314 lifetime = type->getObjCARCImplicitLifetime(); 6315 type = Context.getLifetimeQualifiedType(type, lifetime); 6316 decl->setType(type); 6317 } 6318 6319 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6320 // Thread-local variables cannot have lifetime. 6321 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6322 var->getTLSKind()) { 6323 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6324 << var->getType(); 6325 return true; 6326 } 6327 } 6328 6329 return false; 6330 } 6331 6332 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6333 if (Decl->getType().hasAddressSpace()) 6334 return; 6335 if (Decl->getType()->isDependentType()) 6336 return; 6337 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6338 QualType Type = Var->getType(); 6339 if (Type->isSamplerT() || Type->isVoidType()) 6340 return; 6341 LangAS ImplAS = LangAS::opencl_private; 6342 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6343 Var->hasGlobalStorage()) 6344 ImplAS = LangAS::opencl_global; 6345 // If the original type from a decayed type is an array type and that array 6346 // type has no address space yet, deduce it now. 6347 if (auto DT = dyn_cast<DecayedType>(Type)) { 6348 auto OrigTy = DT->getOriginalType(); 6349 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6350 // Add the address space to the original array type and then propagate 6351 // that to the element type through `getAsArrayType`. 6352 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6353 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6354 // Re-generate the decayed type. 6355 Type = Context.getDecayedType(OrigTy); 6356 } 6357 } 6358 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6359 // Apply any qualifiers (including address space) from the array type to 6360 // the element type. This implements C99 6.7.3p8: "If the specification of 6361 // an array type includes any type qualifiers, the element type is so 6362 // qualified, not the array type." 6363 if (Type->isArrayType()) 6364 Type = QualType(Context.getAsArrayType(Type), 0); 6365 Decl->setType(Type); 6366 } 6367 } 6368 6369 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6370 // Ensure that an auto decl is deduced otherwise the checks below might cache 6371 // the wrong linkage. 6372 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6373 6374 // 'weak' only applies to declarations with external linkage. 6375 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6376 if (!ND.isExternallyVisible()) { 6377 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6378 ND.dropAttr<WeakAttr>(); 6379 } 6380 } 6381 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6382 if (ND.isExternallyVisible()) { 6383 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6384 ND.dropAttr<WeakRefAttr>(); 6385 ND.dropAttr<AliasAttr>(); 6386 } 6387 } 6388 6389 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6390 if (VD->hasInit()) { 6391 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6392 assert(VD->isThisDeclarationADefinition() && 6393 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6394 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6395 VD->dropAttr<AliasAttr>(); 6396 } 6397 } 6398 } 6399 6400 // 'selectany' only applies to externally visible variable declarations. 6401 // It does not apply to functions. 6402 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6403 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6404 S.Diag(Attr->getLocation(), 6405 diag::err_attribute_selectany_non_extern_data); 6406 ND.dropAttr<SelectAnyAttr>(); 6407 } 6408 } 6409 6410 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6411 auto *VD = dyn_cast<VarDecl>(&ND); 6412 bool IsAnonymousNS = false; 6413 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6414 if (VD) { 6415 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6416 while (NS && !IsAnonymousNS) { 6417 IsAnonymousNS = NS->isAnonymousNamespace(); 6418 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6419 } 6420 } 6421 // dll attributes require external linkage. Static locals may have external 6422 // linkage but still cannot be explicitly imported or exported. 6423 // In Microsoft mode, a variable defined in anonymous namespace must have 6424 // external linkage in order to be exported. 6425 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6426 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6427 (!AnonNSInMicrosoftMode && 6428 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6429 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6430 << &ND << Attr; 6431 ND.setInvalidDecl(); 6432 } 6433 } 6434 6435 // Virtual functions cannot be marked as 'notail'. 6436 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6437 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6438 if (MD->isVirtual()) { 6439 S.Diag(ND.getLocation(), 6440 diag::err_invalid_attribute_on_virtual_function) 6441 << Attr; 6442 ND.dropAttr<NotTailCalledAttr>(); 6443 } 6444 6445 // Check the attributes on the function type, if any. 6446 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6447 // Don't declare this variable in the second operand of the for-statement; 6448 // GCC miscompiles that by ending its lifetime before evaluating the 6449 // third operand. See gcc.gnu.org/PR86769. 6450 AttributedTypeLoc ATL; 6451 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6452 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6453 TL = ATL.getModifiedLoc()) { 6454 // The [[lifetimebound]] attribute can be applied to the implicit object 6455 // parameter of a non-static member function (other than a ctor or dtor) 6456 // by applying it to the function type. 6457 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6458 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6459 if (!MD || MD->isStatic()) { 6460 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6461 << !MD << A->getRange(); 6462 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6463 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6464 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6465 } 6466 } 6467 } 6468 } 6469 } 6470 6471 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6472 NamedDecl *NewDecl, 6473 bool IsSpecialization, 6474 bool IsDefinition) { 6475 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6476 return; 6477 6478 bool IsTemplate = false; 6479 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6480 OldDecl = OldTD->getTemplatedDecl(); 6481 IsTemplate = true; 6482 if (!IsSpecialization) 6483 IsDefinition = false; 6484 } 6485 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6486 NewDecl = NewTD->getTemplatedDecl(); 6487 IsTemplate = true; 6488 } 6489 6490 if (!OldDecl || !NewDecl) 6491 return; 6492 6493 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6494 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6495 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6496 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6497 6498 // dllimport and dllexport are inheritable attributes so we have to exclude 6499 // inherited attribute instances. 6500 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6501 (NewExportAttr && !NewExportAttr->isInherited()); 6502 6503 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6504 // the only exception being explicit specializations. 6505 // Implicitly generated declarations are also excluded for now because there 6506 // is no other way to switch these to use dllimport or dllexport. 6507 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6508 6509 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6510 // Allow with a warning for free functions and global variables. 6511 bool JustWarn = false; 6512 if (!OldDecl->isCXXClassMember()) { 6513 auto *VD = dyn_cast<VarDecl>(OldDecl); 6514 if (VD && !VD->getDescribedVarTemplate()) 6515 JustWarn = true; 6516 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6517 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6518 JustWarn = true; 6519 } 6520 6521 // We cannot change a declaration that's been used because IR has already 6522 // been emitted. Dllimported functions will still work though (modulo 6523 // address equality) as they can use the thunk. 6524 if (OldDecl->isUsed()) 6525 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6526 JustWarn = false; 6527 6528 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6529 : diag::err_attribute_dll_redeclaration; 6530 S.Diag(NewDecl->getLocation(), DiagID) 6531 << NewDecl 6532 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6533 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6534 if (!JustWarn) { 6535 NewDecl->setInvalidDecl(); 6536 return; 6537 } 6538 } 6539 6540 // A redeclaration is not allowed to drop a dllimport attribute, the only 6541 // exceptions being inline function definitions (except for function 6542 // templates), local extern declarations, qualified friend declarations or 6543 // special MSVC extension: in the last case, the declaration is treated as if 6544 // it were marked dllexport. 6545 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6546 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6547 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6548 // Ignore static data because out-of-line definitions are diagnosed 6549 // separately. 6550 IsStaticDataMember = VD->isStaticDataMember(); 6551 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6552 VarDecl::DeclarationOnly; 6553 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6554 IsInline = FD->isInlined(); 6555 IsQualifiedFriend = FD->getQualifier() && 6556 FD->getFriendObjectKind() == Decl::FOK_Declared; 6557 } 6558 6559 if (OldImportAttr && !HasNewAttr && 6560 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6561 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6562 if (IsMicrosoftABI && IsDefinition) { 6563 S.Diag(NewDecl->getLocation(), 6564 diag::warn_redeclaration_without_import_attribute) 6565 << NewDecl; 6566 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6567 NewDecl->dropAttr<DLLImportAttr>(); 6568 NewDecl->addAttr( 6569 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6570 } else { 6571 S.Diag(NewDecl->getLocation(), 6572 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6573 << NewDecl << OldImportAttr; 6574 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6575 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6576 OldDecl->dropAttr<DLLImportAttr>(); 6577 NewDecl->dropAttr<DLLImportAttr>(); 6578 } 6579 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6580 // In MinGW, seeing a function declared inline drops the dllimport 6581 // attribute. 6582 OldDecl->dropAttr<DLLImportAttr>(); 6583 NewDecl->dropAttr<DLLImportAttr>(); 6584 S.Diag(NewDecl->getLocation(), 6585 diag::warn_dllimport_dropped_from_inline_function) 6586 << NewDecl << OldImportAttr; 6587 } 6588 6589 // A specialization of a class template member function is processed here 6590 // since it's a redeclaration. If the parent class is dllexport, the 6591 // specialization inherits that attribute. This doesn't happen automatically 6592 // since the parent class isn't instantiated until later. 6593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6594 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6595 !NewImportAttr && !NewExportAttr) { 6596 if (const DLLExportAttr *ParentExportAttr = 6597 MD->getParent()->getAttr<DLLExportAttr>()) { 6598 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6599 NewAttr->setInherited(true); 6600 NewDecl->addAttr(NewAttr); 6601 } 6602 } 6603 } 6604 } 6605 6606 /// Given that we are within the definition of the given function, 6607 /// will that definition behave like C99's 'inline', where the 6608 /// definition is discarded except for optimization purposes? 6609 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6610 // Try to avoid calling GetGVALinkageForFunction. 6611 6612 // All cases of this require the 'inline' keyword. 6613 if (!FD->isInlined()) return false; 6614 6615 // This is only possible in C++ with the gnu_inline attribute. 6616 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6617 return false; 6618 6619 // Okay, go ahead and call the relatively-more-expensive function. 6620 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6621 } 6622 6623 /// Determine whether a variable is extern "C" prior to attaching 6624 /// an initializer. We can't just call isExternC() here, because that 6625 /// will also compute and cache whether the declaration is externally 6626 /// visible, which might change when we attach the initializer. 6627 /// 6628 /// This can only be used if the declaration is known to not be a 6629 /// redeclaration of an internal linkage declaration. 6630 /// 6631 /// For instance: 6632 /// 6633 /// auto x = []{}; 6634 /// 6635 /// Attaching the initializer here makes this declaration not externally 6636 /// visible, because its type has internal linkage. 6637 /// 6638 /// FIXME: This is a hack. 6639 template<typename T> 6640 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6641 if (S.getLangOpts().CPlusPlus) { 6642 // In C++, the overloadable attribute negates the effects of extern "C". 6643 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6644 return false; 6645 6646 // So do CUDA's host/device attributes. 6647 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6648 D->template hasAttr<CUDAHostAttr>())) 6649 return false; 6650 } 6651 return D->isExternC(); 6652 } 6653 6654 static bool shouldConsiderLinkage(const VarDecl *VD) { 6655 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6656 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6657 isa<OMPDeclareMapperDecl>(DC)) 6658 return VD->hasExternalStorage(); 6659 if (DC->isFileContext()) 6660 return true; 6661 if (DC->isRecord()) 6662 return false; 6663 if (isa<RequiresExprBodyDecl>(DC)) 6664 return false; 6665 llvm_unreachable("Unexpected context"); 6666 } 6667 6668 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6669 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6670 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6671 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6672 return true; 6673 if (DC->isRecord()) 6674 return false; 6675 llvm_unreachable("Unexpected context"); 6676 } 6677 6678 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6679 ParsedAttr::Kind Kind) { 6680 // Check decl attributes on the DeclSpec. 6681 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6682 return true; 6683 6684 // Walk the declarator structure, checking decl attributes that were in a type 6685 // position to the decl itself. 6686 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6687 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6688 return true; 6689 } 6690 6691 // Finally, check attributes on the decl itself. 6692 return PD.getAttributes().hasAttribute(Kind); 6693 } 6694 6695 /// Adjust the \c DeclContext for a function or variable that might be a 6696 /// function-local external declaration. 6697 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6698 if (!DC->isFunctionOrMethod()) 6699 return false; 6700 6701 // If this is a local extern function or variable declared within a function 6702 // template, don't add it into the enclosing namespace scope until it is 6703 // instantiated; it might have a dependent type right now. 6704 if (DC->isDependentContext()) 6705 return true; 6706 6707 // C++11 [basic.link]p7: 6708 // When a block scope declaration of an entity with linkage is not found to 6709 // refer to some other declaration, then that entity is a member of the 6710 // innermost enclosing namespace. 6711 // 6712 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6713 // semantically-enclosing namespace, not a lexically-enclosing one. 6714 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6715 DC = DC->getParent(); 6716 return true; 6717 } 6718 6719 /// Returns true if given declaration has external C language linkage. 6720 static bool isDeclExternC(const Decl *D) { 6721 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6722 return FD->isExternC(); 6723 if (const auto *VD = dyn_cast<VarDecl>(D)) 6724 return VD->isExternC(); 6725 6726 llvm_unreachable("Unknown type of decl!"); 6727 } 6728 /// Returns true if there hasn't been any invalid type diagnosed. 6729 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6730 DeclContext *DC, QualType R) { 6731 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6732 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6733 // argument. 6734 if (R->isImageType() || R->isPipeType()) { 6735 Se.Diag(D.getIdentifierLoc(), 6736 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6737 << R; 6738 D.setInvalidType(); 6739 return false; 6740 } 6741 6742 // OpenCL v1.2 s6.9.r: 6743 // The event type cannot be used to declare a program scope variable. 6744 // OpenCL v2.0 s6.9.q: 6745 // The clk_event_t and reserve_id_t types cannot be declared in program 6746 // scope. 6747 if (NULL == S->getParent()) { 6748 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6749 Se.Diag(D.getIdentifierLoc(), 6750 diag::err_invalid_type_for_program_scope_var) 6751 << R; 6752 D.setInvalidType(); 6753 return false; 6754 } 6755 } 6756 6757 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6758 if (!Se.getOpenCLOptions().isEnabled("__cl_clang_function_pointers")) { 6759 QualType NR = R; 6760 while (NR->isPointerType() || NR->isMemberFunctionPointerType()) { 6761 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType()) { 6762 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6763 D.setInvalidType(); 6764 return false; 6765 } 6766 NR = NR->getPointeeType(); 6767 } 6768 } 6769 6770 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6771 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6772 // half array type (unless the cl_khr_fp16 extension is enabled). 6773 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6774 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6775 D.setInvalidType(); 6776 return false; 6777 } 6778 } 6779 6780 // OpenCL v1.2 s6.9.r: 6781 // The event type cannot be used with the __local, __constant and __global 6782 // address space qualifiers. 6783 if (R->isEventT()) { 6784 if (R.getAddressSpace() != LangAS::opencl_private) { 6785 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6786 D.setInvalidType(); 6787 return false; 6788 } 6789 } 6790 6791 // C++ for OpenCL does not allow the thread_local storage qualifier. 6792 // OpenCL C does not support thread_local either, and 6793 // also reject all other thread storage class specifiers. 6794 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6795 if (TSC != TSCS_unspecified) { 6796 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6797 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6798 diag::err_opencl_unknown_type_specifier) 6799 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6800 << DeclSpec::getSpecifierName(TSC) << 1; 6801 D.setInvalidType(); 6802 return false; 6803 } 6804 6805 if (R->isSamplerT()) { 6806 // OpenCL v1.2 s6.9.b p4: 6807 // The sampler type cannot be used with the __local and __global address 6808 // space qualifiers. 6809 if (R.getAddressSpace() == LangAS::opencl_local || 6810 R.getAddressSpace() == LangAS::opencl_global) { 6811 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6812 D.setInvalidType(); 6813 } 6814 6815 // OpenCL v1.2 s6.12.14.1: 6816 // A global sampler must be declared with either the constant address 6817 // space qualifier or with the const qualifier. 6818 if (DC->isTranslationUnit() && 6819 !(R.getAddressSpace() == LangAS::opencl_constant || 6820 R.isConstQualified())) { 6821 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6822 D.setInvalidType(); 6823 } 6824 if (D.isInvalidType()) 6825 return false; 6826 } 6827 return true; 6828 } 6829 6830 NamedDecl *Sema::ActOnVariableDeclarator( 6831 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6832 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6833 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6834 QualType R = TInfo->getType(); 6835 DeclarationName Name = GetNameForDeclarator(D).getName(); 6836 6837 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6838 6839 if (D.isDecompositionDeclarator()) { 6840 // Take the name of the first declarator as our name for diagnostic 6841 // purposes. 6842 auto &Decomp = D.getDecompositionDeclarator(); 6843 if (!Decomp.bindings().empty()) { 6844 II = Decomp.bindings()[0].Name; 6845 Name = II; 6846 } 6847 } else if (!II) { 6848 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6849 return nullptr; 6850 } 6851 6852 6853 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6854 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6855 6856 // dllimport globals without explicit storage class are treated as extern. We 6857 // have to change the storage class this early to get the right DeclContext. 6858 if (SC == SC_None && !DC->isRecord() && 6859 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6860 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6861 SC = SC_Extern; 6862 6863 DeclContext *OriginalDC = DC; 6864 bool IsLocalExternDecl = SC == SC_Extern && 6865 adjustContextForLocalExternDecl(DC); 6866 6867 if (SCSpec == DeclSpec::SCS_mutable) { 6868 // mutable can only appear on non-static class members, so it's always 6869 // an error here 6870 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6871 D.setInvalidType(); 6872 SC = SC_None; 6873 } 6874 6875 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6876 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6877 D.getDeclSpec().getStorageClassSpecLoc())) { 6878 // In C++11, the 'register' storage class specifier is deprecated. 6879 // Suppress the warning in system macros, it's used in macros in some 6880 // popular C system headers, such as in glibc's htonl() macro. 6881 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6882 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6883 : diag::warn_deprecated_register) 6884 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6885 } 6886 6887 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6888 6889 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6890 // C99 6.9p2: The storage-class specifiers auto and register shall not 6891 // appear in the declaration specifiers in an external declaration. 6892 // Global Register+Asm is a GNU extension we support. 6893 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6894 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6895 D.setInvalidType(); 6896 } 6897 } 6898 6899 // If this variable has a variable-modified type and an initializer, try to 6900 // fold to a constant-sized type. This is otherwise invalid. 6901 if (D.hasInitializer() && R->isVariablyModifiedType()) 6902 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6903 /*DiagID=*/0); 6904 6905 bool IsMemberSpecialization = false; 6906 bool IsVariableTemplateSpecialization = false; 6907 bool IsPartialSpecialization = false; 6908 bool IsVariableTemplate = false; 6909 VarDecl *NewVD = nullptr; 6910 VarTemplateDecl *NewTemplate = nullptr; 6911 TemplateParameterList *TemplateParams = nullptr; 6912 if (!getLangOpts().CPlusPlus) { 6913 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6914 II, R, TInfo, SC); 6915 6916 if (R->getContainedDeducedType()) 6917 ParsingInitForAutoVars.insert(NewVD); 6918 6919 if (D.isInvalidType()) 6920 NewVD->setInvalidDecl(); 6921 6922 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6923 NewVD->hasLocalStorage()) 6924 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6925 NTCUC_AutoVar, NTCUK_Destruct); 6926 } else { 6927 bool Invalid = false; 6928 6929 if (DC->isRecord() && !CurContext->isRecord()) { 6930 // This is an out-of-line definition of a static data member. 6931 switch (SC) { 6932 case SC_None: 6933 break; 6934 case SC_Static: 6935 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6936 diag::err_static_out_of_line) 6937 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6938 break; 6939 case SC_Auto: 6940 case SC_Register: 6941 case SC_Extern: 6942 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6943 // to names of variables declared in a block or to function parameters. 6944 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6945 // of class members 6946 6947 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6948 diag::err_storage_class_for_static_member) 6949 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6950 break; 6951 case SC_PrivateExtern: 6952 llvm_unreachable("C storage class in c++!"); 6953 } 6954 } 6955 6956 if (SC == SC_Static && CurContext->isRecord()) { 6957 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6958 // Walk up the enclosing DeclContexts to check for any that are 6959 // incompatible with static data members. 6960 const DeclContext *FunctionOrMethod = nullptr; 6961 const CXXRecordDecl *AnonStruct = nullptr; 6962 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6963 if (Ctxt->isFunctionOrMethod()) { 6964 FunctionOrMethod = Ctxt; 6965 break; 6966 } 6967 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6968 if (ParentDecl && !ParentDecl->getDeclName()) { 6969 AnonStruct = ParentDecl; 6970 break; 6971 } 6972 } 6973 if (FunctionOrMethod) { 6974 // C++ [class.static.data]p5: A local class shall not have static data 6975 // members. 6976 Diag(D.getIdentifierLoc(), 6977 diag::err_static_data_member_not_allowed_in_local_class) 6978 << Name << RD->getDeclName() << RD->getTagKind(); 6979 } else if (AnonStruct) { 6980 // C++ [class.static.data]p4: Unnamed classes and classes contained 6981 // directly or indirectly within unnamed classes shall not contain 6982 // static data members. 6983 Diag(D.getIdentifierLoc(), 6984 diag::err_static_data_member_not_allowed_in_anon_struct) 6985 << Name << AnonStruct->getTagKind(); 6986 Invalid = true; 6987 } else if (RD->isUnion()) { 6988 // C++98 [class.union]p1: If a union contains a static data member, 6989 // the program is ill-formed. C++11 drops this restriction. 6990 Diag(D.getIdentifierLoc(), 6991 getLangOpts().CPlusPlus11 6992 ? diag::warn_cxx98_compat_static_data_member_in_union 6993 : diag::ext_static_data_member_in_union) << Name; 6994 } 6995 } 6996 } 6997 6998 // Match up the template parameter lists with the scope specifier, then 6999 // determine whether we have a template or a template specialization. 7000 bool InvalidScope = false; 7001 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7002 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7003 D.getCXXScopeSpec(), 7004 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7005 ? D.getName().TemplateId 7006 : nullptr, 7007 TemplateParamLists, 7008 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7009 Invalid |= InvalidScope; 7010 7011 if (TemplateParams) { 7012 if (!TemplateParams->size() && 7013 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7014 // There is an extraneous 'template<>' for this variable. Complain 7015 // about it, but allow the declaration of the variable. 7016 Diag(TemplateParams->getTemplateLoc(), 7017 diag::err_template_variable_noparams) 7018 << II 7019 << SourceRange(TemplateParams->getTemplateLoc(), 7020 TemplateParams->getRAngleLoc()); 7021 TemplateParams = nullptr; 7022 } else { 7023 // Check that we can declare a template here. 7024 if (CheckTemplateDeclScope(S, TemplateParams)) 7025 return nullptr; 7026 7027 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7028 // This is an explicit specialization or a partial specialization. 7029 IsVariableTemplateSpecialization = true; 7030 IsPartialSpecialization = TemplateParams->size() > 0; 7031 } else { // if (TemplateParams->size() > 0) 7032 // This is a template declaration. 7033 IsVariableTemplate = true; 7034 7035 // Only C++1y supports variable templates (N3651). 7036 Diag(D.getIdentifierLoc(), 7037 getLangOpts().CPlusPlus14 7038 ? diag::warn_cxx11_compat_variable_template 7039 : diag::ext_variable_template); 7040 } 7041 } 7042 } else { 7043 // Check that we can declare a member specialization here. 7044 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7045 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7046 return nullptr; 7047 assert((Invalid || 7048 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7049 "should have a 'template<>' for this decl"); 7050 } 7051 7052 if (IsVariableTemplateSpecialization) { 7053 SourceLocation TemplateKWLoc = 7054 TemplateParamLists.size() > 0 7055 ? TemplateParamLists[0]->getTemplateLoc() 7056 : SourceLocation(); 7057 DeclResult Res = ActOnVarTemplateSpecialization( 7058 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7059 IsPartialSpecialization); 7060 if (Res.isInvalid()) 7061 return nullptr; 7062 NewVD = cast<VarDecl>(Res.get()); 7063 AddToScope = false; 7064 } else if (D.isDecompositionDeclarator()) { 7065 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7066 D.getIdentifierLoc(), R, TInfo, SC, 7067 Bindings); 7068 } else 7069 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7070 D.getIdentifierLoc(), II, R, TInfo, SC); 7071 7072 // If this is supposed to be a variable template, create it as such. 7073 if (IsVariableTemplate) { 7074 NewTemplate = 7075 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7076 TemplateParams, NewVD); 7077 NewVD->setDescribedVarTemplate(NewTemplate); 7078 } 7079 7080 // If this decl has an auto type in need of deduction, make a note of the 7081 // Decl so we can diagnose uses of it in its own initializer. 7082 if (R->getContainedDeducedType()) 7083 ParsingInitForAutoVars.insert(NewVD); 7084 7085 if (D.isInvalidType() || Invalid) { 7086 NewVD->setInvalidDecl(); 7087 if (NewTemplate) 7088 NewTemplate->setInvalidDecl(); 7089 } 7090 7091 SetNestedNameSpecifier(*this, NewVD, D); 7092 7093 // If we have any template parameter lists that don't directly belong to 7094 // the variable (matching the scope specifier), store them. 7095 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7096 if (TemplateParamLists.size() > VDTemplateParamLists) 7097 NewVD->setTemplateParameterListsInfo( 7098 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7099 } 7100 7101 if (D.getDeclSpec().isInlineSpecified()) { 7102 if (!getLangOpts().CPlusPlus) { 7103 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7104 << 0; 7105 } else if (CurContext->isFunctionOrMethod()) { 7106 // 'inline' is not allowed on block scope variable declaration. 7107 Diag(D.getDeclSpec().getInlineSpecLoc(), 7108 diag::err_inline_declaration_block_scope) << Name 7109 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7110 } else { 7111 Diag(D.getDeclSpec().getInlineSpecLoc(), 7112 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7113 : diag::ext_inline_variable); 7114 NewVD->setInlineSpecified(); 7115 } 7116 } 7117 7118 // Set the lexical context. If the declarator has a C++ scope specifier, the 7119 // lexical context will be different from the semantic context. 7120 NewVD->setLexicalDeclContext(CurContext); 7121 if (NewTemplate) 7122 NewTemplate->setLexicalDeclContext(CurContext); 7123 7124 if (IsLocalExternDecl) { 7125 if (D.isDecompositionDeclarator()) 7126 for (auto *B : Bindings) 7127 B->setLocalExternDecl(); 7128 else 7129 NewVD->setLocalExternDecl(); 7130 } 7131 7132 bool EmitTLSUnsupportedError = false; 7133 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7134 // C++11 [dcl.stc]p4: 7135 // When thread_local is applied to a variable of block scope the 7136 // storage-class-specifier static is implied if it does not appear 7137 // explicitly. 7138 // Core issue: 'static' is not implied if the variable is declared 7139 // 'extern'. 7140 if (NewVD->hasLocalStorage() && 7141 (SCSpec != DeclSpec::SCS_unspecified || 7142 TSCS != DeclSpec::TSCS_thread_local || 7143 !DC->isFunctionOrMethod())) 7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7145 diag::err_thread_non_global) 7146 << DeclSpec::getSpecifierName(TSCS); 7147 else if (!Context.getTargetInfo().isTLSSupported()) { 7148 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7149 getLangOpts().SYCLIsDevice) { 7150 // Postpone error emission until we've collected attributes required to 7151 // figure out whether it's a host or device variable and whether the 7152 // error should be ignored. 7153 EmitTLSUnsupportedError = true; 7154 // We still need to mark the variable as TLS so it shows up in AST with 7155 // proper storage class for other tools to use even if we're not going 7156 // to emit any code for it. 7157 NewVD->setTSCSpec(TSCS); 7158 } else 7159 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7160 diag::err_thread_unsupported); 7161 } else 7162 NewVD->setTSCSpec(TSCS); 7163 } 7164 7165 switch (D.getDeclSpec().getConstexprSpecifier()) { 7166 case ConstexprSpecKind::Unspecified: 7167 break; 7168 7169 case ConstexprSpecKind::Consteval: 7170 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7171 diag::err_constexpr_wrong_decl_kind) 7172 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7173 LLVM_FALLTHROUGH; 7174 7175 case ConstexprSpecKind::Constexpr: 7176 NewVD->setConstexpr(true); 7177 MaybeAddCUDAConstantAttr(NewVD); 7178 // C++1z [dcl.spec.constexpr]p1: 7179 // A static data member declared with the constexpr specifier is 7180 // implicitly an inline variable. 7181 if (NewVD->isStaticDataMember() && 7182 (getLangOpts().CPlusPlus17 || 7183 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7184 NewVD->setImplicitlyInline(); 7185 break; 7186 7187 case ConstexprSpecKind::Constinit: 7188 if (!NewVD->hasGlobalStorage()) 7189 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7190 diag::err_constinit_local_variable); 7191 else 7192 NewVD->addAttr(ConstInitAttr::Create( 7193 Context, D.getDeclSpec().getConstexprSpecLoc(), 7194 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7195 break; 7196 } 7197 7198 // C99 6.7.4p3 7199 // An inline definition of a function with external linkage shall 7200 // not contain a definition of a modifiable object with static or 7201 // thread storage duration... 7202 // We only apply this when the function is required to be defined 7203 // elsewhere, i.e. when the function is not 'extern inline'. Note 7204 // that a local variable with thread storage duration still has to 7205 // be marked 'static'. Also note that it's possible to get these 7206 // semantics in C++ using __attribute__((gnu_inline)). 7207 if (SC == SC_Static && S->getFnParent() != nullptr && 7208 !NewVD->getType().isConstQualified()) { 7209 FunctionDecl *CurFD = getCurFunctionDecl(); 7210 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7211 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7212 diag::warn_static_local_in_extern_inline); 7213 MaybeSuggestAddingStaticToDecl(CurFD); 7214 } 7215 } 7216 7217 if (D.getDeclSpec().isModulePrivateSpecified()) { 7218 if (IsVariableTemplateSpecialization) 7219 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7220 << (IsPartialSpecialization ? 1 : 0) 7221 << FixItHint::CreateRemoval( 7222 D.getDeclSpec().getModulePrivateSpecLoc()); 7223 else if (IsMemberSpecialization) 7224 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7225 << 2 7226 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7227 else if (NewVD->hasLocalStorage()) 7228 Diag(NewVD->getLocation(), diag::err_module_private_local) 7229 << 0 << NewVD 7230 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7231 << FixItHint::CreateRemoval( 7232 D.getDeclSpec().getModulePrivateSpecLoc()); 7233 else { 7234 NewVD->setModulePrivate(); 7235 if (NewTemplate) 7236 NewTemplate->setModulePrivate(); 7237 for (auto *B : Bindings) 7238 B->setModulePrivate(); 7239 } 7240 } 7241 7242 if (getLangOpts().OpenCL) { 7243 7244 deduceOpenCLAddressSpace(NewVD); 7245 7246 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7247 } 7248 7249 // Handle attributes prior to checking for duplicates in MergeVarDecl 7250 ProcessDeclAttributes(S, NewVD, D); 7251 7252 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7253 getLangOpts().SYCLIsDevice) { 7254 if (EmitTLSUnsupportedError && 7255 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7256 (getLangOpts().OpenMPIsDevice && 7257 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7258 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7259 diag::err_thread_unsupported); 7260 7261 if (EmitTLSUnsupportedError && 7262 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7263 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7264 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7265 // storage [duration]." 7266 if (SC == SC_None && S->getFnParent() != nullptr && 7267 (NewVD->hasAttr<CUDASharedAttr>() || 7268 NewVD->hasAttr<CUDAConstantAttr>())) { 7269 NewVD->setStorageClass(SC_Static); 7270 } 7271 } 7272 7273 // Ensure that dllimport globals without explicit storage class are treated as 7274 // extern. The storage class is set above using parsed attributes. Now we can 7275 // check the VarDecl itself. 7276 assert(!NewVD->hasAttr<DLLImportAttr>() || 7277 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7278 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7279 7280 // In auto-retain/release, infer strong retension for variables of 7281 // retainable type. 7282 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7283 NewVD->setInvalidDecl(); 7284 7285 // Handle GNU asm-label extension (encoded as an attribute). 7286 if (Expr *E = (Expr*)D.getAsmLabel()) { 7287 // The parser guarantees this is a string. 7288 StringLiteral *SE = cast<StringLiteral>(E); 7289 StringRef Label = SE->getString(); 7290 if (S->getFnParent() != nullptr) { 7291 switch (SC) { 7292 case SC_None: 7293 case SC_Auto: 7294 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7295 break; 7296 case SC_Register: 7297 // Local Named register 7298 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7299 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7300 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7301 break; 7302 case SC_Static: 7303 case SC_Extern: 7304 case SC_PrivateExtern: 7305 break; 7306 } 7307 } else if (SC == SC_Register) { 7308 // Global Named register 7309 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7310 const auto &TI = Context.getTargetInfo(); 7311 bool HasSizeMismatch; 7312 7313 if (!TI.isValidGCCRegisterName(Label)) 7314 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7315 else if (!TI.validateGlobalRegisterVariable(Label, 7316 Context.getTypeSize(R), 7317 HasSizeMismatch)) 7318 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7319 else if (HasSizeMismatch) 7320 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7321 } 7322 7323 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7324 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7325 NewVD->setInvalidDecl(true); 7326 } 7327 } 7328 7329 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7330 /*IsLiteralLabel=*/true, 7331 SE->getStrTokenLoc(0))); 7332 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7333 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7334 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7335 if (I != ExtnameUndeclaredIdentifiers.end()) { 7336 if (isDeclExternC(NewVD)) { 7337 NewVD->addAttr(I->second); 7338 ExtnameUndeclaredIdentifiers.erase(I); 7339 } else 7340 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7341 << /*Variable*/1 << NewVD; 7342 } 7343 } 7344 7345 // Find the shadowed declaration before filtering for scope. 7346 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7347 ? getShadowedDeclaration(NewVD, Previous) 7348 : nullptr; 7349 7350 // Don't consider existing declarations that are in a different 7351 // scope and are out-of-semantic-context declarations (if the new 7352 // declaration has linkage). 7353 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7354 D.getCXXScopeSpec().isNotEmpty() || 7355 IsMemberSpecialization || 7356 IsVariableTemplateSpecialization); 7357 7358 // Check whether the previous declaration is in the same block scope. This 7359 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7360 if (getLangOpts().CPlusPlus && 7361 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7362 NewVD->setPreviousDeclInSameBlockScope( 7363 Previous.isSingleResult() && !Previous.isShadowed() && 7364 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7365 7366 if (!getLangOpts().CPlusPlus) { 7367 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7368 } else { 7369 // If this is an explicit specialization of a static data member, check it. 7370 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7371 CheckMemberSpecialization(NewVD, Previous)) 7372 NewVD->setInvalidDecl(); 7373 7374 // Merge the decl with the existing one if appropriate. 7375 if (!Previous.empty()) { 7376 if (Previous.isSingleResult() && 7377 isa<FieldDecl>(Previous.getFoundDecl()) && 7378 D.getCXXScopeSpec().isSet()) { 7379 // The user tried to define a non-static data member 7380 // out-of-line (C++ [dcl.meaning]p1). 7381 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7382 << D.getCXXScopeSpec().getRange(); 7383 Previous.clear(); 7384 NewVD->setInvalidDecl(); 7385 } 7386 } else if (D.getCXXScopeSpec().isSet()) { 7387 // No previous declaration in the qualifying scope. 7388 Diag(D.getIdentifierLoc(), diag::err_no_member) 7389 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7390 << D.getCXXScopeSpec().getRange(); 7391 NewVD->setInvalidDecl(); 7392 } 7393 7394 if (!IsVariableTemplateSpecialization) 7395 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7396 7397 if (NewTemplate) { 7398 VarTemplateDecl *PrevVarTemplate = 7399 NewVD->getPreviousDecl() 7400 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7401 : nullptr; 7402 7403 // Check the template parameter list of this declaration, possibly 7404 // merging in the template parameter list from the previous variable 7405 // template declaration. 7406 if (CheckTemplateParameterList( 7407 TemplateParams, 7408 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7409 : nullptr, 7410 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7411 DC->isDependentContext()) 7412 ? TPC_ClassTemplateMember 7413 : TPC_VarTemplate)) 7414 NewVD->setInvalidDecl(); 7415 7416 // If we are providing an explicit specialization of a static variable 7417 // template, make a note of that. 7418 if (PrevVarTemplate && 7419 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7420 PrevVarTemplate->setMemberSpecialization(); 7421 } 7422 } 7423 7424 // Diagnose shadowed variables iff this isn't a redeclaration. 7425 if (ShadowedDecl && !D.isRedeclaration()) 7426 CheckShadow(NewVD, ShadowedDecl, Previous); 7427 7428 ProcessPragmaWeak(S, NewVD); 7429 7430 // If this is the first declaration of an extern C variable, update 7431 // the map of such variables. 7432 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7433 isIncompleteDeclExternC(*this, NewVD)) 7434 RegisterLocallyScopedExternCDecl(NewVD, S); 7435 7436 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7437 MangleNumberingContext *MCtx; 7438 Decl *ManglingContextDecl; 7439 std::tie(MCtx, ManglingContextDecl) = 7440 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7441 if (MCtx) { 7442 Context.setManglingNumber( 7443 NewVD, MCtx->getManglingNumber( 7444 NewVD, getMSManglingNumber(getLangOpts(), S))); 7445 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7446 } 7447 } 7448 7449 // Special handling of variable named 'main'. 7450 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7451 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7452 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7453 7454 // C++ [basic.start.main]p3 7455 // A program that declares a variable main at global scope is ill-formed. 7456 if (getLangOpts().CPlusPlus) 7457 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7458 7459 // In C, and external-linkage variable named main results in undefined 7460 // behavior. 7461 else if (NewVD->hasExternalFormalLinkage()) 7462 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7463 } 7464 7465 if (D.isRedeclaration() && !Previous.empty()) { 7466 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7467 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7468 D.isFunctionDefinition()); 7469 } 7470 7471 if (NewTemplate) { 7472 if (NewVD->isInvalidDecl()) 7473 NewTemplate->setInvalidDecl(); 7474 ActOnDocumentableDecl(NewTemplate); 7475 return NewTemplate; 7476 } 7477 7478 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7479 CompleteMemberSpecialization(NewVD, Previous); 7480 7481 return NewVD; 7482 } 7483 7484 /// Enum describing the %select options in diag::warn_decl_shadow. 7485 enum ShadowedDeclKind { 7486 SDK_Local, 7487 SDK_Global, 7488 SDK_StaticMember, 7489 SDK_Field, 7490 SDK_Typedef, 7491 SDK_Using 7492 }; 7493 7494 /// Determine what kind of declaration we're shadowing. 7495 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7496 const DeclContext *OldDC) { 7497 if (isa<TypeAliasDecl>(ShadowedDecl)) 7498 return SDK_Using; 7499 else if (isa<TypedefDecl>(ShadowedDecl)) 7500 return SDK_Typedef; 7501 else if (isa<RecordDecl>(OldDC)) 7502 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7503 7504 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7505 } 7506 7507 /// Return the location of the capture if the given lambda captures the given 7508 /// variable \p VD, or an invalid source location otherwise. 7509 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7510 const VarDecl *VD) { 7511 for (const Capture &Capture : LSI->Captures) { 7512 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7513 return Capture.getLocation(); 7514 } 7515 return SourceLocation(); 7516 } 7517 7518 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7519 const LookupResult &R) { 7520 // Only diagnose if we're shadowing an unambiguous field or variable. 7521 if (R.getResultKind() != LookupResult::Found) 7522 return false; 7523 7524 // Return false if warning is ignored. 7525 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7526 } 7527 7528 /// Return the declaration shadowed by the given variable \p D, or null 7529 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7530 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7531 const LookupResult &R) { 7532 if (!shouldWarnIfShadowedDecl(Diags, R)) 7533 return nullptr; 7534 7535 // Don't diagnose declarations at file scope. 7536 if (D->hasGlobalStorage()) 7537 return nullptr; 7538 7539 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7540 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7541 ? ShadowedDecl 7542 : nullptr; 7543 } 7544 7545 /// Return the declaration shadowed by the given typedef \p D, or null 7546 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7547 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7548 const LookupResult &R) { 7549 // Don't warn if typedef declaration is part of a class 7550 if (D->getDeclContext()->isRecord()) 7551 return nullptr; 7552 7553 if (!shouldWarnIfShadowedDecl(Diags, R)) 7554 return nullptr; 7555 7556 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7557 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7558 } 7559 7560 /// Diagnose variable or built-in function shadowing. Implements 7561 /// -Wshadow. 7562 /// 7563 /// This method is called whenever a VarDecl is added to a "useful" 7564 /// scope. 7565 /// 7566 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7567 /// \param R the lookup of the name 7568 /// 7569 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7570 const LookupResult &R) { 7571 DeclContext *NewDC = D->getDeclContext(); 7572 7573 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7574 // Fields are not shadowed by variables in C++ static methods. 7575 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7576 if (MD->isStatic()) 7577 return; 7578 7579 // Fields shadowed by constructor parameters are a special case. Usually 7580 // the constructor initializes the field with the parameter. 7581 if (isa<CXXConstructorDecl>(NewDC)) 7582 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7583 // Remember that this was shadowed so we can either warn about its 7584 // modification or its existence depending on warning settings. 7585 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7586 return; 7587 } 7588 } 7589 7590 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7591 if (shadowedVar->isExternC()) { 7592 // For shadowing external vars, make sure that we point to the global 7593 // declaration, not a locally scoped extern declaration. 7594 for (auto I : shadowedVar->redecls()) 7595 if (I->isFileVarDecl()) { 7596 ShadowedDecl = I; 7597 break; 7598 } 7599 } 7600 7601 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7602 7603 unsigned WarningDiag = diag::warn_decl_shadow; 7604 SourceLocation CaptureLoc; 7605 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7606 isa<CXXMethodDecl>(NewDC)) { 7607 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7608 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7609 if (RD->getLambdaCaptureDefault() == LCD_None) { 7610 // Try to avoid warnings for lambdas with an explicit capture list. 7611 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7612 // Warn only when the lambda captures the shadowed decl explicitly. 7613 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7614 if (CaptureLoc.isInvalid()) 7615 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7616 } else { 7617 // Remember that this was shadowed so we can avoid the warning if the 7618 // shadowed decl isn't captured and the warning settings allow it. 7619 cast<LambdaScopeInfo>(getCurFunction()) 7620 ->ShadowingDecls.push_back( 7621 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7622 return; 7623 } 7624 } 7625 7626 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7627 // A variable can't shadow a local variable in an enclosing scope, if 7628 // they are separated by a non-capturing declaration context. 7629 for (DeclContext *ParentDC = NewDC; 7630 ParentDC && !ParentDC->Equals(OldDC); 7631 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7632 // Only block literals, captured statements, and lambda expressions 7633 // can capture; other scopes don't. 7634 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7635 !isLambdaCallOperator(ParentDC)) { 7636 return; 7637 } 7638 } 7639 } 7640 } 7641 } 7642 7643 // Only warn about certain kinds of shadowing for class members. 7644 if (NewDC && NewDC->isRecord()) { 7645 // In particular, don't warn about shadowing non-class members. 7646 if (!OldDC->isRecord()) 7647 return; 7648 7649 // TODO: should we warn about static data members shadowing 7650 // static data members from base classes? 7651 7652 // TODO: don't diagnose for inaccessible shadowed members. 7653 // This is hard to do perfectly because we might friend the 7654 // shadowing context, but that's just a false negative. 7655 } 7656 7657 7658 DeclarationName Name = R.getLookupName(); 7659 7660 // Emit warning and note. 7661 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7662 return; 7663 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7664 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7665 if (!CaptureLoc.isInvalid()) 7666 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7667 << Name << /*explicitly*/ 1; 7668 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7669 } 7670 7671 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7672 /// when these variables are captured by the lambda. 7673 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7674 for (const auto &Shadow : LSI->ShadowingDecls) { 7675 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7676 // Try to avoid the warning when the shadowed decl isn't captured. 7677 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7678 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7679 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7680 ? diag::warn_decl_shadow_uncaptured_local 7681 : diag::warn_decl_shadow) 7682 << Shadow.VD->getDeclName() 7683 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7684 if (!CaptureLoc.isInvalid()) 7685 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7686 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7687 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7688 } 7689 } 7690 7691 /// Check -Wshadow without the advantage of a previous lookup. 7692 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7693 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7694 return; 7695 7696 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7697 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7698 LookupName(R, S); 7699 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7700 CheckShadow(D, ShadowedDecl, R); 7701 } 7702 7703 /// Check if 'E', which is an expression that is about to be modified, refers 7704 /// to a constructor parameter that shadows a field. 7705 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7706 // Quickly ignore expressions that can't be shadowing ctor parameters. 7707 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7708 return; 7709 E = E->IgnoreParenImpCasts(); 7710 auto *DRE = dyn_cast<DeclRefExpr>(E); 7711 if (!DRE) 7712 return; 7713 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7714 auto I = ShadowingDecls.find(D); 7715 if (I == ShadowingDecls.end()) 7716 return; 7717 const NamedDecl *ShadowedDecl = I->second; 7718 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7719 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7720 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7721 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7722 7723 // Avoid issuing multiple warnings about the same decl. 7724 ShadowingDecls.erase(I); 7725 } 7726 7727 /// Check for conflict between this global or extern "C" declaration and 7728 /// previous global or extern "C" declarations. This is only used in C++. 7729 template<typename T> 7730 static bool checkGlobalOrExternCConflict( 7731 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7732 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7733 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7734 7735 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7736 // The common case: this global doesn't conflict with any extern "C" 7737 // declaration. 7738 return false; 7739 } 7740 7741 if (Prev) { 7742 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7743 // Both the old and new declarations have C language linkage. This is a 7744 // redeclaration. 7745 Previous.clear(); 7746 Previous.addDecl(Prev); 7747 return true; 7748 } 7749 7750 // This is a global, non-extern "C" declaration, and there is a previous 7751 // non-global extern "C" declaration. Diagnose if this is a variable 7752 // declaration. 7753 if (!isa<VarDecl>(ND)) 7754 return false; 7755 } else { 7756 // The declaration is extern "C". Check for any declaration in the 7757 // translation unit which might conflict. 7758 if (IsGlobal) { 7759 // We have already performed the lookup into the translation unit. 7760 IsGlobal = false; 7761 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7762 I != E; ++I) { 7763 if (isa<VarDecl>(*I)) { 7764 Prev = *I; 7765 break; 7766 } 7767 } 7768 } else { 7769 DeclContext::lookup_result R = 7770 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7771 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7772 I != E; ++I) { 7773 if (isa<VarDecl>(*I)) { 7774 Prev = *I; 7775 break; 7776 } 7777 // FIXME: If we have any other entity with this name in global scope, 7778 // the declaration is ill-formed, but that is a defect: it breaks the 7779 // 'stat' hack, for instance. Only variables can have mangled name 7780 // clashes with extern "C" declarations, so only they deserve a 7781 // diagnostic. 7782 } 7783 } 7784 7785 if (!Prev) 7786 return false; 7787 } 7788 7789 // Use the first declaration's location to ensure we point at something which 7790 // is lexically inside an extern "C" linkage-spec. 7791 assert(Prev && "should have found a previous declaration to diagnose"); 7792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7793 Prev = FD->getFirstDecl(); 7794 else 7795 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7796 7797 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7798 << IsGlobal << ND; 7799 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7800 << IsGlobal; 7801 return false; 7802 } 7803 7804 /// Apply special rules for handling extern "C" declarations. Returns \c true 7805 /// if we have found that this is a redeclaration of some prior entity. 7806 /// 7807 /// Per C++ [dcl.link]p6: 7808 /// Two declarations [for a function or variable] with C language linkage 7809 /// with the same name that appear in different scopes refer to the same 7810 /// [entity]. An entity with C language linkage shall not be declared with 7811 /// the same name as an entity in global scope. 7812 template<typename T> 7813 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7814 LookupResult &Previous) { 7815 if (!S.getLangOpts().CPlusPlus) { 7816 // In C, when declaring a global variable, look for a corresponding 'extern' 7817 // variable declared in function scope. We don't need this in C++, because 7818 // we find local extern decls in the surrounding file-scope DeclContext. 7819 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7820 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7821 Previous.clear(); 7822 Previous.addDecl(Prev); 7823 return true; 7824 } 7825 } 7826 return false; 7827 } 7828 7829 // A declaration in the translation unit can conflict with an extern "C" 7830 // declaration. 7831 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7832 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7833 7834 // An extern "C" declaration can conflict with a declaration in the 7835 // translation unit or can be a redeclaration of an extern "C" declaration 7836 // in another scope. 7837 if (isIncompleteDeclExternC(S,ND)) 7838 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7839 7840 // Neither global nor extern "C": nothing to do. 7841 return false; 7842 } 7843 7844 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7845 // If the decl is already known invalid, don't check it. 7846 if (NewVD->isInvalidDecl()) 7847 return; 7848 7849 QualType T = NewVD->getType(); 7850 7851 // Defer checking an 'auto' type until its initializer is attached. 7852 if (T->isUndeducedType()) 7853 return; 7854 7855 if (NewVD->hasAttrs()) 7856 CheckAlignasUnderalignment(NewVD); 7857 7858 if (T->isObjCObjectType()) { 7859 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7860 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7861 T = Context.getObjCObjectPointerType(T); 7862 NewVD->setType(T); 7863 } 7864 7865 // Emit an error if an address space was applied to decl with local storage. 7866 // This includes arrays of objects with address space qualifiers, but not 7867 // automatic variables that point to other address spaces. 7868 // ISO/IEC TR 18037 S5.1.2 7869 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7870 T.getAddressSpace() != LangAS::Default) { 7871 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7872 NewVD->setInvalidDecl(); 7873 return; 7874 } 7875 7876 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7877 // scope. 7878 if (getLangOpts().OpenCLVersion == 120 && 7879 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7880 NewVD->isStaticLocal()) { 7881 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7882 NewVD->setInvalidDecl(); 7883 return; 7884 } 7885 7886 if (getLangOpts().OpenCL) { 7887 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7888 if (NewVD->hasAttr<BlocksAttr>()) { 7889 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7890 return; 7891 } 7892 7893 if (T->isBlockPointerType()) { 7894 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7895 // can't use 'extern' storage class. 7896 if (!T.isConstQualified()) { 7897 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7898 << 0 /*const*/; 7899 NewVD->setInvalidDecl(); 7900 return; 7901 } 7902 if (NewVD->hasExternalStorage()) { 7903 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7904 NewVD->setInvalidDecl(); 7905 return; 7906 } 7907 } 7908 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7909 // __constant address space. 7910 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7911 // variables inside a function can also be declared in the global 7912 // address space. 7913 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7914 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7915 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7916 NewVD->hasExternalStorage()) { 7917 if (!T->isSamplerT() && 7918 !T->isDependentType() && 7919 !(T.getAddressSpace() == LangAS::opencl_constant || 7920 (T.getAddressSpace() == LangAS::opencl_global && 7921 (getLangOpts().OpenCLVersion == 200 || 7922 getLangOpts().OpenCLCPlusPlus)))) { 7923 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7924 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7925 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7926 << Scope << "global or constant"; 7927 else 7928 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7929 << Scope << "constant"; 7930 NewVD->setInvalidDecl(); 7931 return; 7932 } 7933 } else { 7934 if (T.getAddressSpace() == LangAS::opencl_global) { 7935 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7936 << 1 /*is any function*/ << "global"; 7937 NewVD->setInvalidDecl(); 7938 return; 7939 } 7940 if (T.getAddressSpace() == LangAS::opencl_constant || 7941 T.getAddressSpace() == LangAS::opencl_local) { 7942 FunctionDecl *FD = getCurFunctionDecl(); 7943 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7944 // in functions. 7945 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7946 if (T.getAddressSpace() == LangAS::opencl_constant) 7947 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7948 << 0 /*non-kernel only*/ << "constant"; 7949 else 7950 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7951 << 0 /*non-kernel only*/ << "local"; 7952 NewVD->setInvalidDecl(); 7953 return; 7954 } 7955 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7956 // in the outermost scope of a kernel function. 7957 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7958 if (!getCurScope()->isFunctionScope()) { 7959 if (T.getAddressSpace() == LangAS::opencl_constant) 7960 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7961 << "constant"; 7962 else 7963 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7964 << "local"; 7965 NewVD->setInvalidDecl(); 7966 return; 7967 } 7968 } 7969 } else if (T.getAddressSpace() != LangAS::opencl_private && 7970 // If we are parsing a template we didn't deduce an addr 7971 // space yet. 7972 T.getAddressSpace() != LangAS::Default) { 7973 // Do not allow other address spaces on automatic variable. 7974 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7975 NewVD->setInvalidDecl(); 7976 return; 7977 } 7978 } 7979 } 7980 7981 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7982 && !NewVD->hasAttr<BlocksAttr>()) { 7983 if (getLangOpts().getGC() != LangOptions::NonGC) 7984 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7985 else { 7986 assert(!getLangOpts().ObjCAutoRefCount); 7987 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7988 } 7989 } 7990 7991 bool isVM = T->isVariablyModifiedType(); 7992 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7993 NewVD->hasAttr<BlocksAttr>()) 7994 setFunctionHasBranchProtectedScope(); 7995 7996 if ((isVM && NewVD->hasLinkage()) || 7997 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7998 bool SizeIsNegative; 7999 llvm::APSInt Oversized; 8000 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8001 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8002 QualType FixedT; 8003 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8004 FixedT = FixedTInfo->getType(); 8005 else if (FixedTInfo) { 8006 // Type and type-as-written are canonically different. We need to fix up 8007 // both types separately. 8008 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8009 Oversized); 8010 } 8011 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8012 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8013 // FIXME: This won't give the correct result for 8014 // int a[10][n]; 8015 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8016 8017 if (NewVD->isFileVarDecl()) 8018 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8019 << SizeRange; 8020 else if (NewVD->isStaticLocal()) 8021 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8022 << SizeRange; 8023 else 8024 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8025 << SizeRange; 8026 NewVD->setInvalidDecl(); 8027 return; 8028 } 8029 8030 if (!FixedTInfo) { 8031 if (NewVD->isFileVarDecl()) 8032 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8033 else 8034 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8035 NewVD->setInvalidDecl(); 8036 return; 8037 } 8038 8039 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8040 NewVD->setType(FixedT); 8041 NewVD->setTypeSourceInfo(FixedTInfo); 8042 } 8043 8044 if (T->isVoidType()) { 8045 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8046 // of objects and functions. 8047 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8048 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8049 << T; 8050 NewVD->setInvalidDecl(); 8051 return; 8052 } 8053 } 8054 8055 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8056 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8057 NewVD->setInvalidDecl(); 8058 return; 8059 } 8060 8061 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8062 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8063 NewVD->setInvalidDecl(); 8064 return; 8065 } 8066 8067 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8068 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8069 NewVD->setInvalidDecl(); 8070 return; 8071 } 8072 8073 if (NewVD->isConstexpr() && !T->isDependentType() && 8074 RequireLiteralType(NewVD->getLocation(), T, 8075 diag::err_constexpr_var_non_literal)) { 8076 NewVD->setInvalidDecl(); 8077 return; 8078 } 8079 8080 // PPC MMA non-pointer types are not allowed as non-local variable types. 8081 if (Context.getTargetInfo().getTriple().isPPC64() && 8082 !NewVD->isLocalVarDecl() && 8083 CheckPPCMMAType(T, NewVD->getLocation())) { 8084 NewVD->setInvalidDecl(); 8085 return; 8086 } 8087 } 8088 8089 /// Perform semantic checking on a newly-created variable 8090 /// declaration. 8091 /// 8092 /// This routine performs all of the type-checking required for a 8093 /// variable declaration once it has been built. It is used both to 8094 /// check variables after they have been parsed and their declarators 8095 /// have been translated into a declaration, and to check variables 8096 /// that have been instantiated from a template. 8097 /// 8098 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8099 /// 8100 /// Returns true if the variable declaration is a redeclaration. 8101 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8102 CheckVariableDeclarationType(NewVD); 8103 8104 // If the decl is already known invalid, don't check it. 8105 if (NewVD->isInvalidDecl()) 8106 return false; 8107 8108 // If we did not find anything by this name, look for a non-visible 8109 // extern "C" declaration with the same name. 8110 if (Previous.empty() && 8111 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8112 Previous.setShadowed(); 8113 8114 if (!Previous.empty()) { 8115 MergeVarDecl(NewVD, Previous); 8116 return true; 8117 } 8118 return false; 8119 } 8120 8121 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8122 /// and if so, check that it's a valid override and remember it. 8123 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8124 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8125 8126 // Look for methods in base classes that this method might override. 8127 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8128 /*DetectVirtual=*/false); 8129 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8130 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8131 DeclarationName Name = MD->getDeclName(); 8132 8133 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8134 // We really want to find the base class destructor here. 8135 QualType T = Context.getTypeDeclType(BaseRecord); 8136 CanQualType CT = Context.getCanonicalType(T); 8137 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8138 } 8139 8140 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8141 CXXMethodDecl *BaseMD = 8142 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8143 if (!BaseMD || !BaseMD->isVirtual() || 8144 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8145 /*ConsiderCudaAttrs=*/true, 8146 // C++2a [class.virtual]p2 does not consider requires 8147 // clauses when overriding. 8148 /*ConsiderRequiresClauses=*/false)) 8149 continue; 8150 8151 if (Overridden.insert(BaseMD).second) { 8152 MD->addOverriddenMethod(BaseMD); 8153 CheckOverridingFunctionReturnType(MD, BaseMD); 8154 CheckOverridingFunctionAttributes(MD, BaseMD); 8155 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8156 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8157 } 8158 8159 // A method can only override one function from each base class. We 8160 // don't track indirectly overridden methods from bases of bases. 8161 return true; 8162 } 8163 8164 return false; 8165 }; 8166 8167 DC->lookupInBases(VisitBase, Paths); 8168 return !Overridden.empty(); 8169 } 8170 8171 namespace { 8172 // Struct for holding all of the extra arguments needed by 8173 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8174 struct ActOnFDArgs { 8175 Scope *S; 8176 Declarator &D; 8177 MultiTemplateParamsArg TemplateParamLists; 8178 bool AddToScope; 8179 }; 8180 } // end anonymous namespace 8181 8182 namespace { 8183 8184 // Callback to only accept typo corrections that have a non-zero edit distance. 8185 // Also only accept corrections that have the same parent decl. 8186 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8187 public: 8188 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8189 CXXRecordDecl *Parent) 8190 : Context(Context), OriginalFD(TypoFD), 8191 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8192 8193 bool ValidateCandidate(const TypoCorrection &candidate) override { 8194 if (candidate.getEditDistance() == 0) 8195 return false; 8196 8197 SmallVector<unsigned, 1> MismatchedParams; 8198 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8199 CDeclEnd = candidate.end(); 8200 CDecl != CDeclEnd; ++CDecl) { 8201 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8202 8203 if (FD && !FD->hasBody() && 8204 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8205 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8206 CXXRecordDecl *Parent = MD->getParent(); 8207 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8208 return true; 8209 } else if (!ExpectedParent) { 8210 return true; 8211 } 8212 } 8213 } 8214 8215 return false; 8216 } 8217 8218 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8219 return std::make_unique<DifferentNameValidatorCCC>(*this); 8220 } 8221 8222 private: 8223 ASTContext &Context; 8224 FunctionDecl *OriginalFD; 8225 CXXRecordDecl *ExpectedParent; 8226 }; 8227 8228 } // end anonymous namespace 8229 8230 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8231 TypoCorrectedFunctionDefinitions.insert(F); 8232 } 8233 8234 /// Generate diagnostics for an invalid function redeclaration. 8235 /// 8236 /// This routine handles generating the diagnostic messages for an invalid 8237 /// function redeclaration, including finding possible similar declarations 8238 /// or performing typo correction if there are no previous declarations with 8239 /// the same name. 8240 /// 8241 /// Returns a NamedDecl iff typo correction was performed and substituting in 8242 /// the new declaration name does not cause new errors. 8243 static NamedDecl *DiagnoseInvalidRedeclaration( 8244 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8245 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8246 DeclarationName Name = NewFD->getDeclName(); 8247 DeclContext *NewDC = NewFD->getDeclContext(); 8248 SmallVector<unsigned, 1> MismatchedParams; 8249 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8250 TypoCorrection Correction; 8251 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8252 unsigned DiagMsg = 8253 IsLocalFriend ? diag::err_no_matching_local_friend : 8254 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8255 diag::err_member_decl_does_not_match; 8256 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8257 IsLocalFriend ? Sema::LookupLocalFriendName 8258 : Sema::LookupOrdinaryName, 8259 Sema::ForVisibleRedeclaration); 8260 8261 NewFD->setInvalidDecl(); 8262 if (IsLocalFriend) 8263 SemaRef.LookupName(Prev, S); 8264 else 8265 SemaRef.LookupQualifiedName(Prev, NewDC); 8266 assert(!Prev.isAmbiguous() && 8267 "Cannot have an ambiguity in previous-declaration lookup"); 8268 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8269 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8270 MD ? MD->getParent() : nullptr); 8271 if (!Prev.empty()) { 8272 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8273 Func != FuncEnd; ++Func) { 8274 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8275 if (FD && 8276 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8277 // Add 1 to the index so that 0 can mean the mismatch didn't 8278 // involve a parameter 8279 unsigned ParamNum = 8280 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8281 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8282 } 8283 } 8284 // If the qualified name lookup yielded nothing, try typo correction 8285 } else if ((Correction = SemaRef.CorrectTypo( 8286 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8287 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8288 IsLocalFriend ? nullptr : NewDC))) { 8289 // Set up everything for the call to ActOnFunctionDeclarator 8290 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8291 ExtraArgs.D.getIdentifierLoc()); 8292 Previous.clear(); 8293 Previous.setLookupName(Correction.getCorrection()); 8294 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8295 CDeclEnd = Correction.end(); 8296 CDecl != CDeclEnd; ++CDecl) { 8297 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8298 if (FD && !FD->hasBody() && 8299 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8300 Previous.addDecl(FD); 8301 } 8302 } 8303 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8304 8305 NamedDecl *Result; 8306 // Retry building the function declaration with the new previous 8307 // declarations, and with errors suppressed. 8308 { 8309 // Trap errors. 8310 Sema::SFINAETrap Trap(SemaRef); 8311 8312 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8313 // pieces need to verify the typo-corrected C++ declaration and hopefully 8314 // eliminate the need for the parameter pack ExtraArgs. 8315 Result = SemaRef.ActOnFunctionDeclarator( 8316 ExtraArgs.S, ExtraArgs.D, 8317 Correction.getCorrectionDecl()->getDeclContext(), 8318 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8319 ExtraArgs.AddToScope); 8320 8321 if (Trap.hasErrorOccurred()) 8322 Result = nullptr; 8323 } 8324 8325 if (Result) { 8326 // Determine which correction we picked. 8327 Decl *Canonical = Result->getCanonicalDecl(); 8328 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8329 I != E; ++I) 8330 if ((*I)->getCanonicalDecl() == Canonical) 8331 Correction.setCorrectionDecl(*I); 8332 8333 // Let Sema know about the correction. 8334 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8335 SemaRef.diagnoseTypo( 8336 Correction, 8337 SemaRef.PDiag(IsLocalFriend 8338 ? diag::err_no_matching_local_friend_suggest 8339 : diag::err_member_decl_does_not_match_suggest) 8340 << Name << NewDC << IsDefinition); 8341 return Result; 8342 } 8343 8344 // Pretend the typo correction never occurred 8345 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8346 ExtraArgs.D.getIdentifierLoc()); 8347 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8348 Previous.clear(); 8349 Previous.setLookupName(Name); 8350 } 8351 8352 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8353 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8354 8355 bool NewFDisConst = false; 8356 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8357 NewFDisConst = NewMD->isConst(); 8358 8359 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8360 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8361 NearMatch != NearMatchEnd; ++NearMatch) { 8362 FunctionDecl *FD = NearMatch->first; 8363 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8364 bool FDisConst = MD && MD->isConst(); 8365 bool IsMember = MD || !IsLocalFriend; 8366 8367 // FIXME: These notes are poorly worded for the local friend case. 8368 if (unsigned Idx = NearMatch->second) { 8369 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8370 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8371 if (Loc.isInvalid()) Loc = FD->getLocation(); 8372 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8373 : diag::note_local_decl_close_param_match) 8374 << Idx << FDParam->getType() 8375 << NewFD->getParamDecl(Idx - 1)->getType(); 8376 } else if (FDisConst != NewFDisConst) { 8377 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8378 << NewFDisConst << FD->getSourceRange().getEnd(); 8379 } else 8380 SemaRef.Diag(FD->getLocation(), 8381 IsMember ? diag::note_member_def_close_match 8382 : diag::note_local_decl_close_match); 8383 } 8384 return nullptr; 8385 } 8386 8387 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8388 switch (D.getDeclSpec().getStorageClassSpec()) { 8389 default: llvm_unreachable("Unknown storage class!"); 8390 case DeclSpec::SCS_auto: 8391 case DeclSpec::SCS_register: 8392 case DeclSpec::SCS_mutable: 8393 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8394 diag::err_typecheck_sclass_func); 8395 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8396 D.setInvalidType(); 8397 break; 8398 case DeclSpec::SCS_unspecified: break; 8399 case DeclSpec::SCS_extern: 8400 if (D.getDeclSpec().isExternInLinkageSpec()) 8401 return SC_None; 8402 return SC_Extern; 8403 case DeclSpec::SCS_static: { 8404 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8405 // C99 6.7.1p5: 8406 // The declaration of an identifier for a function that has 8407 // block scope shall have no explicit storage-class specifier 8408 // other than extern 8409 // See also (C++ [dcl.stc]p4). 8410 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8411 diag::err_static_block_func); 8412 break; 8413 } else 8414 return SC_Static; 8415 } 8416 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8417 } 8418 8419 // No explicit storage class has already been returned 8420 return SC_None; 8421 } 8422 8423 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8424 DeclContext *DC, QualType &R, 8425 TypeSourceInfo *TInfo, 8426 StorageClass SC, 8427 bool &IsVirtualOkay) { 8428 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8429 DeclarationName Name = NameInfo.getName(); 8430 8431 FunctionDecl *NewFD = nullptr; 8432 bool isInline = D.getDeclSpec().isInlineSpecified(); 8433 8434 if (!SemaRef.getLangOpts().CPlusPlus) { 8435 // Determine whether the function was written with a 8436 // prototype. This true when: 8437 // - there is a prototype in the declarator, or 8438 // - the type R of the function is some kind of typedef or other non- 8439 // attributed reference to a type name (which eventually refers to a 8440 // function type). 8441 bool HasPrototype = 8442 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8443 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8444 8445 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8446 R, TInfo, SC, isInline, HasPrototype, 8447 ConstexprSpecKind::Unspecified, 8448 /*TrailingRequiresClause=*/nullptr); 8449 if (D.isInvalidType()) 8450 NewFD->setInvalidDecl(); 8451 8452 return NewFD; 8453 } 8454 8455 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8456 8457 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8458 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8459 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8460 diag::err_constexpr_wrong_decl_kind) 8461 << static_cast<int>(ConstexprKind); 8462 ConstexprKind = ConstexprSpecKind::Unspecified; 8463 D.getMutableDeclSpec().ClearConstexprSpec(); 8464 } 8465 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8466 8467 // Check that the return type is not an abstract class type. 8468 // For record types, this is done by the AbstractClassUsageDiagnoser once 8469 // the class has been completely parsed. 8470 if (!DC->isRecord() && 8471 SemaRef.RequireNonAbstractType( 8472 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8473 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8474 D.setInvalidType(); 8475 8476 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8477 // This is a C++ constructor declaration. 8478 assert(DC->isRecord() && 8479 "Constructors can only be declared in a member context"); 8480 8481 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8482 return CXXConstructorDecl::Create( 8483 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8484 TInfo, ExplicitSpecifier, isInline, 8485 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8486 TrailingRequiresClause); 8487 8488 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8489 // This is a C++ destructor declaration. 8490 if (DC->isRecord()) { 8491 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8492 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8493 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8494 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8495 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8496 TrailingRequiresClause); 8497 8498 // If the destructor needs an implicit exception specification, set it 8499 // now. FIXME: It'd be nice to be able to create the right type to start 8500 // with, but the type needs to reference the destructor declaration. 8501 if (SemaRef.getLangOpts().CPlusPlus11) 8502 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8503 8504 IsVirtualOkay = true; 8505 return NewDD; 8506 8507 } else { 8508 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8509 D.setInvalidType(); 8510 8511 // Create a FunctionDecl to satisfy the function definition parsing 8512 // code path. 8513 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8514 D.getIdentifierLoc(), Name, R, TInfo, SC, 8515 isInline, 8516 /*hasPrototype=*/true, ConstexprKind, 8517 TrailingRequiresClause); 8518 } 8519 8520 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8521 if (!DC->isRecord()) { 8522 SemaRef.Diag(D.getIdentifierLoc(), 8523 diag::err_conv_function_not_member); 8524 return nullptr; 8525 } 8526 8527 SemaRef.CheckConversionDeclarator(D, R, SC); 8528 if (D.isInvalidType()) 8529 return nullptr; 8530 8531 IsVirtualOkay = true; 8532 return CXXConversionDecl::Create( 8533 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8534 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8535 TrailingRequiresClause); 8536 8537 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8538 if (TrailingRequiresClause) 8539 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8540 diag::err_trailing_requires_clause_on_deduction_guide) 8541 << TrailingRequiresClause->getSourceRange(); 8542 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8543 8544 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8545 ExplicitSpecifier, NameInfo, R, TInfo, 8546 D.getEndLoc()); 8547 } else if (DC->isRecord()) { 8548 // If the name of the function is the same as the name of the record, 8549 // then this must be an invalid constructor that has a return type. 8550 // (The parser checks for a return type and makes the declarator a 8551 // constructor if it has no return type). 8552 if (Name.getAsIdentifierInfo() && 8553 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8554 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8555 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8556 << SourceRange(D.getIdentifierLoc()); 8557 return nullptr; 8558 } 8559 8560 // This is a C++ method declaration. 8561 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8562 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8563 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8564 TrailingRequiresClause); 8565 IsVirtualOkay = !Ret->isStatic(); 8566 return Ret; 8567 } else { 8568 bool isFriend = 8569 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8570 if (!isFriend && SemaRef.CurContext->isRecord()) 8571 return nullptr; 8572 8573 // Determine whether the function was written with a 8574 // prototype. This true when: 8575 // - we're in C++ (where every function has a prototype), 8576 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8577 R, TInfo, SC, isInline, true /*HasPrototype*/, 8578 ConstexprKind, TrailingRequiresClause); 8579 } 8580 } 8581 8582 enum OpenCLParamType { 8583 ValidKernelParam, 8584 PtrPtrKernelParam, 8585 PtrKernelParam, 8586 InvalidAddrSpacePtrKernelParam, 8587 InvalidKernelParam, 8588 RecordKernelParam 8589 }; 8590 8591 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8592 // Size dependent types are just typedefs to normal integer types 8593 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8594 // integers other than by their names. 8595 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8596 8597 // Remove typedefs one by one until we reach a typedef 8598 // for a size dependent type. 8599 QualType DesugaredTy = Ty; 8600 do { 8601 ArrayRef<StringRef> Names(SizeTypeNames); 8602 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8603 if (Names.end() != Match) 8604 return true; 8605 8606 Ty = DesugaredTy; 8607 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8608 } while (DesugaredTy != Ty); 8609 8610 return false; 8611 } 8612 8613 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8614 if (PT->isPointerType()) { 8615 QualType PointeeType = PT->getPointeeType(); 8616 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8617 PointeeType.getAddressSpace() == LangAS::opencl_private || 8618 PointeeType.getAddressSpace() == LangAS::Default) 8619 return InvalidAddrSpacePtrKernelParam; 8620 8621 if (PointeeType->isPointerType()) { 8622 // This is a pointer to pointer parameter. 8623 // Recursively check inner type. 8624 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8625 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8626 ParamKind == InvalidKernelParam) 8627 return ParamKind; 8628 8629 return PtrPtrKernelParam; 8630 } 8631 return PtrKernelParam; 8632 } 8633 8634 // OpenCL v1.2 s6.9.k: 8635 // Arguments to kernel functions in a program cannot be declared with the 8636 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8637 // uintptr_t or a struct and/or union that contain fields declared to be one 8638 // of these built-in scalar types. 8639 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8640 return InvalidKernelParam; 8641 8642 if (PT->isImageType()) 8643 return PtrKernelParam; 8644 8645 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8646 return InvalidKernelParam; 8647 8648 // OpenCL extension spec v1.2 s9.5: 8649 // This extension adds support for half scalar and vector types as built-in 8650 // types that can be used for arithmetic operations, conversions etc. 8651 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8652 return InvalidKernelParam; 8653 8654 if (PT->isRecordType()) 8655 return RecordKernelParam; 8656 8657 // Look into an array argument to check if it has a forbidden type. 8658 if (PT->isArrayType()) { 8659 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8660 // Call ourself to check an underlying type of an array. Since the 8661 // getPointeeOrArrayElementType returns an innermost type which is not an 8662 // array, this recursive call only happens once. 8663 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8664 } 8665 8666 return ValidKernelParam; 8667 } 8668 8669 static void checkIsValidOpenCLKernelParameter( 8670 Sema &S, 8671 Declarator &D, 8672 ParmVarDecl *Param, 8673 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8674 QualType PT = Param->getType(); 8675 8676 // Cache the valid types we encounter to avoid rechecking structs that are 8677 // used again 8678 if (ValidTypes.count(PT.getTypePtr())) 8679 return; 8680 8681 switch (getOpenCLKernelParameterType(S, PT)) { 8682 case PtrPtrKernelParam: 8683 // OpenCL v3.0 s6.11.a: 8684 // A kernel function argument cannot be declared as a pointer to a pointer 8685 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8686 if (S.getLangOpts().OpenCLVersion < 120 && 8687 !S.getLangOpts().OpenCLCPlusPlus) { 8688 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8689 D.setInvalidType(); 8690 return; 8691 } 8692 8693 ValidTypes.insert(PT.getTypePtr()); 8694 return; 8695 8696 case InvalidAddrSpacePtrKernelParam: 8697 // OpenCL v1.0 s6.5: 8698 // __kernel function arguments declared to be a pointer of a type can point 8699 // to one of the following address spaces only : __global, __local or 8700 // __constant. 8701 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8702 D.setInvalidType(); 8703 return; 8704 8705 // OpenCL v1.2 s6.9.k: 8706 // Arguments to kernel functions in a program cannot be declared with the 8707 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8708 // uintptr_t or a struct and/or union that contain fields declared to be 8709 // one of these built-in scalar types. 8710 8711 case InvalidKernelParam: 8712 // OpenCL v1.2 s6.8 n: 8713 // A kernel function argument cannot be declared 8714 // of event_t type. 8715 // Do not diagnose half type since it is diagnosed as invalid argument 8716 // type for any function elsewhere. 8717 if (!PT->isHalfType()) { 8718 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8719 8720 // Explain what typedefs are involved. 8721 const TypedefType *Typedef = nullptr; 8722 while ((Typedef = PT->getAs<TypedefType>())) { 8723 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8724 // SourceLocation may be invalid for a built-in type. 8725 if (Loc.isValid()) 8726 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8727 PT = Typedef->desugar(); 8728 } 8729 } 8730 8731 D.setInvalidType(); 8732 return; 8733 8734 case PtrKernelParam: 8735 case ValidKernelParam: 8736 ValidTypes.insert(PT.getTypePtr()); 8737 return; 8738 8739 case RecordKernelParam: 8740 break; 8741 } 8742 8743 // Track nested structs we will inspect 8744 SmallVector<const Decl *, 4> VisitStack; 8745 8746 // Track where we are in the nested structs. Items will migrate from 8747 // VisitStack to HistoryStack as we do the DFS for bad field. 8748 SmallVector<const FieldDecl *, 4> HistoryStack; 8749 HistoryStack.push_back(nullptr); 8750 8751 // At this point we already handled everything except of a RecordType or 8752 // an ArrayType of a RecordType. 8753 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8754 const RecordType *RecTy = 8755 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8756 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8757 8758 VisitStack.push_back(RecTy->getDecl()); 8759 assert(VisitStack.back() && "First decl null?"); 8760 8761 do { 8762 const Decl *Next = VisitStack.pop_back_val(); 8763 if (!Next) { 8764 assert(!HistoryStack.empty()); 8765 // Found a marker, we have gone up a level 8766 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8767 ValidTypes.insert(Hist->getType().getTypePtr()); 8768 8769 continue; 8770 } 8771 8772 // Adds everything except the original parameter declaration (which is not a 8773 // field itself) to the history stack. 8774 const RecordDecl *RD; 8775 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8776 HistoryStack.push_back(Field); 8777 8778 QualType FieldTy = Field->getType(); 8779 // Other field types (known to be valid or invalid) are handled while we 8780 // walk around RecordDecl::fields(). 8781 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8782 "Unexpected type."); 8783 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8784 8785 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8786 } else { 8787 RD = cast<RecordDecl>(Next); 8788 } 8789 8790 // Add a null marker so we know when we've gone back up a level 8791 VisitStack.push_back(nullptr); 8792 8793 for (const auto *FD : RD->fields()) { 8794 QualType QT = FD->getType(); 8795 8796 if (ValidTypes.count(QT.getTypePtr())) 8797 continue; 8798 8799 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8800 if (ParamType == ValidKernelParam) 8801 continue; 8802 8803 if (ParamType == RecordKernelParam) { 8804 VisitStack.push_back(FD); 8805 continue; 8806 } 8807 8808 // OpenCL v1.2 s6.9.p: 8809 // Arguments to kernel functions that are declared to be a struct or union 8810 // do not allow OpenCL objects to be passed as elements of the struct or 8811 // union. 8812 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8813 ParamType == InvalidAddrSpacePtrKernelParam) { 8814 S.Diag(Param->getLocation(), 8815 diag::err_record_with_pointers_kernel_param) 8816 << PT->isUnionType() 8817 << PT; 8818 } else { 8819 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8820 } 8821 8822 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8823 << OrigRecDecl->getDeclName(); 8824 8825 // We have an error, now let's go back up through history and show where 8826 // the offending field came from 8827 for (ArrayRef<const FieldDecl *>::const_iterator 8828 I = HistoryStack.begin() + 1, 8829 E = HistoryStack.end(); 8830 I != E; ++I) { 8831 const FieldDecl *OuterField = *I; 8832 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8833 << OuterField->getType(); 8834 } 8835 8836 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8837 << QT->isPointerType() 8838 << QT; 8839 D.setInvalidType(); 8840 return; 8841 } 8842 } while (!VisitStack.empty()); 8843 } 8844 8845 /// Find the DeclContext 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 DeclContext *getTagInjectionContext(DeclContext *DC) { 8849 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8850 DC = DC->getParent(); 8851 return DC; 8852 } 8853 8854 /// Find the Scope in which a tag is implicitly declared if we see an 8855 /// elaborated type specifier in the specified context, and lookup finds 8856 /// nothing. 8857 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8858 while (S->isClassScope() || 8859 (LangOpts.CPlusPlus && 8860 S->isFunctionPrototypeScope()) || 8861 ((S->getFlags() & Scope::DeclScope) == 0) || 8862 (S->getEntity() && S->getEntity()->isTransparentContext())) 8863 S = S->getParent(); 8864 return S; 8865 } 8866 8867 NamedDecl* 8868 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8869 TypeSourceInfo *TInfo, LookupResult &Previous, 8870 MultiTemplateParamsArg TemplateParamListsRef, 8871 bool &AddToScope) { 8872 QualType R = TInfo->getType(); 8873 8874 assert(R->isFunctionType()); 8875 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8876 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8877 8878 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8879 for (TemplateParameterList *TPL : TemplateParamListsRef) 8880 TemplateParamLists.push_back(TPL); 8881 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8882 if (!TemplateParamLists.empty() && 8883 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8884 TemplateParamLists.back() = Invented; 8885 else 8886 TemplateParamLists.push_back(Invented); 8887 } 8888 8889 // TODO: consider using NameInfo for diagnostic. 8890 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8891 DeclarationName Name = NameInfo.getName(); 8892 StorageClass SC = getFunctionStorageClass(*this, D); 8893 8894 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8895 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8896 diag::err_invalid_thread) 8897 << DeclSpec::getSpecifierName(TSCS); 8898 8899 if (D.isFirstDeclarationOfMember()) 8900 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8901 D.getIdentifierLoc()); 8902 8903 bool isFriend = false; 8904 FunctionTemplateDecl *FunctionTemplate = nullptr; 8905 bool isMemberSpecialization = false; 8906 bool isFunctionTemplateSpecialization = false; 8907 8908 bool isDependentClassScopeExplicitSpecialization = false; 8909 bool HasExplicitTemplateArgs = false; 8910 TemplateArgumentListInfo TemplateArgs; 8911 8912 bool isVirtualOkay = false; 8913 8914 DeclContext *OriginalDC = DC; 8915 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8916 8917 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8918 isVirtualOkay); 8919 if (!NewFD) return nullptr; 8920 8921 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8922 NewFD->setTopLevelDeclInObjCContainer(); 8923 8924 // Set the lexical context. If this is a function-scope declaration, or has a 8925 // C++ scope specifier, or is the object of a friend declaration, the lexical 8926 // context will be different from the semantic context. 8927 NewFD->setLexicalDeclContext(CurContext); 8928 8929 if (IsLocalExternDecl) 8930 NewFD->setLocalExternDecl(); 8931 8932 if (getLangOpts().CPlusPlus) { 8933 bool isInline = D.getDeclSpec().isInlineSpecified(); 8934 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8935 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8936 isFriend = D.getDeclSpec().isFriendSpecified(); 8937 if (isFriend && !isInline && D.isFunctionDefinition()) { 8938 // C++ [class.friend]p5 8939 // A function can be defined in a friend declaration of a 8940 // class . . . . Such a function is implicitly inline. 8941 NewFD->setImplicitlyInline(); 8942 } 8943 8944 // If this is a method defined in an __interface, and is not a constructor 8945 // or an overloaded operator, then set the pure flag (isVirtual will already 8946 // return true). 8947 if (const CXXRecordDecl *Parent = 8948 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8949 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8950 NewFD->setPure(true); 8951 8952 // C++ [class.union]p2 8953 // A union can have member functions, but not virtual functions. 8954 if (isVirtual && Parent->isUnion()) 8955 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8956 } 8957 8958 SetNestedNameSpecifier(*this, NewFD, D); 8959 isMemberSpecialization = false; 8960 isFunctionTemplateSpecialization = false; 8961 if (D.isInvalidType()) 8962 NewFD->setInvalidDecl(); 8963 8964 // Match up the template parameter lists with the scope specifier, then 8965 // determine whether we have a template or a template specialization. 8966 bool Invalid = false; 8967 TemplateParameterList *TemplateParams = 8968 MatchTemplateParametersToScopeSpecifier( 8969 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8970 D.getCXXScopeSpec(), 8971 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8972 ? D.getName().TemplateId 8973 : nullptr, 8974 TemplateParamLists, isFriend, isMemberSpecialization, 8975 Invalid); 8976 if (TemplateParams) { 8977 // Check that we can declare a template here. 8978 if (CheckTemplateDeclScope(S, TemplateParams)) 8979 NewFD->setInvalidDecl(); 8980 8981 if (TemplateParams->size() > 0) { 8982 // This is a function template 8983 8984 // A destructor cannot be a template. 8985 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8986 Diag(NewFD->getLocation(), diag::err_destructor_template); 8987 NewFD->setInvalidDecl(); 8988 } 8989 8990 // If we're adding a template to a dependent context, we may need to 8991 // rebuilding some of the types used within the template parameter list, 8992 // now that we know what the current instantiation is. 8993 if (DC->isDependentContext()) { 8994 ContextRAII SavedContext(*this, DC); 8995 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8996 Invalid = true; 8997 } 8998 8999 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9000 NewFD->getLocation(), 9001 Name, TemplateParams, 9002 NewFD); 9003 FunctionTemplate->setLexicalDeclContext(CurContext); 9004 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9005 9006 // For source fidelity, store the other template param lists. 9007 if (TemplateParamLists.size() > 1) { 9008 NewFD->setTemplateParameterListsInfo(Context, 9009 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9010 .drop_back(1)); 9011 } 9012 } else { 9013 // This is a function template specialization. 9014 isFunctionTemplateSpecialization = true; 9015 // For source fidelity, store all the template param lists. 9016 if (TemplateParamLists.size() > 0) 9017 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9018 9019 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9020 if (isFriend) { 9021 // We want to remove the "template<>", found here. 9022 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9023 9024 // If we remove the template<> and the name is not a 9025 // template-id, we're actually silently creating a problem: 9026 // the friend declaration will refer to an untemplated decl, 9027 // and clearly the user wants a template specialization. So 9028 // we need to insert '<>' after the name. 9029 SourceLocation InsertLoc; 9030 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9031 InsertLoc = D.getName().getSourceRange().getEnd(); 9032 InsertLoc = getLocForEndOfToken(InsertLoc); 9033 } 9034 9035 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9036 << Name << RemoveRange 9037 << FixItHint::CreateRemoval(RemoveRange) 9038 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9039 } 9040 } 9041 } else { 9042 // Check that we can declare a template here. 9043 if (!TemplateParamLists.empty() && isMemberSpecialization && 9044 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9045 NewFD->setInvalidDecl(); 9046 9047 // All template param lists were matched against the scope specifier: 9048 // this is NOT (an explicit specialization of) a template. 9049 if (TemplateParamLists.size() > 0) 9050 // For source fidelity, store all the template param lists. 9051 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9052 } 9053 9054 if (Invalid) { 9055 NewFD->setInvalidDecl(); 9056 if (FunctionTemplate) 9057 FunctionTemplate->setInvalidDecl(); 9058 } 9059 9060 // C++ [dcl.fct.spec]p5: 9061 // The virtual specifier shall only be used in declarations of 9062 // nonstatic class member functions that appear within a 9063 // member-specification of a class declaration; see 10.3. 9064 // 9065 if (isVirtual && !NewFD->isInvalidDecl()) { 9066 if (!isVirtualOkay) { 9067 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9068 diag::err_virtual_non_function); 9069 } else if (!CurContext->isRecord()) { 9070 // 'virtual' was specified outside of the class. 9071 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9072 diag::err_virtual_out_of_class) 9073 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9074 } else if (NewFD->getDescribedFunctionTemplate()) { 9075 // C++ [temp.mem]p3: 9076 // A member function template shall not be virtual. 9077 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9078 diag::err_virtual_member_function_template) 9079 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9080 } else { 9081 // Okay: Add virtual to the method. 9082 NewFD->setVirtualAsWritten(true); 9083 } 9084 9085 if (getLangOpts().CPlusPlus14 && 9086 NewFD->getReturnType()->isUndeducedType()) 9087 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9088 } 9089 9090 if (getLangOpts().CPlusPlus14 && 9091 (NewFD->isDependentContext() || 9092 (isFriend && CurContext->isDependentContext())) && 9093 NewFD->getReturnType()->isUndeducedType()) { 9094 // If the function template is referenced directly (for instance, as a 9095 // member of the current instantiation), pretend it has a dependent type. 9096 // This is not really justified by the standard, but is the only sane 9097 // thing to do. 9098 // FIXME: For a friend function, we have not marked the function as being 9099 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9100 const FunctionProtoType *FPT = 9101 NewFD->getType()->castAs<FunctionProtoType>(); 9102 QualType Result = 9103 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9104 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9105 FPT->getExtProtoInfo())); 9106 } 9107 9108 // C++ [dcl.fct.spec]p3: 9109 // The inline specifier shall not appear on a block scope function 9110 // declaration. 9111 if (isInline && !NewFD->isInvalidDecl()) { 9112 if (CurContext->isFunctionOrMethod()) { 9113 // 'inline' is not allowed on block scope function declaration. 9114 Diag(D.getDeclSpec().getInlineSpecLoc(), 9115 diag::err_inline_declaration_block_scope) << Name 9116 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9117 } 9118 } 9119 9120 // C++ [dcl.fct.spec]p6: 9121 // The explicit specifier shall be used only in the declaration of a 9122 // constructor or conversion function within its class definition; 9123 // see 12.3.1 and 12.3.2. 9124 if (hasExplicit && !NewFD->isInvalidDecl() && 9125 !isa<CXXDeductionGuideDecl>(NewFD)) { 9126 if (!CurContext->isRecord()) { 9127 // 'explicit' was specified outside of the class. 9128 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9129 diag::err_explicit_out_of_class) 9130 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9131 } else if (!isa<CXXConstructorDecl>(NewFD) && 9132 !isa<CXXConversionDecl>(NewFD)) { 9133 // 'explicit' was specified on a function that wasn't a constructor 9134 // or conversion function. 9135 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9136 diag::err_explicit_non_ctor_or_conv_function) 9137 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9138 } 9139 } 9140 9141 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9142 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9143 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9144 // are implicitly inline. 9145 NewFD->setImplicitlyInline(); 9146 9147 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9148 // be either constructors or to return a literal type. Therefore, 9149 // destructors cannot be declared constexpr. 9150 if (isa<CXXDestructorDecl>(NewFD) && 9151 (!getLangOpts().CPlusPlus20 || 9152 ConstexprKind == ConstexprSpecKind::Consteval)) { 9153 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9154 << static_cast<int>(ConstexprKind); 9155 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9156 ? ConstexprSpecKind::Unspecified 9157 : ConstexprSpecKind::Constexpr); 9158 } 9159 // C++20 [dcl.constexpr]p2: An allocation function, or a 9160 // deallocation function shall not be declared with the consteval 9161 // specifier. 9162 if (ConstexprKind == ConstexprSpecKind::Consteval && 9163 (NewFD->getOverloadedOperator() == OO_New || 9164 NewFD->getOverloadedOperator() == OO_Array_New || 9165 NewFD->getOverloadedOperator() == OO_Delete || 9166 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9167 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9168 diag::err_invalid_consteval_decl_kind) 9169 << NewFD; 9170 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9171 } 9172 } 9173 9174 // If __module_private__ was specified, mark the function accordingly. 9175 if (D.getDeclSpec().isModulePrivateSpecified()) { 9176 if (isFunctionTemplateSpecialization) { 9177 SourceLocation ModulePrivateLoc 9178 = D.getDeclSpec().getModulePrivateSpecLoc(); 9179 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9180 << 0 9181 << FixItHint::CreateRemoval(ModulePrivateLoc); 9182 } else { 9183 NewFD->setModulePrivate(); 9184 if (FunctionTemplate) 9185 FunctionTemplate->setModulePrivate(); 9186 } 9187 } 9188 9189 if (isFriend) { 9190 if (FunctionTemplate) { 9191 FunctionTemplate->setObjectOfFriendDecl(); 9192 FunctionTemplate->setAccess(AS_public); 9193 } 9194 NewFD->setObjectOfFriendDecl(); 9195 NewFD->setAccess(AS_public); 9196 } 9197 9198 // If a function is defined as defaulted or deleted, mark it as such now. 9199 // We'll do the relevant checks on defaulted / deleted functions later. 9200 switch (D.getFunctionDefinitionKind()) { 9201 case FunctionDefinitionKind::Declaration: 9202 case FunctionDefinitionKind::Definition: 9203 break; 9204 9205 case FunctionDefinitionKind::Defaulted: 9206 NewFD->setDefaulted(); 9207 break; 9208 9209 case FunctionDefinitionKind::Deleted: 9210 NewFD->setDeletedAsWritten(); 9211 break; 9212 } 9213 9214 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9215 D.isFunctionDefinition()) { 9216 // C++ [class.mfct]p2: 9217 // A member function may be defined (8.4) in its class definition, in 9218 // which case it is an inline member function (7.1.2) 9219 NewFD->setImplicitlyInline(); 9220 } 9221 9222 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9223 !CurContext->isRecord()) { 9224 // C++ [class.static]p1: 9225 // A data or function member of a class may be declared static 9226 // in a class definition, in which case it is a static member of 9227 // the class. 9228 9229 // Complain about the 'static' specifier if it's on an out-of-line 9230 // member function definition. 9231 9232 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9233 // member function template declaration and class member template 9234 // declaration (MSVC versions before 2015), warn about this. 9235 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9236 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9237 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9238 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9239 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9240 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9241 } 9242 9243 // C++11 [except.spec]p15: 9244 // A deallocation function with no exception-specification is treated 9245 // as if it were specified with noexcept(true). 9246 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9247 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9248 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9249 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9250 NewFD->setType(Context.getFunctionType( 9251 FPT->getReturnType(), FPT->getParamTypes(), 9252 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9253 } 9254 9255 // Filter out previous declarations that don't match the scope. 9256 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9257 D.getCXXScopeSpec().isNotEmpty() || 9258 isMemberSpecialization || 9259 isFunctionTemplateSpecialization); 9260 9261 // Handle GNU asm-label extension (encoded as an attribute). 9262 if (Expr *E = (Expr*) D.getAsmLabel()) { 9263 // The parser guarantees this is a string. 9264 StringLiteral *SE = cast<StringLiteral>(E); 9265 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9266 /*IsLiteralLabel=*/true, 9267 SE->getStrTokenLoc(0))); 9268 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9269 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9270 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9271 if (I != ExtnameUndeclaredIdentifiers.end()) { 9272 if (isDeclExternC(NewFD)) { 9273 NewFD->addAttr(I->second); 9274 ExtnameUndeclaredIdentifiers.erase(I); 9275 } else 9276 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9277 << /*Variable*/0 << NewFD; 9278 } 9279 } 9280 9281 // Copy the parameter declarations from the declarator D to the function 9282 // declaration NewFD, if they are available. First scavenge them into Params. 9283 SmallVector<ParmVarDecl*, 16> Params; 9284 unsigned FTIIdx; 9285 if (D.isFunctionDeclarator(FTIIdx)) { 9286 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9287 9288 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9289 // function that takes no arguments, not a function that takes a 9290 // single void argument. 9291 // We let through "const void" here because Sema::GetTypeForDeclarator 9292 // already checks for that case. 9293 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9294 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9295 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9296 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9297 Param->setDeclContext(NewFD); 9298 Params.push_back(Param); 9299 9300 if (Param->isInvalidDecl()) 9301 NewFD->setInvalidDecl(); 9302 } 9303 } 9304 9305 if (!getLangOpts().CPlusPlus) { 9306 // In C, find all the tag declarations from the prototype and move them 9307 // into the function DeclContext. Remove them from the surrounding tag 9308 // injection context of the function, which is typically but not always 9309 // the TU. 9310 DeclContext *PrototypeTagContext = 9311 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9312 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9313 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9314 9315 // We don't want to reparent enumerators. Look at their parent enum 9316 // instead. 9317 if (!TD) { 9318 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9319 TD = cast<EnumDecl>(ECD->getDeclContext()); 9320 } 9321 if (!TD) 9322 continue; 9323 DeclContext *TagDC = TD->getLexicalDeclContext(); 9324 if (!TagDC->containsDecl(TD)) 9325 continue; 9326 TagDC->removeDecl(TD); 9327 TD->setDeclContext(NewFD); 9328 NewFD->addDecl(TD); 9329 9330 // Preserve the lexical DeclContext if it is not the surrounding tag 9331 // injection context of the FD. In this example, the semantic context of 9332 // E will be f and the lexical context will be S, while both the 9333 // semantic and lexical contexts of S will be f: 9334 // void f(struct S { enum E { a } f; } s); 9335 if (TagDC != PrototypeTagContext) 9336 TD->setLexicalDeclContext(TagDC); 9337 } 9338 } 9339 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9340 // When we're declaring a function with a typedef, typeof, etc as in the 9341 // following example, we'll need to synthesize (unnamed) 9342 // parameters for use in the declaration. 9343 // 9344 // @code 9345 // typedef void fn(int); 9346 // fn f; 9347 // @endcode 9348 9349 // Synthesize a parameter for each argument type. 9350 for (const auto &AI : FT->param_types()) { 9351 ParmVarDecl *Param = 9352 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9353 Param->setScopeInfo(0, Params.size()); 9354 Params.push_back(Param); 9355 } 9356 } else { 9357 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9358 "Should not need args for typedef of non-prototype fn"); 9359 } 9360 9361 // Finally, we know we have the right number of parameters, install them. 9362 NewFD->setParams(Params); 9363 9364 if (D.getDeclSpec().isNoreturnSpecified()) 9365 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9366 D.getDeclSpec().getNoreturnSpecLoc(), 9367 AttributeCommonInfo::AS_Keyword)); 9368 9369 // Functions returning a variably modified type violate C99 6.7.5.2p2 9370 // because all functions have linkage. 9371 if (!NewFD->isInvalidDecl() && 9372 NewFD->getReturnType()->isVariablyModifiedType()) { 9373 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9374 NewFD->setInvalidDecl(); 9375 } 9376 9377 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9378 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9379 !NewFD->hasAttr<SectionAttr>()) 9380 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9381 Context, PragmaClangTextSection.SectionName, 9382 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9383 9384 // Apply an implicit SectionAttr if #pragma code_seg is active. 9385 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9386 !NewFD->hasAttr<SectionAttr>()) { 9387 NewFD->addAttr(SectionAttr::CreateImplicit( 9388 Context, CodeSegStack.CurrentValue->getString(), 9389 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9390 SectionAttr::Declspec_allocate)); 9391 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9392 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9393 ASTContext::PSF_Read, 9394 NewFD)) 9395 NewFD->dropAttr<SectionAttr>(); 9396 } 9397 9398 // Apply an implicit CodeSegAttr from class declspec or 9399 // apply an implicit SectionAttr from #pragma code_seg if active. 9400 if (!NewFD->hasAttr<CodeSegAttr>()) { 9401 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9402 D.isFunctionDefinition())) { 9403 NewFD->addAttr(SAttr); 9404 } 9405 } 9406 9407 // Handle attributes. 9408 ProcessDeclAttributes(S, NewFD, D); 9409 9410 if (getLangOpts().OpenCL) { 9411 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9412 // type declaration will generate a compilation error. 9413 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9414 if (AddressSpace != LangAS::Default) { 9415 Diag(NewFD->getLocation(), 9416 diag::err_opencl_return_value_with_address_space); 9417 NewFD->setInvalidDecl(); 9418 } 9419 } 9420 9421 if (!getLangOpts().CPlusPlus) { 9422 // Perform semantic checking on the function declaration. 9423 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9424 CheckMain(NewFD, D.getDeclSpec()); 9425 9426 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9427 CheckMSVCRTEntryPoint(NewFD); 9428 9429 if (!NewFD->isInvalidDecl()) 9430 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9431 isMemberSpecialization)); 9432 else if (!Previous.empty()) 9433 // Recover gracefully from an invalid redeclaration. 9434 D.setRedeclaration(true); 9435 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9436 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9437 "previous declaration set still overloaded"); 9438 9439 // Diagnose no-prototype function declarations with calling conventions that 9440 // don't support variadic calls. Only do this in C and do it after merging 9441 // possibly prototyped redeclarations. 9442 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9443 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9444 CallingConv CC = FT->getExtInfo().getCC(); 9445 if (!supportsVariadicCall(CC)) { 9446 // Windows system headers sometimes accidentally use stdcall without 9447 // (void) parameters, so we relax this to a warning. 9448 int DiagID = 9449 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9450 Diag(NewFD->getLocation(), DiagID) 9451 << FunctionType::getNameForCallConv(CC); 9452 } 9453 } 9454 9455 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9456 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9457 checkNonTrivialCUnion(NewFD->getReturnType(), 9458 NewFD->getReturnTypeSourceRange().getBegin(), 9459 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9460 } else { 9461 // C++11 [replacement.functions]p3: 9462 // The program's definitions shall not be specified as inline. 9463 // 9464 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9465 // 9466 // Suppress the diagnostic if the function is __attribute__((used)), since 9467 // that forces an external definition to be emitted. 9468 if (D.getDeclSpec().isInlineSpecified() && 9469 NewFD->isReplaceableGlobalAllocationFunction() && 9470 !NewFD->hasAttr<UsedAttr>()) 9471 Diag(D.getDeclSpec().getInlineSpecLoc(), 9472 diag::ext_operator_new_delete_declared_inline) 9473 << NewFD->getDeclName(); 9474 9475 // If the declarator is a template-id, translate the parser's template 9476 // argument list into our AST format. 9477 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9478 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9479 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9480 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9481 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9482 TemplateId->NumArgs); 9483 translateTemplateArguments(TemplateArgsPtr, 9484 TemplateArgs); 9485 9486 HasExplicitTemplateArgs = true; 9487 9488 if (NewFD->isInvalidDecl()) { 9489 HasExplicitTemplateArgs = false; 9490 } else if (FunctionTemplate) { 9491 // Function template with explicit template arguments. 9492 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9493 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9494 9495 HasExplicitTemplateArgs = false; 9496 } else { 9497 assert((isFunctionTemplateSpecialization || 9498 D.getDeclSpec().isFriendSpecified()) && 9499 "should have a 'template<>' for this decl"); 9500 // "friend void foo<>(int);" is an implicit specialization decl. 9501 isFunctionTemplateSpecialization = true; 9502 } 9503 } else if (isFriend && isFunctionTemplateSpecialization) { 9504 // This combination is only possible in a recovery case; the user 9505 // wrote something like: 9506 // template <> friend void foo(int); 9507 // which we're recovering from as if the user had written: 9508 // friend void foo<>(int); 9509 // Go ahead and fake up a template id. 9510 HasExplicitTemplateArgs = true; 9511 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9512 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9513 } 9514 9515 // We do not add HD attributes to specializations here because 9516 // they may have different constexpr-ness compared to their 9517 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9518 // may end up with different effective targets. Instead, a 9519 // specialization inherits its target attributes from its template 9520 // in the CheckFunctionTemplateSpecialization() call below. 9521 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9522 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9523 9524 // If it's a friend (and only if it's a friend), it's possible 9525 // that either the specialized function type or the specialized 9526 // template is dependent, and therefore matching will fail. In 9527 // this case, don't check the specialization yet. 9528 if (isFunctionTemplateSpecialization && isFriend && 9529 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9530 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9531 TemplateArgs.arguments()))) { 9532 assert(HasExplicitTemplateArgs && 9533 "friend function specialization without template args"); 9534 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9535 Previous)) 9536 NewFD->setInvalidDecl(); 9537 } else if (isFunctionTemplateSpecialization) { 9538 if (CurContext->isDependentContext() && CurContext->isRecord() 9539 && !isFriend) { 9540 isDependentClassScopeExplicitSpecialization = true; 9541 } else if (!NewFD->isInvalidDecl() && 9542 CheckFunctionTemplateSpecialization( 9543 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9544 Previous)) 9545 NewFD->setInvalidDecl(); 9546 9547 // C++ [dcl.stc]p1: 9548 // A storage-class-specifier shall not be specified in an explicit 9549 // specialization (14.7.3) 9550 FunctionTemplateSpecializationInfo *Info = 9551 NewFD->getTemplateSpecializationInfo(); 9552 if (Info && SC != SC_None) { 9553 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9554 Diag(NewFD->getLocation(), 9555 diag::err_explicit_specialization_inconsistent_storage_class) 9556 << SC 9557 << FixItHint::CreateRemoval( 9558 D.getDeclSpec().getStorageClassSpecLoc()); 9559 9560 else 9561 Diag(NewFD->getLocation(), 9562 diag::ext_explicit_specialization_storage_class) 9563 << FixItHint::CreateRemoval( 9564 D.getDeclSpec().getStorageClassSpecLoc()); 9565 } 9566 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9567 if (CheckMemberSpecialization(NewFD, Previous)) 9568 NewFD->setInvalidDecl(); 9569 } 9570 9571 // Perform semantic checking on the function declaration. 9572 if (!isDependentClassScopeExplicitSpecialization) { 9573 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9574 CheckMain(NewFD, D.getDeclSpec()); 9575 9576 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9577 CheckMSVCRTEntryPoint(NewFD); 9578 9579 if (!NewFD->isInvalidDecl()) 9580 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9581 isMemberSpecialization)); 9582 else if (!Previous.empty()) 9583 // Recover gracefully from an invalid redeclaration. 9584 D.setRedeclaration(true); 9585 } 9586 9587 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9588 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9589 "previous declaration set still overloaded"); 9590 9591 NamedDecl *PrincipalDecl = (FunctionTemplate 9592 ? cast<NamedDecl>(FunctionTemplate) 9593 : NewFD); 9594 9595 if (isFriend && NewFD->getPreviousDecl()) { 9596 AccessSpecifier Access = AS_public; 9597 if (!NewFD->isInvalidDecl()) 9598 Access = NewFD->getPreviousDecl()->getAccess(); 9599 9600 NewFD->setAccess(Access); 9601 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9602 } 9603 9604 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9605 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9606 PrincipalDecl->setNonMemberOperator(); 9607 9608 // If we have a function template, check the template parameter 9609 // list. This will check and merge default template arguments. 9610 if (FunctionTemplate) { 9611 FunctionTemplateDecl *PrevTemplate = 9612 FunctionTemplate->getPreviousDecl(); 9613 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9614 PrevTemplate ? PrevTemplate->getTemplateParameters() 9615 : nullptr, 9616 D.getDeclSpec().isFriendSpecified() 9617 ? (D.isFunctionDefinition() 9618 ? TPC_FriendFunctionTemplateDefinition 9619 : TPC_FriendFunctionTemplate) 9620 : (D.getCXXScopeSpec().isSet() && 9621 DC && DC->isRecord() && 9622 DC->isDependentContext()) 9623 ? TPC_ClassTemplateMember 9624 : TPC_FunctionTemplate); 9625 } 9626 9627 if (NewFD->isInvalidDecl()) { 9628 // Ignore all the rest of this. 9629 } else if (!D.isRedeclaration()) { 9630 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9631 AddToScope }; 9632 // Fake up an access specifier if it's supposed to be a class member. 9633 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9634 NewFD->setAccess(AS_public); 9635 9636 // Qualified decls generally require a previous declaration. 9637 if (D.getCXXScopeSpec().isSet()) { 9638 // ...with the major exception of templated-scope or 9639 // dependent-scope friend declarations. 9640 9641 // TODO: we currently also suppress this check in dependent 9642 // contexts because (1) the parameter depth will be off when 9643 // matching friend templates and (2) we might actually be 9644 // selecting a friend based on a dependent factor. But there 9645 // are situations where these conditions don't apply and we 9646 // can actually do this check immediately. 9647 // 9648 // Unless the scope is dependent, it's always an error if qualified 9649 // redeclaration lookup found nothing at all. Diagnose that now; 9650 // nothing will diagnose that error later. 9651 if (isFriend && 9652 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9653 (!Previous.empty() && CurContext->isDependentContext()))) { 9654 // ignore these 9655 } else { 9656 // The user tried to provide an out-of-line definition for a 9657 // function that is a member of a class or namespace, but there 9658 // was no such member function declared (C++ [class.mfct]p2, 9659 // C++ [namespace.memdef]p2). For example: 9660 // 9661 // class X { 9662 // void f() const; 9663 // }; 9664 // 9665 // void X::f() { } // ill-formed 9666 // 9667 // Complain about this problem, and attempt to suggest close 9668 // matches (e.g., those that differ only in cv-qualifiers and 9669 // whether the parameter types are references). 9670 9671 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9672 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9673 AddToScope = ExtraArgs.AddToScope; 9674 return Result; 9675 } 9676 } 9677 9678 // Unqualified local friend declarations are required to resolve 9679 // to something. 9680 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9681 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9682 *this, Previous, NewFD, ExtraArgs, true, S)) { 9683 AddToScope = ExtraArgs.AddToScope; 9684 return Result; 9685 } 9686 } 9687 } else if (!D.isFunctionDefinition() && 9688 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9689 !isFriend && !isFunctionTemplateSpecialization && 9690 !isMemberSpecialization) { 9691 // An out-of-line member function declaration must also be a 9692 // definition (C++ [class.mfct]p2). 9693 // Note that this is not the case for explicit specializations of 9694 // function templates or member functions of class templates, per 9695 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9696 // extension for compatibility with old SWIG code which likes to 9697 // generate them. 9698 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9699 << D.getCXXScopeSpec().getRange(); 9700 } 9701 } 9702 9703 // If this is the first declaration of a library builtin function, add 9704 // attributes as appropriate. 9705 if (!D.isRedeclaration() && 9706 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9707 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9708 if (unsigned BuiltinID = II->getBuiltinID()) { 9709 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9710 // Validate the type matches unless this builtin is specified as 9711 // matching regardless of its declared type. 9712 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9713 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9714 } else { 9715 ASTContext::GetBuiltinTypeError Error; 9716 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9717 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9718 9719 if (!Error && !BuiltinType.isNull() && 9720 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9721 NewFD->getType(), BuiltinType)) 9722 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9723 } 9724 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9725 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9726 // FIXME: We should consider this a builtin only in the std namespace. 9727 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9728 } 9729 } 9730 } 9731 } 9732 9733 ProcessPragmaWeak(S, NewFD); 9734 checkAttributesAfterMerging(*this, *NewFD); 9735 9736 AddKnownFunctionAttributes(NewFD); 9737 9738 if (NewFD->hasAttr<OverloadableAttr>() && 9739 !NewFD->getType()->getAs<FunctionProtoType>()) { 9740 Diag(NewFD->getLocation(), 9741 diag::err_attribute_overloadable_no_prototype) 9742 << NewFD; 9743 9744 // Turn this into a variadic function with no parameters. 9745 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9746 FunctionProtoType::ExtProtoInfo EPI( 9747 Context.getDefaultCallingConvention(true, false)); 9748 EPI.Variadic = true; 9749 EPI.ExtInfo = FT->getExtInfo(); 9750 9751 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9752 NewFD->setType(R); 9753 } 9754 9755 // If there's a #pragma GCC visibility in scope, and this isn't a class 9756 // member, set the visibility of this function. 9757 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9758 AddPushedVisibilityAttribute(NewFD); 9759 9760 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9761 // marking the function. 9762 AddCFAuditedAttribute(NewFD); 9763 9764 // If this is a function definition, check if we have to apply optnone due to 9765 // a pragma. 9766 if(D.isFunctionDefinition()) 9767 AddRangeBasedOptnone(NewFD); 9768 9769 // If this is the first declaration of an extern C variable, update 9770 // the map of such variables. 9771 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9772 isIncompleteDeclExternC(*this, NewFD)) 9773 RegisterLocallyScopedExternCDecl(NewFD, S); 9774 9775 // Set this FunctionDecl's range up to the right paren. 9776 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9777 9778 if (D.isRedeclaration() && !Previous.empty()) { 9779 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9780 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9781 isMemberSpecialization || 9782 isFunctionTemplateSpecialization, 9783 D.isFunctionDefinition()); 9784 } 9785 9786 if (getLangOpts().CUDA) { 9787 IdentifierInfo *II = NewFD->getIdentifier(); 9788 if (II && II->isStr(getCudaConfigureFuncName()) && 9789 !NewFD->isInvalidDecl() && 9790 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9791 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9792 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9793 << getCudaConfigureFuncName(); 9794 Context.setcudaConfigureCallDecl(NewFD); 9795 } 9796 9797 // Variadic functions, other than a *declaration* of printf, are not allowed 9798 // in device-side CUDA code, unless someone passed 9799 // -fcuda-allow-variadic-functions. 9800 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9801 (NewFD->hasAttr<CUDADeviceAttr>() || 9802 NewFD->hasAttr<CUDAGlobalAttr>()) && 9803 !(II && II->isStr("printf") && NewFD->isExternC() && 9804 !D.isFunctionDefinition())) { 9805 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9806 } 9807 } 9808 9809 MarkUnusedFileScopedDecl(NewFD); 9810 9811 9812 9813 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9814 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9815 if ((getLangOpts().OpenCLVersion >= 120) 9816 && (SC == SC_Static)) { 9817 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9818 D.setInvalidType(); 9819 } 9820 9821 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9822 if (!NewFD->getReturnType()->isVoidType()) { 9823 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9824 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9825 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9826 : FixItHint()); 9827 D.setInvalidType(); 9828 } 9829 9830 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9831 for (auto Param : NewFD->parameters()) 9832 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9833 9834 if (getLangOpts().OpenCLCPlusPlus) { 9835 if (DC->isRecord()) { 9836 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9837 D.setInvalidType(); 9838 } 9839 if (FunctionTemplate) { 9840 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9841 D.setInvalidType(); 9842 } 9843 } 9844 } 9845 9846 if (getLangOpts().CPlusPlus) { 9847 if (FunctionTemplate) { 9848 if (NewFD->isInvalidDecl()) 9849 FunctionTemplate->setInvalidDecl(); 9850 return FunctionTemplate; 9851 } 9852 9853 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9854 CompleteMemberSpecialization(NewFD, Previous); 9855 } 9856 9857 for (const ParmVarDecl *Param : NewFD->parameters()) { 9858 QualType PT = Param->getType(); 9859 9860 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9861 // types. 9862 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9863 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9864 QualType ElemTy = PipeTy->getElementType(); 9865 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9866 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9867 D.setInvalidType(); 9868 } 9869 } 9870 } 9871 } 9872 9873 // Here we have an function template explicit specialization at class scope. 9874 // The actual specialization will be postponed to template instatiation 9875 // time via the ClassScopeFunctionSpecializationDecl node. 9876 if (isDependentClassScopeExplicitSpecialization) { 9877 ClassScopeFunctionSpecializationDecl *NewSpec = 9878 ClassScopeFunctionSpecializationDecl::Create( 9879 Context, CurContext, NewFD->getLocation(), 9880 cast<CXXMethodDecl>(NewFD), 9881 HasExplicitTemplateArgs, TemplateArgs); 9882 CurContext->addDecl(NewSpec); 9883 AddToScope = false; 9884 } 9885 9886 // Diagnose availability attributes. Availability cannot be used on functions 9887 // that are run during load/unload. 9888 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9889 if (NewFD->hasAttr<ConstructorAttr>()) { 9890 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9891 << 1; 9892 NewFD->dropAttr<AvailabilityAttr>(); 9893 } 9894 if (NewFD->hasAttr<DestructorAttr>()) { 9895 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9896 << 2; 9897 NewFD->dropAttr<AvailabilityAttr>(); 9898 } 9899 } 9900 9901 // Diagnose no_builtin attribute on function declaration that are not a 9902 // definition. 9903 // FIXME: We should really be doing this in 9904 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9905 // the FunctionDecl and at this point of the code 9906 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9907 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9908 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9909 switch (D.getFunctionDefinitionKind()) { 9910 case FunctionDefinitionKind::Defaulted: 9911 case FunctionDefinitionKind::Deleted: 9912 Diag(NBA->getLocation(), 9913 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9914 << NBA->getSpelling(); 9915 break; 9916 case FunctionDefinitionKind::Declaration: 9917 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9918 << NBA->getSpelling(); 9919 break; 9920 case FunctionDefinitionKind::Definition: 9921 break; 9922 } 9923 9924 return NewFD; 9925 } 9926 9927 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9928 /// when __declspec(code_seg) "is applied to a class, all member functions of 9929 /// the class and nested classes -- this includes compiler-generated special 9930 /// member functions -- are put in the specified segment." 9931 /// The actual behavior is a little more complicated. The Microsoft compiler 9932 /// won't check outer classes if there is an active value from #pragma code_seg. 9933 /// The CodeSeg is always applied from the direct parent but only from outer 9934 /// classes when the #pragma code_seg stack is empty. See: 9935 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9936 /// available since MS has removed the page. 9937 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9938 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9939 if (!Method) 9940 return nullptr; 9941 const CXXRecordDecl *Parent = Method->getParent(); 9942 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9943 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9944 NewAttr->setImplicit(true); 9945 return NewAttr; 9946 } 9947 9948 // The Microsoft compiler won't check outer classes for the CodeSeg 9949 // when the #pragma code_seg stack is active. 9950 if (S.CodeSegStack.CurrentValue) 9951 return nullptr; 9952 9953 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9954 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9955 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9956 NewAttr->setImplicit(true); 9957 return NewAttr; 9958 } 9959 } 9960 return nullptr; 9961 } 9962 9963 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9964 /// containing class. Otherwise it will return implicit SectionAttr if the 9965 /// function is a definition and there is an active value on CodeSegStack 9966 /// (from the current #pragma code-seg value). 9967 /// 9968 /// \param FD Function being declared. 9969 /// \param IsDefinition Whether it is a definition or just a declarartion. 9970 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9971 /// nullptr if no attribute should be added. 9972 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9973 bool IsDefinition) { 9974 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9975 return A; 9976 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9977 CodeSegStack.CurrentValue) 9978 return SectionAttr::CreateImplicit( 9979 getASTContext(), CodeSegStack.CurrentValue->getString(), 9980 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9981 SectionAttr::Declspec_allocate); 9982 return nullptr; 9983 } 9984 9985 /// Determines if we can perform a correct type check for \p D as a 9986 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9987 /// best-effort check. 9988 /// 9989 /// \param NewD The new declaration. 9990 /// \param OldD The old declaration. 9991 /// \param NewT The portion of the type of the new declaration to check. 9992 /// \param OldT The portion of the type of the old declaration to check. 9993 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9994 QualType NewT, QualType OldT) { 9995 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9996 return true; 9997 9998 // For dependently-typed local extern declarations and friends, we can't 9999 // perform a correct type check in general until instantiation: 10000 // 10001 // int f(); 10002 // template<typename T> void g() { T f(); } 10003 // 10004 // (valid if g() is only instantiated with T = int). 10005 if (NewT->isDependentType() && 10006 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10007 return false; 10008 10009 // Similarly, if the previous declaration was a dependent local extern 10010 // declaration, we don't really know its type yet. 10011 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10012 return false; 10013 10014 return true; 10015 } 10016 10017 /// Checks if the new declaration declared in dependent context must be 10018 /// put in the same redeclaration chain as the specified declaration. 10019 /// 10020 /// \param D Declaration that is checked. 10021 /// \param PrevDecl Previous declaration found with proper lookup method for the 10022 /// same declaration name. 10023 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10024 /// belongs to. 10025 /// 10026 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10027 if (!D->getLexicalDeclContext()->isDependentContext()) 10028 return true; 10029 10030 // Don't chain dependent friend function definitions until instantiation, to 10031 // permit cases like 10032 // 10033 // void func(); 10034 // template<typename T> class C1 { friend void func() {} }; 10035 // template<typename T> class C2 { friend void func() {} }; 10036 // 10037 // ... which is valid if only one of C1 and C2 is ever instantiated. 10038 // 10039 // FIXME: This need only apply to function definitions. For now, we proxy 10040 // this by checking for a file-scope function. We do not want this to apply 10041 // to friend declarations nominating member functions, because that gets in 10042 // the way of access checks. 10043 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10044 return false; 10045 10046 auto *VD = dyn_cast<ValueDecl>(D); 10047 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10048 return !VD || !PrevVD || 10049 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10050 PrevVD->getType()); 10051 } 10052 10053 /// Check the target attribute of the function for MultiVersion 10054 /// validity. 10055 /// 10056 /// Returns true if there was an error, false otherwise. 10057 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10058 const auto *TA = FD->getAttr<TargetAttr>(); 10059 assert(TA && "MultiVersion Candidate requires a target attribute"); 10060 ParsedTargetAttr ParseInfo = TA->parse(); 10061 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10062 enum ErrType { Feature = 0, Architecture = 1 }; 10063 10064 if (!ParseInfo.Architecture.empty() && 10065 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10066 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10067 << Architecture << ParseInfo.Architecture; 10068 return true; 10069 } 10070 10071 for (const auto &Feat : ParseInfo.Features) { 10072 auto BareFeat = StringRef{Feat}.substr(1); 10073 if (Feat[0] == '-') { 10074 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10075 << Feature << ("no-" + BareFeat).str(); 10076 return true; 10077 } 10078 10079 if (!TargetInfo.validateCpuSupports(BareFeat) || 10080 !TargetInfo.isValidFeatureName(BareFeat)) { 10081 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10082 << Feature << BareFeat; 10083 return true; 10084 } 10085 } 10086 return false; 10087 } 10088 10089 // Provide a white-list of attributes that are allowed to be combined with 10090 // multiversion functions. 10091 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10092 MultiVersionKind MVType) { 10093 // Note: this list/diagnosis must match the list in 10094 // checkMultiversionAttributesAllSame. 10095 switch (Kind) { 10096 default: 10097 return false; 10098 case attr::Used: 10099 return MVType == MultiVersionKind::Target; 10100 case attr::NonNull: 10101 case attr::NoThrow: 10102 return true; 10103 } 10104 } 10105 10106 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10107 const FunctionDecl *FD, 10108 const FunctionDecl *CausedFD, 10109 MultiVersionKind MVType) { 10110 bool IsCPUSpecificCPUDispatchMVType = 10111 MVType == MultiVersionKind::CPUDispatch || 10112 MVType == MultiVersionKind::CPUSpecific; 10113 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10114 Sema &S, const Attr *A) { 10115 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10116 << IsCPUSpecificCPUDispatchMVType << A; 10117 if (CausedFD) 10118 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10119 return true; 10120 }; 10121 10122 for (const Attr *A : FD->attrs()) { 10123 switch (A->getKind()) { 10124 case attr::CPUDispatch: 10125 case attr::CPUSpecific: 10126 if (MVType != MultiVersionKind::CPUDispatch && 10127 MVType != MultiVersionKind::CPUSpecific) 10128 return Diagnose(S, A); 10129 break; 10130 case attr::Target: 10131 if (MVType != MultiVersionKind::Target) 10132 return Diagnose(S, A); 10133 break; 10134 default: 10135 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10136 return Diagnose(S, A); 10137 break; 10138 } 10139 } 10140 return false; 10141 } 10142 10143 bool Sema::areMultiversionVariantFunctionsCompatible( 10144 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10145 const PartialDiagnostic &NoProtoDiagID, 10146 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10147 const PartialDiagnosticAt &NoSupportDiagIDAt, 10148 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10149 bool ConstexprSupported, bool CLinkageMayDiffer) { 10150 enum DoesntSupport { 10151 FuncTemplates = 0, 10152 VirtFuncs = 1, 10153 DeducedReturn = 2, 10154 Constructors = 3, 10155 Destructors = 4, 10156 DeletedFuncs = 5, 10157 DefaultedFuncs = 6, 10158 ConstexprFuncs = 7, 10159 ConstevalFuncs = 8, 10160 }; 10161 enum Different { 10162 CallingConv = 0, 10163 ReturnType = 1, 10164 ConstexprSpec = 2, 10165 InlineSpec = 3, 10166 StorageClass = 4, 10167 Linkage = 5, 10168 }; 10169 10170 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10171 !OldFD->getType()->getAs<FunctionProtoType>()) { 10172 Diag(OldFD->getLocation(), NoProtoDiagID); 10173 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10174 return true; 10175 } 10176 10177 if (NoProtoDiagID.getDiagID() != 0 && 10178 !NewFD->getType()->getAs<FunctionProtoType>()) 10179 return Diag(NewFD->getLocation(), NoProtoDiagID); 10180 10181 if (!TemplatesSupported && 10182 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10183 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10184 << FuncTemplates; 10185 10186 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10187 if (NewCXXFD->isVirtual()) 10188 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10189 << VirtFuncs; 10190 10191 if (isa<CXXConstructorDecl>(NewCXXFD)) 10192 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10193 << Constructors; 10194 10195 if (isa<CXXDestructorDecl>(NewCXXFD)) 10196 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10197 << Destructors; 10198 } 10199 10200 if (NewFD->isDeleted()) 10201 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10202 << DeletedFuncs; 10203 10204 if (NewFD->isDefaulted()) 10205 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10206 << DefaultedFuncs; 10207 10208 if (!ConstexprSupported && NewFD->isConstexpr()) 10209 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10210 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10211 10212 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10213 const auto *NewType = cast<FunctionType>(NewQType); 10214 QualType NewReturnType = NewType->getReturnType(); 10215 10216 if (NewReturnType->isUndeducedType()) 10217 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10218 << DeducedReturn; 10219 10220 // Ensure the return type is identical. 10221 if (OldFD) { 10222 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10223 const auto *OldType = cast<FunctionType>(OldQType); 10224 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10225 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10226 10227 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10228 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10229 10230 QualType OldReturnType = OldType->getReturnType(); 10231 10232 if (OldReturnType != NewReturnType) 10233 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10234 10235 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10236 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10237 10238 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10239 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10240 10241 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10242 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10243 10244 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10245 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10246 10247 if (CheckEquivalentExceptionSpec( 10248 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10249 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10250 return true; 10251 } 10252 return false; 10253 } 10254 10255 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10256 const FunctionDecl *NewFD, 10257 bool CausesMV, 10258 MultiVersionKind MVType) { 10259 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10260 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10261 if (OldFD) 10262 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10263 return true; 10264 } 10265 10266 bool IsCPUSpecificCPUDispatchMVType = 10267 MVType == MultiVersionKind::CPUDispatch || 10268 MVType == MultiVersionKind::CPUSpecific; 10269 10270 if (CausesMV && OldFD && 10271 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10272 return true; 10273 10274 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10275 return true; 10276 10277 // Only allow transition to MultiVersion if it hasn't been used. 10278 if (OldFD && CausesMV && OldFD->isUsed(false)) 10279 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10280 10281 return S.areMultiversionVariantFunctionsCompatible( 10282 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10283 PartialDiagnosticAt(NewFD->getLocation(), 10284 S.PDiag(diag::note_multiversioning_caused_here)), 10285 PartialDiagnosticAt(NewFD->getLocation(), 10286 S.PDiag(diag::err_multiversion_doesnt_support) 10287 << IsCPUSpecificCPUDispatchMVType), 10288 PartialDiagnosticAt(NewFD->getLocation(), 10289 S.PDiag(diag::err_multiversion_diff)), 10290 /*TemplatesSupported=*/false, 10291 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10292 /*CLinkageMayDiffer=*/false); 10293 } 10294 10295 /// Check the validity of a multiversion function declaration that is the 10296 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10297 /// 10298 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10299 /// 10300 /// Returns true if there was an error, false otherwise. 10301 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10302 MultiVersionKind MVType, 10303 const TargetAttr *TA) { 10304 assert(MVType != MultiVersionKind::None && 10305 "Function lacks multiversion attribute"); 10306 10307 // Target only causes MV if it is default, otherwise this is a normal 10308 // function. 10309 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10310 return false; 10311 10312 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10313 FD->setInvalidDecl(); 10314 return true; 10315 } 10316 10317 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10318 FD->setInvalidDecl(); 10319 return true; 10320 } 10321 10322 FD->setIsMultiVersion(); 10323 return false; 10324 } 10325 10326 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10327 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10328 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10329 return true; 10330 } 10331 10332 return false; 10333 } 10334 10335 static bool CheckTargetCausesMultiVersioning( 10336 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10337 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10338 LookupResult &Previous) { 10339 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10340 ParsedTargetAttr NewParsed = NewTA->parse(); 10341 // Sort order doesn't matter, it just needs to be consistent. 10342 llvm::sort(NewParsed.Features); 10343 10344 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10345 // to change, this is a simple redeclaration. 10346 if (!NewTA->isDefaultVersion() && 10347 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10348 return false; 10349 10350 // Otherwise, this decl causes MultiVersioning. 10351 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10352 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10353 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10354 NewFD->setInvalidDecl(); 10355 return true; 10356 } 10357 10358 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10359 MultiVersionKind::Target)) { 10360 NewFD->setInvalidDecl(); 10361 return true; 10362 } 10363 10364 if (CheckMultiVersionValue(S, NewFD)) { 10365 NewFD->setInvalidDecl(); 10366 return true; 10367 } 10368 10369 // If this is 'default', permit the forward declaration. 10370 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10371 Redeclaration = true; 10372 OldDecl = OldFD; 10373 OldFD->setIsMultiVersion(); 10374 NewFD->setIsMultiVersion(); 10375 return false; 10376 } 10377 10378 if (CheckMultiVersionValue(S, OldFD)) { 10379 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10380 NewFD->setInvalidDecl(); 10381 return true; 10382 } 10383 10384 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10385 10386 if (OldParsed == NewParsed) { 10387 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10388 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10389 NewFD->setInvalidDecl(); 10390 return true; 10391 } 10392 10393 for (const auto *FD : OldFD->redecls()) { 10394 const auto *CurTA = FD->getAttr<TargetAttr>(); 10395 // We allow forward declarations before ANY multiversioning attributes, but 10396 // nothing after the fact. 10397 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10398 (!CurTA || CurTA->isInherited())) { 10399 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10400 << 0; 10401 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10402 NewFD->setInvalidDecl(); 10403 return true; 10404 } 10405 } 10406 10407 OldFD->setIsMultiVersion(); 10408 NewFD->setIsMultiVersion(); 10409 Redeclaration = false; 10410 MergeTypeWithPrevious = false; 10411 OldDecl = nullptr; 10412 Previous.clear(); 10413 return false; 10414 } 10415 10416 /// Check the validity of a new function declaration being added to an existing 10417 /// multiversioned declaration collection. 10418 static bool CheckMultiVersionAdditionalDecl( 10419 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10420 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10421 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10422 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10423 LookupResult &Previous) { 10424 10425 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10426 // Disallow mixing of multiversioning types. 10427 if ((OldMVType == MultiVersionKind::Target && 10428 NewMVType != MultiVersionKind::Target) || 10429 (NewMVType == MultiVersionKind::Target && 10430 OldMVType != MultiVersionKind::Target)) { 10431 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10432 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10433 NewFD->setInvalidDecl(); 10434 return true; 10435 } 10436 10437 ParsedTargetAttr NewParsed; 10438 if (NewTA) { 10439 NewParsed = NewTA->parse(); 10440 llvm::sort(NewParsed.Features); 10441 } 10442 10443 bool UseMemberUsingDeclRules = 10444 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10445 10446 // Next, check ALL non-overloads to see if this is a redeclaration of a 10447 // previous member of the MultiVersion set. 10448 for (NamedDecl *ND : Previous) { 10449 FunctionDecl *CurFD = ND->getAsFunction(); 10450 if (!CurFD) 10451 continue; 10452 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10453 continue; 10454 10455 if (NewMVType == MultiVersionKind::Target) { 10456 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10457 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10458 NewFD->setIsMultiVersion(); 10459 Redeclaration = true; 10460 OldDecl = ND; 10461 return false; 10462 } 10463 10464 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10465 if (CurParsed == NewParsed) { 10466 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10467 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10468 NewFD->setInvalidDecl(); 10469 return true; 10470 } 10471 } else { 10472 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10473 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10474 // Handle CPUDispatch/CPUSpecific versions. 10475 // Only 1 CPUDispatch function is allowed, this will make it go through 10476 // the redeclaration errors. 10477 if (NewMVType == MultiVersionKind::CPUDispatch && 10478 CurFD->hasAttr<CPUDispatchAttr>()) { 10479 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10480 std::equal( 10481 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10482 NewCPUDisp->cpus_begin(), 10483 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10484 return Cur->getName() == New->getName(); 10485 })) { 10486 NewFD->setIsMultiVersion(); 10487 Redeclaration = true; 10488 OldDecl = ND; 10489 return false; 10490 } 10491 10492 // If the declarations don't match, this is an error condition. 10493 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10494 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10495 NewFD->setInvalidDecl(); 10496 return true; 10497 } 10498 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10499 10500 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10501 std::equal( 10502 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10503 NewCPUSpec->cpus_begin(), 10504 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10505 return Cur->getName() == New->getName(); 10506 })) { 10507 NewFD->setIsMultiVersion(); 10508 Redeclaration = true; 10509 OldDecl = ND; 10510 return false; 10511 } 10512 10513 // Only 1 version of CPUSpecific is allowed for each CPU. 10514 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10515 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10516 if (CurII == NewII) { 10517 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10518 << NewII; 10519 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10520 NewFD->setInvalidDecl(); 10521 return true; 10522 } 10523 } 10524 } 10525 } 10526 // If the two decls aren't the same MVType, there is no possible error 10527 // condition. 10528 } 10529 } 10530 10531 // Else, this is simply a non-redecl case. Checking the 'value' is only 10532 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10533 // handled in the attribute adding step. 10534 if (NewMVType == MultiVersionKind::Target && 10535 CheckMultiVersionValue(S, NewFD)) { 10536 NewFD->setInvalidDecl(); 10537 return true; 10538 } 10539 10540 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10541 !OldFD->isMultiVersion(), NewMVType)) { 10542 NewFD->setInvalidDecl(); 10543 return true; 10544 } 10545 10546 // Permit forward declarations in the case where these two are compatible. 10547 if (!OldFD->isMultiVersion()) { 10548 OldFD->setIsMultiVersion(); 10549 NewFD->setIsMultiVersion(); 10550 Redeclaration = true; 10551 OldDecl = OldFD; 10552 return false; 10553 } 10554 10555 NewFD->setIsMultiVersion(); 10556 Redeclaration = false; 10557 MergeTypeWithPrevious = false; 10558 OldDecl = nullptr; 10559 Previous.clear(); 10560 return false; 10561 } 10562 10563 10564 /// Check the validity of a mulitversion function declaration. 10565 /// Also sets the multiversion'ness' of the function itself. 10566 /// 10567 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10568 /// 10569 /// Returns true if there was an error, false otherwise. 10570 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10571 bool &Redeclaration, NamedDecl *&OldDecl, 10572 bool &MergeTypeWithPrevious, 10573 LookupResult &Previous) { 10574 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10575 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10576 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10577 10578 // Mixing Multiversioning types is prohibited. 10579 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10580 (NewCPUDisp && NewCPUSpec)) { 10581 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10582 NewFD->setInvalidDecl(); 10583 return true; 10584 } 10585 10586 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10587 10588 // Main isn't allowed to become a multiversion function, however it IS 10589 // permitted to have 'main' be marked with the 'target' optimization hint. 10590 if (NewFD->isMain()) { 10591 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10592 MVType == MultiVersionKind::CPUDispatch || 10593 MVType == MultiVersionKind::CPUSpecific) { 10594 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10595 NewFD->setInvalidDecl(); 10596 return true; 10597 } 10598 return false; 10599 } 10600 10601 if (!OldDecl || !OldDecl->getAsFunction() || 10602 OldDecl->getDeclContext()->getRedeclContext() != 10603 NewFD->getDeclContext()->getRedeclContext()) { 10604 // If there's no previous declaration, AND this isn't attempting to cause 10605 // multiversioning, this isn't an error condition. 10606 if (MVType == MultiVersionKind::None) 10607 return false; 10608 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10609 } 10610 10611 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10612 10613 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10614 return false; 10615 10616 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10617 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10618 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10619 NewFD->setInvalidDecl(); 10620 return true; 10621 } 10622 10623 // Handle the target potentially causes multiversioning case. 10624 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10625 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10626 Redeclaration, OldDecl, 10627 MergeTypeWithPrevious, Previous); 10628 10629 // At this point, we have a multiversion function decl (in OldFD) AND an 10630 // appropriate attribute in the current function decl. Resolve that these are 10631 // still compatible with previous declarations. 10632 return CheckMultiVersionAdditionalDecl( 10633 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10634 OldDecl, MergeTypeWithPrevious, Previous); 10635 } 10636 10637 /// Perform semantic checking of a new function declaration. 10638 /// 10639 /// Performs semantic analysis of the new function declaration 10640 /// NewFD. This routine performs all semantic checking that does not 10641 /// require the actual declarator involved in the declaration, and is 10642 /// used both for the declaration of functions as they are parsed 10643 /// (called via ActOnDeclarator) and for the declaration of functions 10644 /// that have been instantiated via C++ template instantiation (called 10645 /// via InstantiateDecl). 10646 /// 10647 /// \param IsMemberSpecialization whether this new function declaration is 10648 /// a member specialization (that replaces any definition provided by the 10649 /// previous declaration). 10650 /// 10651 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10652 /// 10653 /// \returns true if the function declaration is a redeclaration. 10654 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10655 LookupResult &Previous, 10656 bool IsMemberSpecialization) { 10657 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10658 "Variably modified return types are not handled here"); 10659 10660 // Determine whether the type of this function should be merged with 10661 // a previous visible declaration. This never happens for functions in C++, 10662 // and always happens in C if the previous declaration was visible. 10663 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10664 !Previous.isShadowed(); 10665 10666 bool Redeclaration = false; 10667 NamedDecl *OldDecl = nullptr; 10668 bool MayNeedOverloadableChecks = false; 10669 10670 // Merge or overload the declaration with an existing declaration of 10671 // the same name, if appropriate. 10672 if (!Previous.empty()) { 10673 // Determine whether NewFD is an overload of PrevDecl or 10674 // a declaration that requires merging. If it's an overload, 10675 // there's no more work to do here; we'll just add the new 10676 // function to the scope. 10677 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10678 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10679 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10680 Redeclaration = true; 10681 OldDecl = Candidate; 10682 } 10683 } else { 10684 MayNeedOverloadableChecks = true; 10685 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10686 /*NewIsUsingDecl*/ false)) { 10687 case Ovl_Match: 10688 Redeclaration = true; 10689 break; 10690 10691 case Ovl_NonFunction: 10692 Redeclaration = true; 10693 break; 10694 10695 case Ovl_Overload: 10696 Redeclaration = false; 10697 break; 10698 } 10699 } 10700 } 10701 10702 // Check for a previous extern "C" declaration with this name. 10703 if (!Redeclaration && 10704 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10705 if (!Previous.empty()) { 10706 // This is an extern "C" declaration with the same name as a previous 10707 // declaration, and thus redeclares that entity... 10708 Redeclaration = true; 10709 OldDecl = Previous.getFoundDecl(); 10710 MergeTypeWithPrevious = false; 10711 10712 // ... except in the presence of __attribute__((overloadable)). 10713 if (OldDecl->hasAttr<OverloadableAttr>() || 10714 NewFD->hasAttr<OverloadableAttr>()) { 10715 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10716 MayNeedOverloadableChecks = true; 10717 Redeclaration = false; 10718 OldDecl = nullptr; 10719 } 10720 } 10721 } 10722 } 10723 10724 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10725 MergeTypeWithPrevious, Previous)) 10726 return Redeclaration; 10727 10728 // PPC MMA non-pointer types are not allowed as function return types. 10729 if (Context.getTargetInfo().getTriple().isPPC64() && 10730 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10731 NewFD->setInvalidDecl(); 10732 } 10733 10734 // C++11 [dcl.constexpr]p8: 10735 // A constexpr specifier for a non-static member function that is not 10736 // a constructor declares that member function to be const. 10737 // 10738 // This needs to be delayed until we know whether this is an out-of-line 10739 // definition of a static member function. 10740 // 10741 // This rule is not present in C++1y, so we produce a backwards 10742 // compatibility warning whenever it happens in C++11. 10743 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10744 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10745 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10746 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10747 CXXMethodDecl *OldMD = nullptr; 10748 if (OldDecl) 10749 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10750 if (!OldMD || !OldMD->isStatic()) { 10751 const FunctionProtoType *FPT = 10752 MD->getType()->castAs<FunctionProtoType>(); 10753 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10754 EPI.TypeQuals.addConst(); 10755 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10756 FPT->getParamTypes(), EPI)); 10757 10758 // Warn that we did this, if we're not performing template instantiation. 10759 // In that case, we'll have warned already when the template was defined. 10760 if (!inTemplateInstantiation()) { 10761 SourceLocation AddConstLoc; 10762 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10763 .IgnoreParens().getAs<FunctionTypeLoc>()) 10764 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10765 10766 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10767 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10768 } 10769 } 10770 } 10771 10772 if (Redeclaration) { 10773 // NewFD and OldDecl represent declarations that need to be 10774 // merged. 10775 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10776 NewFD->setInvalidDecl(); 10777 return Redeclaration; 10778 } 10779 10780 Previous.clear(); 10781 Previous.addDecl(OldDecl); 10782 10783 if (FunctionTemplateDecl *OldTemplateDecl = 10784 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10785 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10786 FunctionTemplateDecl *NewTemplateDecl 10787 = NewFD->getDescribedFunctionTemplate(); 10788 assert(NewTemplateDecl && "Template/non-template mismatch"); 10789 10790 // The call to MergeFunctionDecl above may have created some state in 10791 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10792 // can add it as a redeclaration. 10793 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10794 10795 NewFD->setPreviousDeclaration(OldFD); 10796 if (NewFD->isCXXClassMember()) { 10797 NewFD->setAccess(OldTemplateDecl->getAccess()); 10798 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10799 } 10800 10801 // If this is an explicit specialization of a member that is a function 10802 // template, mark it as a member specialization. 10803 if (IsMemberSpecialization && 10804 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10805 NewTemplateDecl->setMemberSpecialization(); 10806 assert(OldTemplateDecl->isMemberSpecialization()); 10807 // Explicit specializations of a member template do not inherit deleted 10808 // status from the parent member template that they are specializing. 10809 if (OldFD->isDeleted()) { 10810 // FIXME: This assert will not hold in the presence of modules. 10811 assert(OldFD->getCanonicalDecl() == OldFD); 10812 // FIXME: We need an update record for this AST mutation. 10813 OldFD->setDeletedAsWritten(false); 10814 } 10815 } 10816 10817 } else { 10818 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10819 auto *OldFD = cast<FunctionDecl>(OldDecl); 10820 // This needs to happen first so that 'inline' propagates. 10821 NewFD->setPreviousDeclaration(OldFD); 10822 if (NewFD->isCXXClassMember()) 10823 NewFD->setAccess(OldFD->getAccess()); 10824 } 10825 } 10826 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10827 !NewFD->getAttr<OverloadableAttr>()) { 10828 assert((Previous.empty() || 10829 llvm::any_of(Previous, 10830 [](const NamedDecl *ND) { 10831 return ND->hasAttr<OverloadableAttr>(); 10832 })) && 10833 "Non-redecls shouldn't happen without overloadable present"); 10834 10835 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10836 const auto *FD = dyn_cast<FunctionDecl>(ND); 10837 return FD && !FD->hasAttr<OverloadableAttr>(); 10838 }); 10839 10840 if (OtherUnmarkedIter != Previous.end()) { 10841 Diag(NewFD->getLocation(), 10842 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10843 Diag((*OtherUnmarkedIter)->getLocation(), 10844 diag::note_attribute_overloadable_prev_overload) 10845 << false; 10846 10847 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10848 } 10849 } 10850 10851 if (LangOpts.OpenMP) 10852 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10853 10854 // Semantic checking for this function declaration (in isolation). 10855 10856 if (getLangOpts().CPlusPlus) { 10857 // C++-specific checks. 10858 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10859 CheckConstructor(Constructor); 10860 } else if (CXXDestructorDecl *Destructor = 10861 dyn_cast<CXXDestructorDecl>(NewFD)) { 10862 CXXRecordDecl *Record = Destructor->getParent(); 10863 QualType ClassType = Context.getTypeDeclType(Record); 10864 10865 // FIXME: Shouldn't we be able to perform this check even when the class 10866 // type is dependent? Both gcc and edg can handle that. 10867 if (!ClassType->isDependentType()) { 10868 DeclarationName Name 10869 = Context.DeclarationNames.getCXXDestructorName( 10870 Context.getCanonicalType(ClassType)); 10871 if (NewFD->getDeclName() != Name) { 10872 Diag(NewFD->getLocation(), diag::err_destructor_name); 10873 NewFD->setInvalidDecl(); 10874 return Redeclaration; 10875 } 10876 } 10877 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10878 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10879 CheckDeductionGuideTemplate(TD); 10880 10881 // A deduction guide is not on the list of entities that can be 10882 // explicitly specialized. 10883 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10884 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10885 << /*explicit specialization*/ 1; 10886 } 10887 10888 // Find any virtual functions that this function overrides. 10889 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10890 if (!Method->isFunctionTemplateSpecialization() && 10891 !Method->getDescribedFunctionTemplate() && 10892 Method->isCanonicalDecl()) { 10893 AddOverriddenMethods(Method->getParent(), Method); 10894 } 10895 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10896 // C++2a [class.virtual]p6 10897 // A virtual method shall not have a requires-clause. 10898 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10899 diag::err_constrained_virtual_method); 10900 10901 if (Method->isStatic()) 10902 checkThisInStaticMemberFunctionType(Method); 10903 } 10904 10905 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10906 ActOnConversionDeclarator(Conversion); 10907 10908 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10909 if (NewFD->isOverloadedOperator() && 10910 CheckOverloadedOperatorDeclaration(NewFD)) { 10911 NewFD->setInvalidDecl(); 10912 return Redeclaration; 10913 } 10914 10915 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10916 if (NewFD->getLiteralIdentifier() && 10917 CheckLiteralOperatorDeclaration(NewFD)) { 10918 NewFD->setInvalidDecl(); 10919 return Redeclaration; 10920 } 10921 10922 // In C++, check default arguments now that we have merged decls. Unless 10923 // the lexical context is the class, because in this case this is done 10924 // during delayed parsing anyway. 10925 if (!CurContext->isRecord()) 10926 CheckCXXDefaultArguments(NewFD); 10927 10928 // If this function declares a builtin function, check the type of this 10929 // declaration against the expected type for the builtin. 10930 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10931 ASTContext::GetBuiltinTypeError Error; 10932 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10933 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10934 // If the type of the builtin differs only in its exception 10935 // specification, that's OK. 10936 // FIXME: If the types do differ in this way, it would be better to 10937 // retain the 'noexcept' form of the type. 10938 if (!T.isNull() && 10939 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10940 NewFD->getType())) 10941 // The type of this function differs from the type of the builtin, 10942 // so forget about the builtin entirely. 10943 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10944 } 10945 10946 // If this function is declared as being extern "C", then check to see if 10947 // the function returns a UDT (class, struct, or union type) that is not C 10948 // compatible, and if it does, warn the user. 10949 // But, issue any diagnostic on the first declaration only. 10950 if (Previous.empty() && NewFD->isExternC()) { 10951 QualType R = NewFD->getReturnType(); 10952 if (R->isIncompleteType() && !R->isVoidType()) 10953 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10954 << NewFD << R; 10955 else if (!R.isPODType(Context) && !R->isVoidType() && 10956 !R->isObjCObjectPointerType()) 10957 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10958 } 10959 10960 // C++1z [dcl.fct]p6: 10961 // [...] whether the function has a non-throwing exception-specification 10962 // [is] part of the function type 10963 // 10964 // This results in an ABI break between C++14 and C++17 for functions whose 10965 // declared type includes an exception-specification in a parameter or 10966 // return type. (Exception specifications on the function itself are OK in 10967 // most cases, and exception specifications are not permitted in most other 10968 // contexts where they could make it into a mangling.) 10969 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10970 auto HasNoexcept = [&](QualType T) -> bool { 10971 // Strip off declarator chunks that could be between us and a function 10972 // type. We don't need to look far, exception specifications are very 10973 // restricted prior to C++17. 10974 if (auto *RT = T->getAs<ReferenceType>()) 10975 T = RT->getPointeeType(); 10976 else if (T->isAnyPointerType()) 10977 T = T->getPointeeType(); 10978 else if (auto *MPT = T->getAs<MemberPointerType>()) 10979 T = MPT->getPointeeType(); 10980 if (auto *FPT = T->getAs<FunctionProtoType>()) 10981 if (FPT->isNothrow()) 10982 return true; 10983 return false; 10984 }; 10985 10986 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10987 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10988 for (QualType T : FPT->param_types()) 10989 AnyNoexcept |= HasNoexcept(T); 10990 if (AnyNoexcept) 10991 Diag(NewFD->getLocation(), 10992 diag::warn_cxx17_compat_exception_spec_in_signature) 10993 << NewFD; 10994 } 10995 10996 if (!Redeclaration && LangOpts.CUDA) 10997 checkCUDATargetOverload(NewFD, Previous); 10998 } 10999 return Redeclaration; 11000 } 11001 11002 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11003 // C++11 [basic.start.main]p3: 11004 // A program that [...] declares main to be inline, static or 11005 // constexpr is ill-formed. 11006 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11007 // appear in a declaration of main. 11008 // static main is not an error under C99, but we should warn about it. 11009 // We accept _Noreturn main as an extension. 11010 if (FD->getStorageClass() == SC_Static) 11011 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11012 ? diag::err_static_main : diag::warn_static_main) 11013 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11014 if (FD->isInlineSpecified()) 11015 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11016 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11017 if (DS.isNoreturnSpecified()) { 11018 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11019 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11020 Diag(NoreturnLoc, diag::ext_noreturn_main); 11021 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11022 << FixItHint::CreateRemoval(NoreturnRange); 11023 } 11024 if (FD->isConstexpr()) { 11025 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11026 << FD->isConsteval() 11027 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11028 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11029 } 11030 11031 if (getLangOpts().OpenCL) { 11032 Diag(FD->getLocation(), diag::err_opencl_no_main) 11033 << FD->hasAttr<OpenCLKernelAttr>(); 11034 FD->setInvalidDecl(); 11035 return; 11036 } 11037 11038 QualType T = FD->getType(); 11039 assert(T->isFunctionType() && "function decl is not of function type"); 11040 const FunctionType* FT = T->castAs<FunctionType>(); 11041 11042 // Set default calling convention for main() 11043 if (FT->getCallConv() != CC_C) { 11044 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11045 FD->setType(QualType(FT, 0)); 11046 T = Context.getCanonicalType(FD->getType()); 11047 } 11048 11049 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11050 // In C with GNU extensions we allow main() to have non-integer return 11051 // type, but we should warn about the extension, and we disable the 11052 // implicit-return-zero rule. 11053 11054 // GCC in C mode accepts qualified 'int'. 11055 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11056 FD->setHasImplicitReturnZero(true); 11057 else { 11058 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11059 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11060 if (RTRange.isValid()) 11061 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11062 << FixItHint::CreateReplacement(RTRange, "int"); 11063 } 11064 } else { 11065 // In C and C++, main magically returns 0 if you fall off the end; 11066 // set the flag which tells us that. 11067 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11068 11069 // All the standards say that main() should return 'int'. 11070 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11071 FD->setHasImplicitReturnZero(true); 11072 else { 11073 // Otherwise, this is just a flat-out error. 11074 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11075 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11076 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11077 : FixItHint()); 11078 FD->setInvalidDecl(true); 11079 } 11080 } 11081 11082 // Treat protoless main() as nullary. 11083 if (isa<FunctionNoProtoType>(FT)) return; 11084 11085 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11086 unsigned nparams = FTP->getNumParams(); 11087 assert(FD->getNumParams() == nparams); 11088 11089 bool HasExtraParameters = (nparams > 3); 11090 11091 if (FTP->isVariadic()) { 11092 Diag(FD->getLocation(), diag::ext_variadic_main); 11093 // FIXME: if we had information about the location of the ellipsis, we 11094 // could add a FixIt hint to remove it as a parameter. 11095 } 11096 11097 // Darwin passes an undocumented fourth argument of type char**. If 11098 // other platforms start sprouting these, the logic below will start 11099 // getting shifty. 11100 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11101 HasExtraParameters = false; 11102 11103 if (HasExtraParameters) { 11104 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11105 FD->setInvalidDecl(true); 11106 nparams = 3; 11107 } 11108 11109 // FIXME: a lot of the following diagnostics would be improved 11110 // if we had some location information about types. 11111 11112 QualType CharPP = 11113 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11114 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11115 11116 for (unsigned i = 0; i < nparams; ++i) { 11117 QualType AT = FTP->getParamType(i); 11118 11119 bool mismatch = true; 11120 11121 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11122 mismatch = false; 11123 else if (Expected[i] == CharPP) { 11124 // As an extension, the following forms are okay: 11125 // char const ** 11126 // char const * const * 11127 // char * const * 11128 11129 QualifierCollector qs; 11130 const PointerType* PT; 11131 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11132 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11133 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11134 Context.CharTy)) { 11135 qs.removeConst(); 11136 mismatch = !qs.empty(); 11137 } 11138 } 11139 11140 if (mismatch) { 11141 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11142 // TODO: suggest replacing given type with expected type 11143 FD->setInvalidDecl(true); 11144 } 11145 } 11146 11147 if (nparams == 1 && !FD->isInvalidDecl()) { 11148 Diag(FD->getLocation(), diag::warn_main_one_arg); 11149 } 11150 11151 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11152 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11153 FD->setInvalidDecl(); 11154 } 11155 } 11156 11157 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11158 QualType T = FD->getType(); 11159 assert(T->isFunctionType() && "function decl is not of function type"); 11160 const FunctionType *FT = T->castAs<FunctionType>(); 11161 11162 // Set an implicit return of 'zero' if the function can return some integral, 11163 // enumeration, pointer or nullptr type. 11164 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11165 FT->getReturnType()->isAnyPointerType() || 11166 FT->getReturnType()->isNullPtrType()) 11167 // DllMain is exempt because a return value of zero means it failed. 11168 if (FD->getName() != "DllMain") 11169 FD->setHasImplicitReturnZero(true); 11170 11171 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11172 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11173 FD->setInvalidDecl(); 11174 } 11175 } 11176 11177 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11178 // FIXME: Need strict checking. In C89, we need to check for 11179 // any assignment, increment, decrement, function-calls, or 11180 // commas outside of a sizeof. In C99, it's the same list, 11181 // except that the aforementioned are allowed in unevaluated 11182 // expressions. Everything else falls under the 11183 // "may accept other forms of constant expressions" exception. 11184 // 11185 // Regular C++ code will not end up here (exceptions: language extensions, 11186 // OpenCL C++ etc), so the constant expression rules there don't matter. 11187 if (Init->isValueDependent()) { 11188 assert(Init->containsErrors() && 11189 "Dependent code should only occur in error-recovery path."); 11190 return true; 11191 } 11192 const Expr *Culprit; 11193 if (Init->isConstantInitializer(Context, false, &Culprit)) 11194 return false; 11195 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11196 << Culprit->getSourceRange(); 11197 return true; 11198 } 11199 11200 namespace { 11201 // Visits an initialization expression to see if OrigDecl is evaluated in 11202 // its own initialization and throws a warning if it does. 11203 class SelfReferenceChecker 11204 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11205 Sema &S; 11206 Decl *OrigDecl; 11207 bool isRecordType; 11208 bool isPODType; 11209 bool isReferenceType; 11210 11211 bool isInitList; 11212 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11213 11214 public: 11215 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11216 11217 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11218 S(S), OrigDecl(OrigDecl) { 11219 isPODType = false; 11220 isRecordType = false; 11221 isReferenceType = false; 11222 isInitList = false; 11223 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11224 isPODType = VD->getType().isPODType(S.Context); 11225 isRecordType = VD->getType()->isRecordType(); 11226 isReferenceType = VD->getType()->isReferenceType(); 11227 } 11228 } 11229 11230 // For most expressions, just call the visitor. For initializer lists, 11231 // track the index of the field being initialized since fields are 11232 // initialized in order allowing use of previously initialized fields. 11233 void CheckExpr(Expr *E) { 11234 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11235 if (!InitList) { 11236 Visit(E); 11237 return; 11238 } 11239 11240 // Track and increment the index here. 11241 isInitList = true; 11242 InitFieldIndex.push_back(0); 11243 for (auto Child : InitList->children()) { 11244 CheckExpr(cast<Expr>(Child)); 11245 ++InitFieldIndex.back(); 11246 } 11247 InitFieldIndex.pop_back(); 11248 } 11249 11250 // Returns true if MemberExpr is checked and no further checking is needed. 11251 // Returns false if additional checking is required. 11252 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11253 llvm::SmallVector<FieldDecl*, 4> Fields; 11254 Expr *Base = E; 11255 bool ReferenceField = false; 11256 11257 // Get the field members used. 11258 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11259 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11260 if (!FD) 11261 return false; 11262 Fields.push_back(FD); 11263 if (FD->getType()->isReferenceType()) 11264 ReferenceField = true; 11265 Base = ME->getBase()->IgnoreParenImpCasts(); 11266 } 11267 11268 // Keep checking only if the base Decl is the same. 11269 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11270 if (!DRE || DRE->getDecl() != OrigDecl) 11271 return false; 11272 11273 // A reference field can be bound to an unininitialized field. 11274 if (CheckReference && !ReferenceField) 11275 return true; 11276 11277 // Convert FieldDecls to their index number. 11278 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11279 for (const FieldDecl *I : llvm::reverse(Fields)) 11280 UsedFieldIndex.push_back(I->getFieldIndex()); 11281 11282 // See if a warning is needed by checking the first difference in index 11283 // numbers. If field being used has index less than the field being 11284 // initialized, then the use is safe. 11285 for (auto UsedIter = UsedFieldIndex.begin(), 11286 UsedEnd = UsedFieldIndex.end(), 11287 OrigIter = InitFieldIndex.begin(), 11288 OrigEnd = InitFieldIndex.end(); 11289 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11290 if (*UsedIter < *OrigIter) 11291 return true; 11292 if (*UsedIter > *OrigIter) 11293 break; 11294 } 11295 11296 // TODO: Add a different warning which will print the field names. 11297 HandleDeclRefExpr(DRE); 11298 return true; 11299 } 11300 11301 // For most expressions, the cast is directly above the DeclRefExpr. 11302 // For conditional operators, the cast can be outside the conditional 11303 // operator if both expressions are DeclRefExpr's. 11304 void HandleValue(Expr *E) { 11305 E = E->IgnoreParens(); 11306 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11307 HandleDeclRefExpr(DRE); 11308 return; 11309 } 11310 11311 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11312 Visit(CO->getCond()); 11313 HandleValue(CO->getTrueExpr()); 11314 HandleValue(CO->getFalseExpr()); 11315 return; 11316 } 11317 11318 if (BinaryConditionalOperator *BCO = 11319 dyn_cast<BinaryConditionalOperator>(E)) { 11320 Visit(BCO->getCond()); 11321 HandleValue(BCO->getFalseExpr()); 11322 return; 11323 } 11324 11325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11326 HandleValue(OVE->getSourceExpr()); 11327 return; 11328 } 11329 11330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11331 if (BO->getOpcode() == BO_Comma) { 11332 Visit(BO->getLHS()); 11333 HandleValue(BO->getRHS()); 11334 return; 11335 } 11336 } 11337 11338 if (isa<MemberExpr>(E)) { 11339 if (isInitList) { 11340 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11341 false /*CheckReference*/)) 11342 return; 11343 } 11344 11345 Expr *Base = E->IgnoreParenImpCasts(); 11346 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11347 // Check for static member variables and don't warn on them. 11348 if (!isa<FieldDecl>(ME->getMemberDecl())) 11349 return; 11350 Base = ME->getBase()->IgnoreParenImpCasts(); 11351 } 11352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11353 HandleDeclRefExpr(DRE); 11354 return; 11355 } 11356 11357 Visit(E); 11358 } 11359 11360 // Reference types not handled in HandleValue are handled here since all 11361 // uses of references are bad, not just r-value uses. 11362 void VisitDeclRefExpr(DeclRefExpr *E) { 11363 if (isReferenceType) 11364 HandleDeclRefExpr(E); 11365 } 11366 11367 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11368 if (E->getCastKind() == CK_LValueToRValue) { 11369 HandleValue(E->getSubExpr()); 11370 return; 11371 } 11372 11373 Inherited::VisitImplicitCastExpr(E); 11374 } 11375 11376 void VisitMemberExpr(MemberExpr *E) { 11377 if (isInitList) { 11378 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11379 return; 11380 } 11381 11382 // Don't warn on arrays since they can be treated as pointers. 11383 if (E->getType()->canDecayToPointerType()) return; 11384 11385 // Warn when a non-static method call is followed by non-static member 11386 // field accesses, which is followed by a DeclRefExpr. 11387 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11388 bool Warn = (MD && !MD->isStatic()); 11389 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11390 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11391 if (!isa<FieldDecl>(ME->getMemberDecl())) 11392 Warn = false; 11393 Base = ME->getBase()->IgnoreParenImpCasts(); 11394 } 11395 11396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11397 if (Warn) 11398 HandleDeclRefExpr(DRE); 11399 return; 11400 } 11401 11402 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11403 // Visit that expression. 11404 Visit(Base); 11405 } 11406 11407 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11408 Expr *Callee = E->getCallee(); 11409 11410 if (isa<UnresolvedLookupExpr>(Callee)) 11411 return Inherited::VisitCXXOperatorCallExpr(E); 11412 11413 Visit(Callee); 11414 for (auto Arg: E->arguments()) 11415 HandleValue(Arg->IgnoreParenImpCasts()); 11416 } 11417 11418 void VisitUnaryOperator(UnaryOperator *E) { 11419 // For POD record types, addresses of its own members are well-defined. 11420 if (E->getOpcode() == UO_AddrOf && isRecordType && 11421 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11422 if (!isPODType) 11423 HandleValue(E->getSubExpr()); 11424 return; 11425 } 11426 11427 if (E->isIncrementDecrementOp()) { 11428 HandleValue(E->getSubExpr()); 11429 return; 11430 } 11431 11432 Inherited::VisitUnaryOperator(E); 11433 } 11434 11435 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11436 11437 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11438 if (E->getConstructor()->isCopyConstructor()) { 11439 Expr *ArgExpr = E->getArg(0); 11440 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11441 if (ILE->getNumInits() == 1) 11442 ArgExpr = ILE->getInit(0); 11443 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11444 if (ICE->getCastKind() == CK_NoOp) 11445 ArgExpr = ICE->getSubExpr(); 11446 HandleValue(ArgExpr); 11447 return; 11448 } 11449 Inherited::VisitCXXConstructExpr(E); 11450 } 11451 11452 void VisitCallExpr(CallExpr *E) { 11453 // Treat std::move as a use. 11454 if (E->isCallToStdMove()) { 11455 HandleValue(E->getArg(0)); 11456 return; 11457 } 11458 11459 Inherited::VisitCallExpr(E); 11460 } 11461 11462 void VisitBinaryOperator(BinaryOperator *E) { 11463 if (E->isCompoundAssignmentOp()) { 11464 HandleValue(E->getLHS()); 11465 Visit(E->getRHS()); 11466 return; 11467 } 11468 11469 Inherited::VisitBinaryOperator(E); 11470 } 11471 11472 // A custom visitor for BinaryConditionalOperator is needed because the 11473 // regular visitor would check the condition and true expression separately 11474 // but both point to the same place giving duplicate diagnostics. 11475 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11476 Visit(E->getCond()); 11477 Visit(E->getFalseExpr()); 11478 } 11479 11480 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11481 Decl* ReferenceDecl = DRE->getDecl(); 11482 if (OrigDecl != ReferenceDecl) return; 11483 unsigned diag; 11484 if (isReferenceType) { 11485 diag = diag::warn_uninit_self_reference_in_reference_init; 11486 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11487 diag = diag::warn_static_self_reference_in_init; 11488 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11489 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11490 DRE->getDecl()->getType()->isRecordType()) { 11491 diag = diag::warn_uninit_self_reference_in_init; 11492 } else { 11493 // Local variables will be handled by the CFG analysis. 11494 return; 11495 } 11496 11497 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11498 S.PDiag(diag) 11499 << DRE->getDecl() << OrigDecl->getLocation() 11500 << DRE->getSourceRange()); 11501 } 11502 }; 11503 11504 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11505 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11506 bool DirectInit) { 11507 // Parameters arguments are occassionially constructed with itself, 11508 // for instance, in recursive functions. Skip them. 11509 if (isa<ParmVarDecl>(OrigDecl)) 11510 return; 11511 11512 E = E->IgnoreParens(); 11513 11514 // Skip checking T a = a where T is not a record or reference type. 11515 // Doing so is a way to silence uninitialized warnings. 11516 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11518 if (ICE->getCastKind() == CK_LValueToRValue) 11519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11520 if (DRE->getDecl() == OrigDecl) 11521 return; 11522 11523 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11524 } 11525 } // end anonymous namespace 11526 11527 namespace { 11528 // Simple wrapper to add the name of a variable or (if no variable is 11529 // available) a DeclarationName into a diagnostic. 11530 struct VarDeclOrName { 11531 VarDecl *VDecl; 11532 DeclarationName Name; 11533 11534 friend const Sema::SemaDiagnosticBuilder & 11535 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11536 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11537 } 11538 }; 11539 } // end anonymous namespace 11540 11541 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11542 DeclarationName Name, QualType Type, 11543 TypeSourceInfo *TSI, 11544 SourceRange Range, bool DirectInit, 11545 Expr *Init) { 11546 bool IsInitCapture = !VDecl; 11547 assert((!VDecl || !VDecl->isInitCapture()) && 11548 "init captures are expected to be deduced prior to initialization"); 11549 11550 VarDeclOrName VN{VDecl, Name}; 11551 11552 DeducedType *Deduced = Type->getContainedDeducedType(); 11553 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11554 11555 // C++11 [dcl.spec.auto]p3 11556 if (!Init) { 11557 assert(VDecl && "no init for init capture deduction?"); 11558 11559 // Except for class argument deduction, and then for an initializing 11560 // declaration only, i.e. no static at class scope or extern. 11561 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11562 VDecl->hasExternalStorage() || 11563 VDecl->isStaticDataMember()) { 11564 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11565 << VDecl->getDeclName() << Type; 11566 return QualType(); 11567 } 11568 } 11569 11570 ArrayRef<Expr*> DeduceInits; 11571 if (Init) 11572 DeduceInits = Init; 11573 11574 if (DirectInit) { 11575 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11576 DeduceInits = PL->exprs(); 11577 } 11578 11579 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11580 assert(VDecl && "non-auto type for init capture deduction?"); 11581 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11582 InitializationKind Kind = InitializationKind::CreateForInit( 11583 VDecl->getLocation(), DirectInit, Init); 11584 // FIXME: Initialization should not be taking a mutable list of inits. 11585 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11586 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11587 InitsCopy); 11588 } 11589 11590 if (DirectInit) { 11591 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11592 DeduceInits = IL->inits(); 11593 } 11594 11595 // Deduction only works if we have exactly one source expression. 11596 if (DeduceInits.empty()) { 11597 // It isn't possible to write this directly, but it is possible to 11598 // end up in this situation with "auto x(some_pack...);" 11599 Diag(Init->getBeginLoc(), IsInitCapture 11600 ? diag::err_init_capture_no_expression 11601 : diag::err_auto_var_init_no_expression) 11602 << VN << Type << Range; 11603 return QualType(); 11604 } 11605 11606 if (DeduceInits.size() > 1) { 11607 Diag(DeduceInits[1]->getBeginLoc(), 11608 IsInitCapture ? diag::err_init_capture_multiple_expressions 11609 : diag::err_auto_var_init_multiple_expressions) 11610 << VN << Type << Range; 11611 return QualType(); 11612 } 11613 11614 Expr *DeduceInit = DeduceInits[0]; 11615 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11616 Diag(Init->getBeginLoc(), IsInitCapture 11617 ? diag::err_init_capture_paren_braces 11618 : diag::err_auto_var_init_paren_braces) 11619 << isa<InitListExpr>(Init) << VN << Type << Range; 11620 return QualType(); 11621 } 11622 11623 // Expressions default to 'id' when we're in a debugger. 11624 bool DefaultedAnyToId = false; 11625 if (getLangOpts().DebuggerCastResultToId && 11626 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11627 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11628 if (Result.isInvalid()) { 11629 return QualType(); 11630 } 11631 Init = Result.get(); 11632 DefaultedAnyToId = true; 11633 } 11634 11635 // C++ [dcl.decomp]p1: 11636 // If the assignment-expression [...] has array type A and no ref-qualifier 11637 // is present, e has type cv A 11638 if (VDecl && isa<DecompositionDecl>(VDecl) && 11639 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11640 DeduceInit->getType()->isConstantArrayType()) 11641 return Context.getQualifiedType(DeduceInit->getType(), 11642 Type.getQualifiers()); 11643 11644 QualType DeducedType; 11645 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11646 if (!IsInitCapture) 11647 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11648 else if (isa<InitListExpr>(Init)) 11649 Diag(Range.getBegin(), 11650 diag::err_init_capture_deduction_failure_from_init_list) 11651 << VN 11652 << (DeduceInit->getType().isNull() ? TSI->getType() 11653 : DeduceInit->getType()) 11654 << DeduceInit->getSourceRange(); 11655 else 11656 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11657 << VN << TSI->getType() 11658 << (DeduceInit->getType().isNull() ? TSI->getType() 11659 : DeduceInit->getType()) 11660 << DeduceInit->getSourceRange(); 11661 } 11662 11663 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11664 // 'id' instead of a specific object type prevents most of our usual 11665 // checks. 11666 // We only want to warn outside of template instantiations, though: 11667 // inside a template, the 'id' could have come from a parameter. 11668 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11669 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11670 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11671 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11672 } 11673 11674 return DeducedType; 11675 } 11676 11677 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11678 Expr *Init) { 11679 assert(!Init || !Init->containsErrors()); 11680 QualType DeducedType = deduceVarTypeFromInitializer( 11681 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11682 VDecl->getSourceRange(), DirectInit, Init); 11683 if (DeducedType.isNull()) { 11684 VDecl->setInvalidDecl(); 11685 return true; 11686 } 11687 11688 VDecl->setType(DeducedType); 11689 assert(VDecl->isLinkageValid()); 11690 11691 // In ARC, infer lifetime. 11692 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11693 VDecl->setInvalidDecl(); 11694 11695 if (getLangOpts().OpenCL) 11696 deduceOpenCLAddressSpace(VDecl); 11697 11698 // If this is a redeclaration, check that the type we just deduced matches 11699 // the previously declared type. 11700 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11701 // We never need to merge the type, because we cannot form an incomplete 11702 // array of auto, nor deduce such a type. 11703 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11704 } 11705 11706 // Check the deduced type is valid for a variable declaration. 11707 CheckVariableDeclarationType(VDecl); 11708 return VDecl->isInvalidDecl(); 11709 } 11710 11711 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11712 SourceLocation Loc) { 11713 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11714 Init = EWC->getSubExpr(); 11715 11716 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11717 Init = CE->getSubExpr(); 11718 11719 QualType InitType = Init->getType(); 11720 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11721 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11722 "shouldn't be called if type doesn't have a non-trivial C struct"); 11723 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11724 for (auto I : ILE->inits()) { 11725 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11726 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11727 continue; 11728 SourceLocation SL = I->getExprLoc(); 11729 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11730 } 11731 return; 11732 } 11733 11734 if (isa<ImplicitValueInitExpr>(Init)) { 11735 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11736 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11737 NTCUK_Init); 11738 } else { 11739 // Assume all other explicit initializers involving copying some existing 11740 // object. 11741 // TODO: ignore any explicit initializers where we can guarantee 11742 // copy-elision. 11743 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11744 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11745 } 11746 } 11747 11748 namespace { 11749 11750 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11751 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11752 // in the source code or implicitly by the compiler if it is in a union 11753 // defined in a system header and has non-trivial ObjC ownership 11754 // qualifications. We don't want those fields to participate in determining 11755 // whether the containing union is non-trivial. 11756 return FD->hasAttr<UnavailableAttr>(); 11757 } 11758 11759 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11760 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11761 void> { 11762 using Super = 11763 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11764 void>; 11765 11766 DiagNonTrivalCUnionDefaultInitializeVisitor( 11767 QualType OrigTy, SourceLocation OrigLoc, 11768 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11769 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11770 11771 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11772 const FieldDecl *FD, bool InNonTrivialUnion) { 11773 if (const auto *AT = S.Context.getAsArrayType(QT)) 11774 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11775 InNonTrivialUnion); 11776 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11777 } 11778 11779 void visitARCStrong(QualType QT, const FieldDecl *FD, 11780 bool InNonTrivialUnion) { 11781 if (InNonTrivialUnion) 11782 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11783 << 1 << 0 << QT << FD->getName(); 11784 } 11785 11786 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11787 if (InNonTrivialUnion) 11788 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11789 << 1 << 0 << QT << FD->getName(); 11790 } 11791 11792 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11793 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11794 if (RD->isUnion()) { 11795 if (OrigLoc.isValid()) { 11796 bool IsUnion = false; 11797 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11798 IsUnion = OrigRD->isUnion(); 11799 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11800 << 0 << OrigTy << IsUnion << UseContext; 11801 // Reset OrigLoc so that this diagnostic is emitted only once. 11802 OrigLoc = SourceLocation(); 11803 } 11804 InNonTrivialUnion = true; 11805 } 11806 11807 if (InNonTrivialUnion) 11808 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11809 << 0 << 0 << QT.getUnqualifiedType() << ""; 11810 11811 for (const FieldDecl *FD : RD->fields()) 11812 if (!shouldIgnoreForRecordTriviality(FD)) 11813 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11814 } 11815 11816 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11817 11818 // The non-trivial C union type or the struct/union type that contains a 11819 // non-trivial C union. 11820 QualType OrigTy; 11821 SourceLocation OrigLoc; 11822 Sema::NonTrivialCUnionContext UseContext; 11823 Sema &S; 11824 }; 11825 11826 struct DiagNonTrivalCUnionDestructedTypeVisitor 11827 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11828 using Super = 11829 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11830 11831 DiagNonTrivalCUnionDestructedTypeVisitor( 11832 QualType OrigTy, SourceLocation OrigLoc, 11833 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11834 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11835 11836 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11837 const FieldDecl *FD, bool InNonTrivialUnion) { 11838 if (const auto *AT = S.Context.getAsArrayType(QT)) 11839 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11840 InNonTrivialUnion); 11841 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11842 } 11843 11844 void visitARCStrong(QualType QT, const FieldDecl *FD, 11845 bool InNonTrivialUnion) { 11846 if (InNonTrivialUnion) 11847 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11848 << 1 << 1 << QT << FD->getName(); 11849 } 11850 11851 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11852 if (InNonTrivialUnion) 11853 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11854 << 1 << 1 << QT << FD->getName(); 11855 } 11856 11857 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11858 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11859 if (RD->isUnion()) { 11860 if (OrigLoc.isValid()) { 11861 bool IsUnion = false; 11862 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11863 IsUnion = OrigRD->isUnion(); 11864 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11865 << 1 << OrigTy << IsUnion << UseContext; 11866 // Reset OrigLoc so that this diagnostic is emitted only once. 11867 OrigLoc = SourceLocation(); 11868 } 11869 InNonTrivialUnion = true; 11870 } 11871 11872 if (InNonTrivialUnion) 11873 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11874 << 0 << 1 << QT.getUnqualifiedType() << ""; 11875 11876 for (const FieldDecl *FD : RD->fields()) 11877 if (!shouldIgnoreForRecordTriviality(FD)) 11878 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11879 } 11880 11881 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11882 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11883 bool InNonTrivialUnion) {} 11884 11885 // The non-trivial C union type or the struct/union type that contains a 11886 // non-trivial C union. 11887 QualType OrigTy; 11888 SourceLocation OrigLoc; 11889 Sema::NonTrivialCUnionContext UseContext; 11890 Sema &S; 11891 }; 11892 11893 struct DiagNonTrivalCUnionCopyVisitor 11894 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11895 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11896 11897 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11898 Sema::NonTrivialCUnionContext UseContext, 11899 Sema &S) 11900 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11901 11902 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11903 const FieldDecl *FD, bool InNonTrivialUnion) { 11904 if (const auto *AT = S.Context.getAsArrayType(QT)) 11905 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11906 InNonTrivialUnion); 11907 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11908 } 11909 11910 void visitARCStrong(QualType QT, const FieldDecl *FD, 11911 bool InNonTrivialUnion) { 11912 if (InNonTrivialUnion) 11913 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11914 << 1 << 2 << QT << FD->getName(); 11915 } 11916 11917 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11918 if (InNonTrivialUnion) 11919 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11920 << 1 << 2 << QT << FD->getName(); 11921 } 11922 11923 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11924 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11925 if (RD->isUnion()) { 11926 if (OrigLoc.isValid()) { 11927 bool IsUnion = false; 11928 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11929 IsUnion = OrigRD->isUnion(); 11930 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11931 << 2 << OrigTy << IsUnion << UseContext; 11932 // Reset OrigLoc so that this diagnostic is emitted only once. 11933 OrigLoc = SourceLocation(); 11934 } 11935 InNonTrivialUnion = true; 11936 } 11937 11938 if (InNonTrivialUnion) 11939 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11940 << 0 << 2 << QT.getUnqualifiedType() << ""; 11941 11942 for (const FieldDecl *FD : RD->fields()) 11943 if (!shouldIgnoreForRecordTriviality(FD)) 11944 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11945 } 11946 11947 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11948 const FieldDecl *FD, bool InNonTrivialUnion) {} 11949 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11950 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11951 bool InNonTrivialUnion) {} 11952 11953 // The non-trivial C union type or the struct/union type that contains a 11954 // non-trivial C union. 11955 QualType OrigTy; 11956 SourceLocation OrigLoc; 11957 Sema::NonTrivialCUnionContext UseContext; 11958 Sema &S; 11959 }; 11960 11961 } // namespace 11962 11963 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11964 NonTrivialCUnionContext UseContext, 11965 unsigned NonTrivialKind) { 11966 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11967 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11968 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11969 "shouldn't be called if type doesn't have a non-trivial C union"); 11970 11971 if ((NonTrivialKind & NTCUK_Init) && 11972 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11973 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11974 .visit(QT, nullptr, false); 11975 if ((NonTrivialKind & NTCUK_Destruct) && 11976 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11977 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11978 .visit(QT, nullptr, false); 11979 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11980 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11981 .visit(QT, nullptr, false); 11982 } 11983 11984 /// AddInitializerToDecl - Adds the initializer Init to the 11985 /// declaration dcl. If DirectInit is true, this is C++ direct 11986 /// initialization rather than copy initialization. 11987 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11988 // If there is no declaration, there was an error parsing it. Just ignore 11989 // the initializer. 11990 if (!RealDecl || RealDecl->isInvalidDecl()) { 11991 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11992 return; 11993 } 11994 11995 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11996 // Pure-specifiers are handled in ActOnPureSpecifier. 11997 Diag(Method->getLocation(), diag::err_member_function_initialization) 11998 << Method->getDeclName() << Init->getSourceRange(); 11999 Method->setInvalidDecl(); 12000 return; 12001 } 12002 12003 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12004 if (!VDecl) { 12005 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12006 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12007 RealDecl->setInvalidDecl(); 12008 return; 12009 } 12010 12011 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12012 if (VDecl->getType()->isUndeducedType()) { 12013 // Attempt typo correction early so that the type of the init expression can 12014 // be deduced based on the chosen correction if the original init contains a 12015 // TypoExpr. 12016 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12017 if (!Res.isUsable()) { 12018 // There are unresolved typos in Init, just drop them. 12019 // FIXME: improve the recovery strategy to preserve the Init. 12020 RealDecl->setInvalidDecl(); 12021 return; 12022 } 12023 if (Res.get()->containsErrors()) { 12024 // Invalidate the decl as we don't know the type for recovery-expr yet. 12025 RealDecl->setInvalidDecl(); 12026 VDecl->setInit(Res.get()); 12027 return; 12028 } 12029 Init = Res.get(); 12030 12031 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12032 return; 12033 } 12034 12035 // dllimport cannot be used on variable definitions. 12036 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12037 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12038 VDecl->setInvalidDecl(); 12039 return; 12040 } 12041 12042 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12043 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12044 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12045 VDecl->setInvalidDecl(); 12046 return; 12047 } 12048 12049 if (!VDecl->getType()->isDependentType()) { 12050 // A definition must end up with a complete type, which means it must be 12051 // complete with the restriction that an array type might be completed by 12052 // the initializer; note that later code assumes this restriction. 12053 QualType BaseDeclType = VDecl->getType(); 12054 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12055 BaseDeclType = Array->getElementType(); 12056 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12057 diag::err_typecheck_decl_incomplete_type)) { 12058 RealDecl->setInvalidDecl(); 12059 return; 12060 } 12061 12062 // The variable can not have an abstract class type. 12063 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12064 diag::err_abstract_type_in_decl, 12065 AbstractVariableType)) 12066 VDecl->setInvalidDecl(); 12067 } 12068 12069 // If adding the initializer will turn this declaration into a definition, 12070 // and we already have a definition for this variable, diagnose or otherwise 12071 // handle the situation. 12072 VarDecl *Def; 12073 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12074 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12075 !VDecl->isThisDeclarationADemotedDefinition() && 12076 checkVarDeclRedefinition(Def, VDecl)) 12077 return; 12078 12079 if (getLangOpts().CPlusPlus) { 12080 // C++ [class.static.data]p4 12081 // If a static data member is of const integral or const 12082 // enumeration type, its declaration in the class definition can 12083 // specify a constant-initializer which shall be an integral 12084 // constant expression (5.19). In that case, the member can appear 12085 // in integral constant expressions. The member shall still be 12086 // defined in a namespace scope if it is used in the program and the 12087 // namespace scope definition shall not contain an initializer. 12088 // 12089 // We already performed a redefinition check above, but for static 12090 // data members we also need to check whether there was an in-class 12091 // declaration with an initializer. 12092 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12093 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12094 << VDecl->getDeclName(); 12095 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12096 diag::note_previous_initializer) 12097 << 0; 12098 return; 12099 } 12100 12101 if (VDecl->hasLocalStorage()) 12102 setFunctionHasBranchProtectedScope(); 12103 12104 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12105 VDecl->setInvalidDecl(); 12106 return; 12107 } 12108 } 12109 12110 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12111 // a kernel function cannot be initialized." 12112 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12113 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12114 VDecl->setInvalidDecl(); 12115 return; 12116 } 12117 12118 // The LoaderUninitialized attribute acts as a definition (of undef). 12119 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12120 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12121 VDecl->setInvalidDecl(); 12122 return; 12123 } 12124 12125 // Get the decls type and save a reference for later, since 12126 // CheckInitializerTypes may change it. 12127 QualType DclT = VDecl->getType(), SavT = DclT; 12128 12129 // Expressions default to 'id' when we're in a debugger 12130 // and we are assigning it to a variable of Objective-C pointer type. 12131 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12132 Init->getType() == Context.UnknownAnyTy) { 12133 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12134 if (Result.isInvalid()) { 12135 VDecl->setInvalidDecl(); 12136 return; 12137 } 12138 Init = Result.get(); 12139 } 12140 12141 // Perform the initialization. 12142 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12143 if (!VDecl->isInvalidDecl()) { 12144 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12145 InitializationKind Kind = InitializationKind::CreateForInit( 12146 VDecl->getLocation(), DirectInit, Init); 12147 12148 MultiExprArg Args = Init; 12149 if (CXXDirectInit) 12150 Args = MultiExprArg(CXXDirectInit->getExprs(), 12151 CXXDirectInit->getNumExprs()); 12152 12153 // Try to correct any TypoExprs in the initialization arguments. 12154 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12155 ExprResult Res = CorrectDelayedTyposInExpr( 12156 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12157 [this, Entity, Kind](Expr *E) { 12158 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12159 return Init.Failed() ? ExprError() : E; 12160 }); 12161 if (Res.isInvalid()) { 12162 VDecl->setInvalidDecl(); 12163 } else if (Res.get() != Args[Idx]) { 12164 Args[Idx] = Res.get(); 12165 } 12166 } 12167 if (VDecl->isInvalidDecl()) 12168 return; 12169 12170 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12171 /*TopLevelOfInitList=*/false, 12172 /*TreatUnavailableAsInvalid=*/false); 12173 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12174 if (Result.isInvalid()) { 12175 // If the provied initializer fails to initialize the var decl, 12176 // we attach a recovery expr for better recovery. 12177 auto RecoveryExpr = 12178 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12179 if (RecoveryExpr.get()) 12180 VDecl->setInit(RecoveryExpr.get()); 12181 return; 12182 } 12183 12184 Init = Result.getAs<Expr>(); 12185 } 12186 12187 // Check for self-references within variable initializers. 12188 // Variables declared within a function/method body (except for references) 12189 // are handled by a dataflow analysis. 12190 // This is undefined behavior in C++, but valid in C. 12191 if (getLangOpts().CPlusPlus) { 12192 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12193 VDecl->getType()->isReferenceType()) { 12194 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12195 } 12196 } 12197 12198 // If the type changed, it means we had an incomplete type that was 12199 // completed by the initializer. For example: 12200 // int ary[] = { 1, 3, 5 }; 12201 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12202 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12203 VDecl->setType(DclT); 12204 12205 if (!VDecl->isInvalidDecl()) { 12206 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12207 12208 if (VDecl->hasAttr<BlocksAttr>()) 12209 checkRetainCycles(VDecl, Init); 12210 12211 // It is safe to assign a weak reference into a strong variable. 12212 // Although this code can still have problems: 12213 // id x = self.weakProp; 12214 // id y = self.weakProp; 12215 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12216 // paths through the function. This should be revisited if 12217 // -Wrepeated-use-of-weak is made flow-sensitive. 12218 if (FunctionScopeInfo *FSI = getCurFunction()) 12219 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12220 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12221 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12222 Init->getBeginLoc())) 12223 FSI->markSafeWeakUse(Init); 12224 } 12225 12226 // The initialization is usually a full-expression. 12227 // 12228 // FIXME: If this is a braced initialization of an aggregate, it is not 12229 // an expression, and each individual field initializer is a separate 12230 // full-expression. For instance, in: 12231 // 12232 // struct Temp { ~Temp(); }; 12233 // struct S { S(Temp); }; 12234 // struct T { S a, b; } t = { Temp(), Temp() } 12235 // 12236 // we should destroy the first Temp before constructing the second. 12237 ExprResult Result = 12238 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12239 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12240 if (Result.isInvalid()) { 12241 VDecl->setInvalidDecl(); 12242 return; 12243 } 12244 Init = Result.get(); 12245 12246 // Attach the initializer to the decl. 12247 VDecl->setInit(Init); 12248 12249 if (VDecl->isLocalVarDecl()) { 12250 // Don't check the initializer if the declaration is malformed. 12251 if (VDecl->isInvalidDecl()) { 12252 // do nothing 12253 12254 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12255 // This is true even in C++ for OpenCL. 12256 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12257 CheckForConstantInitializer(Init, DclT); 12258 12259 // Otherwise, C++ does not restrict the initializer. 12260 } else if (getLangOpts().CPlusPlus) { 12261 // do nothing 12262 12263 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12264 // static storage duration shall be constant expressions or string literals. 12265 } else if (VDecl->getStorageClass() == SC_Static) { 12266 CheckForConstantInitializer(Init, DclT); 12267 12268 // C89 is stricter than C99 for aggregate initializers. 12269 // C89 6.5.7p3: All the expressions [...] in an initializer list 12270 // for an object that has aggregate or union type shall be 12271 // constant expressions. 12272 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12273 isa<InitListExpr>(Init)) { 12274 const Expr *Culprit; 12275 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12276 Diag(Culprit->getExprLoc(), 12277 diag::ext_aggregate_init_not_constant) 12278 << Culprit->getSourceRange(); 12279 } 12280 } 12281 12282 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12283 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12284 if (VDecl->hasLocalStorage()) 12285 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12286 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12287 VDecl->getLexicalDeclContext()->isRecord()) { 12288 // This is an in-class initialization for a static data member, e.g., 12289 // 12290 // struct S { 12291 // static const int value = 17; 12292 // }; 12293 12294 // C++ [class.mem]p4: 12295 // A member-declarator can contain a constant-initializer only 12296 // if it declares a static member (9.4) of const integral or 12297 // const enumeration type, see 9.4.2. 12298 // 12299 // C++11 [class.static.data]p3: 12300 // If a non-volatile non-inline const static data member is of integral 12301 // or enumeration type, its declaration in the class definition can 12302 // specify a brace-or-equal-initializer in which every initializer-clause 12303 // that is an assignment-expression is a constant expression. A static 12304 // data member of literal type can be declared in the class definition 12305 // with the constexpr specifier; if so, its declaration shall specify a 12306 // brace-or-equal-initializer in which every initializer-clause that is 12307 // an assignment-expression is a constant expression. 12308 12309 // Do nothing on dependent types. 12310 if (DclT->isDependentType()) { 12311 12312 // Allow any 'static constexpr' members, whether or not they are of literal 12313 // type. We separately check that every constexpr variable is of literal 12314 // type. 12315 } else if (VDecl->isConstexpr()) { 12316 12317 // Require constness. 12318 } else if (!DclT.isConstQualified()) { 12319 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12320 << Init->getSourceRange(); 12321 VDecl->setInvalidDecl(); 12322 12323 // We allow integer constant expressions in all cases. 12324 } else if (DclT->isIntegralOrEnumerationType()) { 12325 // Check whether the expression is a constant expression. 12326 SourceLocation Loc; 12327 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12328 // In C++11, a non-constexpr const static data member with an 12329 // in-class initializer cannot be volatile. 12330 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12331 else if (Init->isValueDependent()) 12332 ; // Nothing to check. 12333 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12334 ; // Ok, it's an ICE! 12335 else if (Init->getType()->isScopedEnumeralType() && 12336 Init->isCXX11ConstantExpr(Context)) 12337 ; // Ok, it is a scoped-enum constant expression. 12338 else if (Init->isEvaluatable(Context)) { 12339 // If we can constant fold the initializer through heroics, accept it, 12340 // but report this as a use of an extension for -pedantic. 12341 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12342 << Init->getSourceRange(); 12343 } else { 12344 // Otherwise, this is some crazy unknown case. Report the issue at the 12345 // location provided by the isIntegerConstantExpr failed check. 12346 Diag(Loc, diag::err_in_class_initializer_non_constant) 12347 << Init->getSourceRange(); 12348 VDecl->setInvalidDecl(); 12349 } 12350 12351 // We allow foldable floating-point constants as an extension. 12352 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12353 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12354 // it anyway and provide a fixit to add the 'constexpr'. 12355 if (getLangOpts().CPlusPlus11) { 12356 Diag(VDecl->getLocation(), 12357 diag::ext_in_class_initializer_float_type_cxx11) 12358 << DclT << Init->getSourceRange(); 12359 Diag(VDecl->getBeginLoc(), 12360 diag::note_in_class_initializer_float_type_cxx11) 12361 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12362 } else { 12363 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12364 << DclT << Init->getSourceRange(); 12365 12366 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12367 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12368 << Init->getSourceRange(); 12369 VDecl->setInvalidDecl(); 12370 } 12371 } 12372 12373 // Suggest adding 'constexpr' in C++11 for literal types. 12374 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12375 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12376 << DclT << Init->getSourceRange() 12377 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12378 VDecl->setConstexpr(true); 12379 12380 } else { 12381 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12382 << DclT << Init->getSourceRange(); 12383 VDecl->setInvalidDecl(); 12384 } 12385 } else if (VDecl->isFileVarDecl()) { 12386 // In C, extern is typically used to avoid tentative definitions when 12387 // declaring variables in headers, but adding an intializer makes it a 12388 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12389 // In C++, extern is often used to give implictly static const variables 12390 // external linkage, so don't warn in that case. If selectany is present, 12391 // this might be header code intended for C and C++ inclusion, so apply the 12392 // C++ rules. 12393 if (VDecl->getStorageClass() == SC_Extern && 12394 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12395 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12396 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12397 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12398 Diag(VDecl->getLocation(), diag::warn_extern_init); 12399 12400 // In Microsoft C++ mode, a const variable defined in namespace scope has 12401 // external linkage by default if the variable is declared with 12402 // __declspec(dllexport). 12403 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12404 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12405 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12406 VDecl->setStorageClass(SC_Extern); 12407 12408 // C99 6.7.8p4. All file scoped initializers need to be constant. 12409 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12410 CheckForConstantInitializer(Init, DclT); 12411 } 12412 12413 QualType InitType = Init->getType(); 12414 if (!InitType.isNull() && 12415 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12416 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12417 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12418 12419 // We will represent direct-initialization similarly to copy-initialization: 12420 // int x(1); -as-> int x = 1; 12421 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12422 // 12423 // Clients that want to distinguish between the two forms, can check for 12424 // direct initializer using VarDecl::getInitStyle(). 12425 // A major benefit is that clients that don't particularly care about which 12426 // exactly form was it (like the CodeGen) can handle both cases without 12427 // special case code. 12428 12429 // C++ 8.5p11: 12430 // The form of initialization (using parentheses or '=') is generally 12431 // insignificant, but does matter when the entity being initialized has a 12432 // class type. 12433 if (CXXDirectInit) { 12434 assert(DirectInit && "Call-style initializer must be direct init."); 12435 VDecl->setInitStyle(VarDecl::CallInit); 12436 } else if (DirectInit) { 12437 // This must be list-initialization. No other way is direct-initialization. 12438 VDecl->setInitStyle(VarDecl::ListInit); 12439 } 12440 12441 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12442 DeclsToCheckForDeferredDiags.push_back(VDecl); 12443 CheckCompleteVariableDeclaration(VDecl); 12444 } 12445 12446 /// ActOnInitializerError - Given that there was an error parsing an 12447 /// initializer for the given declaration, try to return to some form 12448 /// of sanity. 12449 void Sema::ActOnInitializerError(Decl *D) { 12450 // Our main concern here is re-establishing invariants like "a 12451 // variable's type is either dependent or complete". 12452 if (!D || D->isInvalidDecl()) return; 12453 12454 VarDecl *VD = dyn_cast<VarDecl>(D); 12455 if (!VD) return; 12456 12457 // Bindings are not usable if we can't make sense of the initializer. 12458 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12459 for (auto *BD : DD->bindings()) 12460 BD->setInvalidDecl(); 12461 12462 // Auto types are meaningless if we can't make sense of the initializer. 12463 if (VD->getType()->isUndeducedType()) { 12464 D->setInvalidDecl(); 12465 return; 12466 } 12467 12468 QualType Ty = VD->getType(); 12469 if (Ty->isDependentType()) return; 12470 12471 // Require a complete type. 12472 if (RequireCompleteType(VD->getLocation(), 12473 Context.getBaseElementType(Ty), 12474 diag::err_typecheck_decl_incomplete_type)) { 12475 VD->setInvalidDecl(); 12476 return; 12477 } 12478 12479 // Require a non-abstract type. 12480 if (RequireNonAbstractType(VD->getLocation(), Ty, 12481 diag::err_abstract_type_in_decl, 12482 AbstractVariableType)) { 12483 VD->setInvalidDecl(); 12484 return; 12485 } 12486 12487 // Don't bother complaining about constructors or destructors, 12488 // though. 12489 } 12490 12491 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12492 // If there is no declaration, there was an error parsing it. Just ignore it. 12493 if (!RealDecl) 12494 return; 12495 12496 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12497 QualType Type = Var->getType(); 12498 12499 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12500 if (isa<DecompositionDecl>(RealDecl)) { 12501 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12502 Var->setInvalidDecl(); 12503 return; 12504 } 12505 12506 if (Type->isUndeducedType() && 12507 DeduceVariableDeclarationType(Var, false, nullptr)) 12508 return; 12509 12510 // C++11 [class.static.data]p3: A static data member can be declared with 12511 // the constexpr specifier; if so, its declaration shall specify 12512 // a brace-or-equal-initializer. 12513 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12514 // the definition of a variable [...] or the declaration of a static data 12515 // member. 12516 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12517 !Var->isThisDeclarationADemotedDefinition()) { 12518 if (Var->isStaticDataMember()) { 12519 // C++1z removes the relevant rule; the in-class declaration is always 12520 // a definition there. 12521 if (!getLangOpts().CPlusPlus17 && 12522 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12523 Diag(Var->getLocation(), 12524 diag::err_constexpr_static_mem_var_requires_init) 12525 << Var; 12526 Var->setInvalidDecl(); 12527 return; 12528 } 12529 } else { 12530 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12531 Var->setInvalidDecl(); 12532 return; 12533 } 12534 } 12535 12536 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12537 // be initialized. 12538 if (!Var->isInvalidDecl() && 12539 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12540 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12541 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12542 Var->setInvalidDecl(); 12543 return; 12544 } 12545 12546 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12547 if (Var->getStorageClass() == SC_Extern) { 12548 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12549 << Var; 12550 Var->setInvalidDecl(); 12551 return; 12552 } 12553 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12554 diag::err_typecheck_decl_incomplete_type)) { 12555 Var->setInvalidDecl(); 12556 return; 12557 } 12558 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12559 if (!RD->hasTrivialDefaultConstructor()) { 12560 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12561 Var->setInvalidDecl(); 12562 return; 12563 } 12564 } 12565 } 12566 12567 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12568 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12569 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12570 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12571 NTCUC_DefaultInitializedObject, NTCUK_Init); 12572 12573 12574 switch (DefKind) { 12575 case VarDecl::Definition: 12576 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12577 break; 12578 12579 // We have an out-of-line definition of a static data member 12580 // that has an in-class initializer, so we type-check this like 12581 // a declaration. 12582 // 12583 LLVM_FALLTHROUGH; 12584 12585 case VarDecl::DeclarationOnly: 12586 // It's only a declaration. 12587 12588 // Block scope. C99 6.7p7: If an identifier for an object is 12589 // declared with no linkage (C99 6.2.2p6), the type for the 12590 // object shall be complete. 12591 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12592 !Var->hasLinkage() && !Var->isInvalidDecl() && 12593 RequireCompleteType(Var->getLocation(), Type, 12594 diag::err_typecheck_decl_incomplete_type)) 12595 Var->setInvalidDecl(); 12596 12597 // Make sure that the type is not abstract. 12598 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12599 RequireNonAbstractType(Var->getLocation(), Type, 12600 diag::err_abstract_type_in_decl, 12601 AbstractVariableType)) 12602 Var->setInvalidDecl(); 12603 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12604 Var->getStorageClass() == SC_PrivateExtern) { 12605 Diag(Var->getLocation(), diag::warn_private_extern); 12606 Diag(Var->getLocation(), diag::note_private_extern); 12607 } 12608 12609 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12610 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12611 ExternalDeclarations.push_back(Var); 12612 12613 return; 12614 12615 case VarDecl::TentativeDefinition: 12616 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12617 // object that has file scope without an initializer, and without a 12618 // storage-class specifier or with the storage-class specifier "static", 12619 // constitutes a tentative definition. Note: A tentative definition with 12620 // external linkage is valid (C99 6.2.2p5). 12621 if (!Var->isInvalidDecl()) { 12622 if (const IncompleteArrayType *ArrayT 12623 = Context.getAsIncompleteArrayType(Type)) { 12624 if (RequireCompleteSizedType( 12625 Var->getLocation(), ArrayT->getElementType(), 12626 diag::err_array_incomplete_or_sizeless_type)) 12627 Var->setInvalidDecl(); 12628 } else if (Var->getStorageClass() == SC_Static) { 12629 // C99 6.9.2p3: If the declaration of an identifier for an object is 12630 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12631 // declared type shall not be an incomplete type. 12632 // NOTE: code such as the following 12633 // static struct s; 12634 // struct s { int a; }; 12635 // is accepted by gcc. Hence here we issue a warning instead of 12636 // an error and we do not invalidate the static declaration. 12637 // NOTE: to avoid multiple warnings, only check the first declaration. 12638 if (Var->isFirstDecl()) 12639 RequireCompleteType(Var->getLocation(), Type, 12640 diag::ext_typecheck_decl_incomplete_type); 12641 } 12642 } 12643 12644 // Record the tentative definition; we're done. 12645 if (!Var->isInvalidDecl()) 12646 TentativeDefinitions.push_back(Var); 12647 return; 12648 } 12649 12650 // Provide a specific diagnostic for uninitialized variable 12651 // definitions with incomplete array type. 12652 if (Type->isIncompleteArrayType()) { 12653 Diag(Var->getLocation(), 12654 diag::err_typecheck_incomplete_array_needs_initializer); 12655 Var->setInvalidDecl(); 12656 return; 12657 } 12658 12659 // Provide a specific diagnostic for uninitialized variable 12660 // definitions with reference type. 12661 if (Type->isReferenceType()) { 12662 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12663 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12664 Var->setInvalidDecl(); 12665 return; 12666 } 12667 12668 // Do not attempt to type-check the default initializer for a 12669 // variable with dependent type. 12670 if (Type->isDependentType()) 12671 return; 12672 12673 if (Var->isInvalidDecl()) 12674 return; 12675 12676 if (!Var->hasAttr<AliasAttr>()) { 12677 if (RequireCompleteType(Var->getLocation(), 12678 Context.getBaseElementType(Type), 12679 diag::err_typecheck_decl_incomplete_type)) { 12680 Var->setInvalidDecl(); 12681 return; 12682 } 12683 } else { 12684 return; 12685 } 12686 12687 // The variable can not have an abstract class type. 12688 if (RequireNonAbstractType(Var->getLocation(), Type, 12689 diag::err_abstract_type_in_decl, 12690 AbstractVariableType)) { 12691 Var->setInvalidDecl(); 12692 return; 12693 } 12694 12695 // Check for jumps past the implicit initializer. C++0x 12696 // clarifies that this applies to a "variable with automatic 12697 // storage duration", not a "local variable". 12698 // C++11 [stmt.dcl]p3 12699 // A program that jumps from a point where a variable with automatic 12700 // storage duration is not in scope to a point where it is in scope is 12701 // ill-formed unless the variable has scalar type, class type with a 12702 // trivial default constructor and a trivial destructor, a cv-qualified 12703 // version of one of these types, or an array of one of the preceding 12704 // types and is declared without an initializer. 12705 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12706 if (const RecordType *Record 12707 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12708 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12709 // Mark the function (if we're in one) for further checking even if the 12710 // looser rules of C++11 do not require such checks, so that we can 12711 // diagnose incompatibilities with C++98. 12712 if (!CXXRecord->isPOD()) 12713 setFunctionHasBranchProtectedScope(); 12714 } 12715 } 12716 // In OpenCL, we can't initialize objects in the __local address space, 12717 // even implicitly, so don't synthesize an implicit initializer. 12718 if (getLangOpts().OpenCL && 12719 Var->getType().getAddressSpace() == LangAS::opencl_local) 12720 return; 12721 // C++03 [dcl.init]p9: 12722 // If no initializer is specified for an object, and the 12723 // object is of (possibly cv-qualified) non-POD class type (or 12724 // array thereof), the object shall be default-initialized; if 12725 // the object is of const-qualified type, the underlying class 12726 // type shall have a user-declared default 12727 // constructor. Otherwise, if no initializer is specified for 12728 // a non- static object, the object and its subobjects, if 12729 // any, have an indeterminate initial value); if the object 12730 // or any of its subobjects are of const-qualified type, the 12731 // program is ill-formed. 12732 // C++0x [dcl.init]p11: 12733 // If no initializer is specified for an object, the object is 12734 // default-initialized; [...]. 12735 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12736 InitializationKind Kind 12737 = InitializationKind::CreateDefault(Var->getLocation()); 12738 12739 InitializationSequence InitSeq(*this, Entity, Kind, None); 12740 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12741 12742 if (Init.get()) { 12743 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12744 // This is important for template substitution. 12745 Var->setInitStyle(VarDecl::CallInit); 12746 } else if (Init.isInvalid()) { 12747 // If default-init fails, attach a recovery-expr initializer to track 12748 // that initialization was attempted and failed. 12749 auto RecoveryExpr = 12750 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12751 if (RecoveryExpr.get()) 12752 Var->setInit(RecoveryExpr.get()); 12753 } 12754 12755 CheckCompleteVariableDeclaration(Var); 12756 } 12757 } 12758 12759 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12760 // If there is no declaration, there was an error parsing it. Ignore it. 12761 if (!D) 12762 return; 12763 12764 VarDecl *VD = dyn_cast<VarDecl>(D); 12765 if (!VD) { 12766 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12767 D->setInvalidDecl(); 12768 return; 12769 } 12770 12771 VD->setCXXForRangeDecl(true); 12772 12773 // for-range-declaration cannot be given a storage class specifier. 12774 int Error = -1; 12775 switch (VD->getStorageClass()) { 12776 case SC_None: 12777 break; 12778 case SC_Extern: 12779 Error = 0; 12780 break; 12781 case SC_Static: 12782 Error = 1; 12783 break; 12784 case SC_PrivateExtern: 12785 Error = 2; 12786 break; 12787 case SC_Auto: 12788 Error = 3; 12789 break; 12790 case SC_Register: 12791 Error = 4; 12792 break; 12793 } 12794 12795 // for-range-declaration cannot be given a storage class specifier con't. 12796 switch (VD->getTSCSpec()) { 12797 case TSCS_thread_local: 12798 Error = 6; 12799 break; 12800 case TSCS___thread: 12801 case TSCS__Thread_local: 12802 case TSCS_unspecified: 12803 break; 12804 } 12805 12806 if (Error != -1) { 12807 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12808 << VD << Error; 12809 D->setInvalidDecl(); 12810 } 12811 } 12812 12813 StmtResult 12814 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12815 IdentifierInfo *Ident, 12816 ParsedAttributes &Attrs, 12817 SourceLocation AttrEnd) { 12818 // C++1y [stmt.iter]p1: 12819 // A range-based for statement of the form 12820 // for ( for-range-identifier : for-range-initializer ) statement 12821 // is equivalent to 12822 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12823 DeclSpec DS(Attrs.getPool().getFactory()); 12824 12825 const char *PrevSpec; 12826 unsigned DiagID; 12827 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12828 getPrintingPolicy()); 12829 12830 Declarator D(DS, DeclaratorContext::ForInit); 12831 D.SetIdentifier(Ident, IdentLoc); 12832 D.takeAttributes(Attrs, AttrEnd); 12833 12834 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12835 IdentLoc); 12836 Decl *Var = ActOnDeclarator(S, D); 12837 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12838 FinalizeDeclaration(Var); 12839 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12840 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12841 } 12842 12843 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12844 if (var->isInvalidDecl()) return; 12845 12846 if (getLangOpts().OpenCL) { 12847 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12848 // initialiser 12849 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12850 !var->hasInit()) { 12851 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12852 << 1 /*Init*/; 12853 var->setInvalidDecl(); 12854 return; 12855 } 12856 } 12857 12858 // In Objective-C, don't allow jumps past the implicit initialization of a 12859 // local retaining variable. 12860 if (getLangOpts().ObjC && 12861 var->hasLocalStorage()) { 12862 switch (var->getType().getObjCLifetime()) { 12863 case Qualifiers::OCL_None: 12864 case Qualifiers::OCL_ExplicitNone: 12865 case Qualifiers::OCL_Autoreleasing: 12866 break; 12867 12868 case Qualifiers::OCL_Weak: 12869 case Qualifiers::OCL_Strong: 12870 setFunctionHasBranchProtectedScope(); 12871 break; 12872 } 12873 } 12874 12875 if (var->hasLocalStorage() && 12876 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12877 setFunctionHasBranchProtectedScope(); 12878 12879 // Warn about externally-visible variables being defined without a 12880 // prior declaration. We only want to do this for global 12881 // declarations, but we also specifically need to avoid doing it for 12882 // class members because the linkage of an anonymous class can 12883 // change if it's later given a typedef name. 12884 if (var->isThisDeclarationADefinition() && 12885 var->getDeclContext()->getRedeclContext()->isFileContext() && 12886 var->isExternallyVisible() && var->hasLinkage() && 12887 !var->isInline() && !var->getDescribedVarTemplate() && 12888 !isa<VarTemplatePartialSpecializationDecl>(var) && 12889 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12890 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12891 var->getLocation())) { 12892 // Find a previous declaration that's not a definition. 12893 VarDecl *prev = var->getPreviousDecl(); 12894 while (prev && prev->isThisDeclarationADefinition()) 12895 prev = prev->getPreviousDecl(); 12896 12897 if (!prev) { 12898 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12899 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12900 << /* variable */ 0; 12901 } 12902 } 12903 12904 // Cache the result of checking for constant initialization. 12905 Optional<bool> CacheHasConstInit; 12906 const Expr *CacheCulprit = nullptr; 12907 auto checkConstInit = [&]() mutable { 12908 if (!CacheHasConstInit) 12909 CacheHasConstInit = var->getInit()->isConstantInitializer( 12910 Context, var->getType()->isReferenceType(), &CacheCulprit); 12911 return *CacheHasConstInit; 12912 }; 12913 12914 if (var->getTLSKind() == VarDecl::TLS_Static) { 12915 if (var->getType().isDestructedType()) { 12916 // GNU C++98 edits for __thread, [basic.start.term]p3: 12917 // The type of an object with thread storage duration shall not 12918 // have a non-trivial destructor. 12919 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12920 if (getLangOpts().CPlusPlus11) 12921 Diag(var->getLocation(), diag::note_use_thread_local); 12922 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12923 if (!checkConstInit()) { 12924 // GNU C++98 edits for __thread, [basic.start.init]p4: 12925 // An object of thread storage duration shall not require dynamic 12926 // initialization. 12927 // FIXME: Need strict checking here. 12928 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12929 << CacheCulprit->getSourceRange(); 12930 if (getLangOpts().CPlusPlus11) 12931 Diag(var->getLocation(), diag::note_use_thread_local); 12932 } 12933 } 12934 } 12935 12936 // Apply section attributes and pragmas to global variables. 12937 bool GlobalStorage = var->hasGlobalStorage(); 12938 if (GlobalStorage && var->isThisDeclarationADefinition() && 12939 !inTemplateInstantiation()) { 12940 PragmaStack<StringLiteral *> *Stack = nullptr; 12941 int SectionFlags = ASTContext::PSF_Read; 12942 if (var->getType().isConstQualified()) 12943 Stack = &ConstSegStack; 12944 else if (!var->getInit()) { 12945 Stack = &BSSSegStack; 12946 SectionFlags |= ASTContext::PSF_Write; 12947 } else { 12948 Stack = &DataSegStack; 12949 SectionFlags |= ASTContext::PSF_Write; 12950 } 12951 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12952 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12953 SectionFlags |= ASTContext::PSF_Implicit; 12954 UnifySection(SA->getName(), SectionFlags, var); 12955 } else if (Stack->CurrentValue) { 12956 SectionFlags |= ASTContext::PSF_Implicit; 12957 auto SectionName = Stack->CurrentValue->getString(); 12958 var->addAttr(SectionAttr::CreateImplicit( 12959 Context, SectionName, Stack->CurrentPragmaLocation, 12960 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12961 if (UnifySection(SectionName, SectionFlags, var)) 12962 var->dropAttr<SectionAttr>(); 12963 } 12964 12965 // Apply the init_seg attribute if this has an initializer. If the 12966 // initializer turns out to not be dynamic, we'll end up ignoring this 12967 // attribute. 12968 if (CurInitSeg && var->getInit()) 12969 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12970 CurInitSegLoc, 12971 AttributeCommonInfo::AS_Pragma)); 12972 } 12973 12974 if (!var->getType()->isStructureType() && var->hasInit() && 12975 isa<InitListExpr>(var->getInit())) { 12976 const auto *ILE = cast<InitListExpr>(var->getInit()); 12977 unsigned NumInits = ILE->getNumInits(); 12978 if (NumInits > 2) 12979 for (unsigned I = 0; I < NumInits; ++I) { 12980 const auto *Init = ILE->getInit(I); 12981 if (!Init) 12982 break; 12983 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12984 if (!SL) 12985 break; 12986 12987 unsigned NumConcat = SL->getNumConcatenated(); 12988 // Diagnose missing comma in string array initialization. 12989 // Do not warn when all the elements in the initializer are concatenated 12990 // together. Do not warn for macros too. 12991 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12992 bool OnlyOneMissingComma = true; 12993 for (unsigned J = I + 1; J < NumInits; ++J) { 12994 const auto *Init = ILE->getInit(J); 12995 if (!Init) 12996 break; 12997 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12998 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12999 OnlyOneMissingComma = false; 13000 break; 13001 } 13002 } 13003 13004 if (OnlyOneMissingComma) { 13005 SmallVector<FixItHint, 1> Hints; 13006 for (unsigned i = 0; i < NumConcat - 1; ++i) 13007 Hints.push_back(FixItHint::CreateInsertion( 13008 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13009 13010 Diag(SL->getStrTokenLoc(1), 13011 diag::warn_concatenated_literal_array_init) 13012 << Hints; 13013 Diag(SL->getBeginLoc(), 13014 diag::note_concatenated_string_literal_silence); 13015 } 13016 // In any case, stop now. 13017 break; 13018 } 13019 } 13020 } 13021 13022 // All the following checks are C++ only. 13023 if (!getLangOpts().CPlusPlus) { 13024 // If this variable must be emitted, add it as an initializer for the 13025 // current module. 13026 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13027 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13028 return; 13029 } 13030 13031 QualType type = var->getType(); 13032 13033 if (var->hasAttr<BlocksAttr>()) 13034 getCurFunction()->addByrefBlockVar(var); 13035 13036 Expr *Init = var->getInit(); 13037 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13038 QualType baseType = Context.getBaseElementType(type); 13039 13040 // Check whether the initializer is sufficiently constant. 13041 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13042 (GlobalStorage || var->isConstexpr() || 13043 var->mightBeUsableInConstantExpressions(Context))) { 13044 // If this variable might have a constant initializer or might be usable in 13045 // constant expressions, check whether or not it actually is now. We can't 13046 // do this lazily, because the result might depend on things that change 13047 // later, such as which constexpr functions happen to be defined. 13048 SmallVector<PartialDiagnosticAt, 8> Notes; 13049 bool HasConstInit; 13050 if (!getLangOpts().CPlusPlus11) { 13051 // Prior to C++11, in contexts where a constant initializer is required, 13052 // the set of valid constant initializers is described by syntactic rules 13053 // in [expr.const]p2-6. 13054 // FIXME: Stricter checking for these rules would be useful for constinit / 13055 // -Wglobal-constructors. 13056 HasConstInit = checkConstInit(); 13057 13058 // Compute and cache the constant value, and remember that we have a 13059 // constant initializer. 13060 if (HasConstInit) { 13061 (void)var->checkForConstantInitialization(Notes); 13062 Notes.clear(); 13063 } else if (CacheCulprit) { 13064 Notes.emplace_back(CacheCulprit->getExprLoc(), 13065 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13066 Notes.back().second << CacheCulprit->getSourceRange(); 13067 } 13068 } else { 13069 // Evaluate the initializer to see if it's a constant initializer. 13070 HasConstInit = var->checkForConstantInitialization(Notes); 13071 } 13072 13073 if (HasConstInit) { 13074 // FIXME: Consider replacing the initializer with a ConstantExpr. 13075 } else if (var->isConstexpr()) { 13076 SourceLocation DiagLoc = var->getLocation(); 13077 // If the note doesn't add any useful information other than a source 13078 // location, fold it into the primary diagnostic. 13079 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13080 diag::note_invalid_subexpr_in_const_expr) { 13081 DiagLoc = Notes[0].first; 13082 Notes.clear(); 13083 } 13084 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13085 << var << Init->getSourceRange(); 13086 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13087 Diag(Notes[I].first, Notes[I].second); 13088 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13089 auto *Attr = var->getAttr<ConstInitAttr>(); 13090 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13091 << Init->getSourceRange(); 13092 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13093 << Attr->getRange() << Attr->isConstinit(); 13094 for (auto &it : Notes) 13095 Diag(it.first, it.second); 13096 } else if (IsGlobal && 13097 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13098 var->getLocation())) { 13099 // Warn about globals which don't have a constant initializer. Don't 13100 // warn about globals with a non-trivial destructor because we already 13101 // warned about them. 13102 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13103 if (!(RD && !RD->hasTrivialDestructor())) { 13104 // checkConstInit() here permits trivial default initialization even in 13105 // C++11 onwards, where such an initializer is not a constant initializer 13106 // but nonetheless doesn't require a global constructor. 13107 if (!checkConstInit()) 13108 Diag(var->getLocation(), diag::warn_global_constructor) 13109 << Init->getSourceRange(); 13110 } 13111 } 13112 } 13113 13114 // Require the destructor. 13115 if (!type->isDependentType()) 13116 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13117 FinalizeVarWithDestructor(var, recordType); 13118 13119 // If this variable must be emitted, add it as an initializer for the current 13120 // module. 13121 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13122 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13123 13124 // Build the bindings if this is a structured binding declaration. 13125 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13126 CheckCompleteDecompositionDeclaration(DD); 13127 } 13128 13129 /// Determines if a variable's alignment is dependent. 13130 static bool hasDependentAlignment(VarDecl *VD) { 13131 if (VD->getType()->isDependentType()) 13132 return true; 13133 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13134 if (I->isAlignmentDependent()) 13135 return true; 13136 return false; 13137 } 13138 13139 /// Check if VD needs to be dllexport/dllimport due to being in a 13140 /// dllexport/import function. 13141 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13142 assert(VD->isStaticLocal()); 13143 13144 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13145 13146 // Find outermost function when VD is in lambda function. 13147 while (FD && !getDLLAttr(FD) && 13148 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13149 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13150 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13151 } 13152 13153 if (!FD) 13154 return; 13155 13156 // Static locals inherit dll attributes from their function. 13157 if (Attr *A = getDLLAttr(FD)) { 13158 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13159 NewAttr->setInherited(true); 13160 VD->addAttr(NewAttr); 13161 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13162 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13163 NewAttr->setInherited(true); 13164 VD->addAttr(NewAttr); 13165 13166 // Export this function to enforce exporting this static variable even 13167 // if it is not used in this compilation unit. 13168 if (!FD->hasAttr<DLLExportAttr>()) 13169 FD->addAttr(NewAttr); 13170 13171 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13172 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13173 NewAttr->setInherited(true); 13174 VD->addAttr(NewAttr); 13175 } 13176 } 13177 13178 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13179 /// any semantic actions necessary after any initializer has been attached. 13180 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13181 // Note that we are no longer parsing the initializer for this declaration. 13182 ParsingInitForAutoVars.erase(ThisDecl); 13183 13184 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13185 if (!VD) 13186 return; 13187 13188 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13189 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13190 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13191 if (PragmaClangBSSSection.Valid) 13192 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13193 Context, PragmaClangBSSSection.SectionName, 13194 PragmaClangBSSSection.PragmaLocation, 13195 AttributeCommonInfo::AS_Pragma)); 13196 if (PragmaClangDataSection.Valid) 13197 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13198 Context, PragmaClangDataSection.SectionName, 13199 PragmaClangDataSection.PragmaLocation, 13200 AttributeCommonInfo::AS_Pragma)); 13201 if (PragmaClangRodataSection.Valid) 13202 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13203 Context, PragmaClangRodataSection.SectionName, 13204 PragmaClangRodataSection.PragmaLocation, 13205 AttributeCommonInfo::AS_Pragma)); 13206 if (PragmaClangRelroSection.Valid) 13207 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13208 Context, PragmaClangRelroSection.SectionName, 13209 PragmaClangRelroSection.PragmaLocation, 13210 AttributeCommonInfo::AS_Pragma)); 13211 } 13212 13213 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13214 for (auto *BD : DD->bindings()) { 13215 FinalizeDeclaration(BD); 13216 } 13217 } 13218 13219 checkAttributesAfterMerging(*this, *VD); 13220 13221 // Perform TLS alignment check here after attributes attached to the variable 13222 // which may affect the alignment have been processed. Only perform the check 13223 // if the target has a maximum TLS alignment (zero means no constraints). 13224 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13225 // Protect the check so that it's not performed on dependent types and 13226 // dependent alignments (we can't determine the alignment in that case). 13227 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13228 !VD->isInvalidDecl()) { 13229 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13230 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13231 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13232 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13233 << (unsigned)MaxAlignChars.getQuantity(); 13234 } 13235 } 13236 } 13237 13238 if (VD->isStaticLocal()) 13239 CheckStaticLocalForDllExport(VD); 13240 13241 // Perform check for initializers of device-side global variables. 13242 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13243 // 7.5). We must also apply the same checks to all __shared__ 13244 // variables whether they are local or not. CUDA also allows 13245 // constant initializers for __constant__ and __device__ variables. 13246 if (getLangOpts().CUDA) 13247 checkAllowedCUDAInitializer(VD); 13248 13249 // Grab the dllimport or dllexport attribute off of the VarDecl. 13250 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13251 13252 // Imported static data members cannot be defined out-of-line. 13253 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13254 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13255 VD->isThisDeclarationADefinition()) { 13256 // We allow definitions of dllimport class template static data members 13257 // with a warning. 13258 CXXRecordDecl *Context = 13259 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13260 bool IsClassTemplateMember = 13261 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13262 Context->getDescribedClassTemplate(); 13263 13264 Diag(VD->getLocation(), 13265 IsClassTemplateMember 13266 ? diag::warn_attribute_dllimport_static_field_definition 13267 : diag::err_attribute_dllimport_static_field_definition); 13268 Diag(IA->getLocation(), diag::note_attribute); 13269 if (!IsClassTemplateMember) 13270 VD->setInvalidDecl(); 13271 } 13272 } 13273 13274 // dllimport/dllexport variables cannot be thread local, their TLS index 13275 // isn't exported with the variable. 13276 if (DLLAttr && VD->getTLSKind()) { 13277 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13278 if (F && getDLLAttr(F)) { 13279 assert(VD->isStaticLocal()); 13280 // But if this is a static local in a dlimport/dllexport function, the 13281 // function will never be inlined, which means the var would never be 13282 // imported, so having it marked import/export is safe. 13283 } else { 13284 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13285 << DLLAttr; 13286 VD->setInvalidDecl(); 13287 } 13288 } 13289 13290 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13291 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13292 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13293 VD->dropAttr<UsedAttr>(); 13294 } 13295 } 13296 13297 const DeclContext *DC = VD->getDeclContext(); 13298 // If there's a #pragma GCC visibility in scope, and this isn't a class 13299 // member, set the visibility of this variable. 13300 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13301 AddPushedVisibilityAttribute(VD); 13302 13303 // FIXME: Warn on unused var template partial specializations. 13304 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13305 MarkUnusedFileScopedDecl(VD); 13306 13307 // Now we have parsed the initializer and can update the table of magic 13308 // tag values. 13309 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13310 !VD->getType()->isIntegralOrEnumerationType()) 13311 return; 13312 13313 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13314 const Expr *MagicValueExpr = VD->getInit(); 13315 if (!MagicValueExpr) { 13316 continue; 13317 } 13318 Optional<llvm::APSInt> MagicValueInt; 13319 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13320 Diag(I->getRange().getBegin(), 13321 diag::err_type_tag_for_datatype_not_ice) 13322 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13323 continue; 13324 } 13325 if (MagicValueInt->getActiveBits() > 64) { 13326 Diag(I->getRange().getBegin(), 13327 diag::err_type_tag_for_datatype_too_large) 13328 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13329 continue; 13330 } 13331 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13332 RegisterTypeTagForDatatype(I->getArgumentKind(), 13333 MagicValue, 13334 I->getMatchingCType(), 13335 I->getLayoutCompatible(), 13336 I->getMustBeNull()); 13337 } 13338 } 13339 13340 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13341 auto *VD = dyn_cast<VarDecl>(DD); 13342 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13343 } 13344 13345 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13346 ArrayRef<Decl *> Group) { 13347 SmallVector<Decl*, 8> Decls; 13348 13349 if (DS.isTypeSpecOwned()) 13350 Decls.push_back(DS.getRepAsDecl()); 13351 13352 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13353 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13354 bool DiagnosedMultipleDecomps = false; 13355 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13356 bool DiagnosedNonDeducedAuto = false; 13357 13358 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13359 if (Decl *D = Group[i]) { 13360 // For declarators, there are some additional syntactic-ish checks we need 13361 // to perform. 13362 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13363 if (!FirstDeclaratorInGroup) 13364 FirstDeclaratorInGroup = DD; 13365 if (!FirstDecompDeclaratorInGroup) 13366 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13367 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13368 !hasDeducedAuto(DD)) 13369 FirstNonDeducedAutoInGroup = DD; 13370 13371 if (FirstDeclaratorInGroup != DD) { 13372 // A decomposition declaration cannot be combined with any other 13373 // declaration in the same group. 13374 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13375 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13376 diag::err_decomp_decl_not_alone) 13377 << FirstDeclaratorInGroup->getSourceRange() 13378 << DD->getSourceRange(); 13379 DiagnosedMultipleDecomps = true; 13380 } 13381 13382 // A declarator that uses 'auto' in any way other than to declare a 13383 // variable with a deduced type cannot be combined with any other 13384 // declarator in the same group. 13385 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13386 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13387 diag::err_auto_non_deduced_not_alone) 13388 << FirstNonDeducedAutoInGroup->getType() 13389 ->hasAutoForTrailingReturnType() 13390 << FirstDeclaratorInGroup->getSourceRange() 13391 << DD->getSourceRange(); 13392 DiagnosedNonDeducedAuto = true; 13393 } 13394 } 13395 } 13396 13397 Decls.push_back(D); 13398 } 13399 } 13400 13401 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13402 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13403 handleTagNumbering(Tag, S); 13404 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13405 getLangOpts().CPlusPlus) 13406 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13407 } 13408 } 13409 13410 return BuildDeclaratorGroup(Decls); 13411 } 13412 13413 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13414 /// group, performing any necessary semantic checking. 13415 Sema::DeclGroupPtrTy 13416 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13417 // C++14 [dcl.spec.auto]p7: (DR1347) 13418 // If the type that replaces the placeholder type is not the same in each 13419 // deduction, the program is ill-formed. 13420 if (Group.size() > 1) { 13421 QualType Deduced; 13422 VarDecl *DeducedDecl = nullptr; 13423 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13424 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13425 if (!D || D->isInvalidDecl()) 13426 break; 13427 DeducedType *DT = D->getType()->getContainedDeducedType(); 13428 if (!DT || DT->getDeducedType().isNull()) 13429 continue; 13430 if (Deduced.isNull()) { 13431 Deduced = DT->getDeducedType(); 13432 DeducedDecl = D; 13433 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13434 auto *AT = dyn_cast<AutoType>(DT); 13435 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13436 diag::err_auto_different_deductions) 13437 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13438 << DeducedDecl->getDeclName() << DT->getDeducedType() 13439 << D->getDeclName(); 13440 if (DeducedDecl->hasInit()) 13441 Dia << DeducedDecl->getInit()->getSourceRange(); 13442 if (D->getInit()) 13443 Dia << D->getInit()->getSourceRange(); 13444 D->setInvalidDecl(); 13445 break; 13446 } 13447 } 13448 } 13449 13450 ActOnDocumentableDecls(Group); 13451 13452 return DeclGroupPtrTy::make( 13453 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13454 } 13455 13456 void Sema::ActOnDocumentableDecl(Decl *D) { 13457 ActOnDocumentableDecls(D); 13458 } 13459 13460 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13461 // Don't parse the comment if Doxygen diagnostics are ignored. 13462 if (Group.empty() || !Group[0]) 13463 return; 13464 13465 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13466 Group[0]->getLocation()) && 13467 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13468 Group[0]->getLocation())) 13469 return; 13470 13471 if (Group.size() >= 2) { 13472 // This is a decl group. Normally it will contain only declarations 13473 // produced from declarator list. But in case we have any definitions or 13474 // additional declaration references: 13475 // 'typedef struct S {} S;' 13476 // 'typedef struct S *S;' 13477 // 'struct S *pS;' 13478 // FinalizeDeclaratorGroup adds these as separate declarations. 13479 Decl *MaybeTagDecl = Group[0]; 13480 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13481 Group = Group.slice(1); 13482 } 13483 } 13484 13485 // FIMXE: We assume every Decl in the group is in the same file. 13486 // This is false when preprocessor constructs the group from decls in 13487 // different files (e. g. macros or #include). 13488 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13489 } 13490 13491 /// Common checks for a parameter-declaration that should apply to both function 13492 /// parameters and non-type template parameters. 13493 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13494 // Check that there are no default arguments inside the type of this 13495 // parameter. 13496 if (getLangOpts().CPlusPlus) 13497 CheckExtraCXXDefaultArguments(D); 13498 13499 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13500 if (D.getCXXScopeSpec().isSet()) { 13501 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13502 << D.getCXXScopeSpec().getRange(); 13503 } 13504 13505 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13506 // simple identifier except [...irrelevant cases...]. 13507 switch (D.getName().getKind()) { 13508 case UnqualifiedIdKind::IK_Identifier: 13509 break; 13510 13511 case UnqualifiedIdKind::IK_OperatorFunctionId: 13512 case UnqualifiedIdKind::IK_ConversionFunctionId: 13513 case UnqualifiedIdKind::IK_LiteralOperatorId: 13514 case UnqualifiedIdKind::IK_ConstructorName: 13515 case UnqualifiedIdKind::IK_DestructorName: 13516 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13517 case UnqualifiedIdKind::IK_DeductionGuideName: 13518 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13519 << GetNameForDeclarator(D).getName(); 13520 break; 13521 13522 case UnqualifiedIdKind::IK_TemplateId: 13523 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13524 // GetNameForDeclarator would not produce a useful name in this case. 13525 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13526 break; 13527 } 13528 } 13529 13530 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13531 /// to introduce parameters into function prototype scope. 13532 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13533 const DeclSpec &DS = D.getDeclSpec(); 13534 13535 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13536 13537 // C++03 [dcl.stc]p2 also permits 'auto'. 13538 StorageClass SC = SC_None; 13539 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13540 SC = SC_Register; 13541 // In C++11, the 'register' storage class specifier is deprecated. 13542 // In C++17, it is not allowed, but we tolerate it as an extension. 13543 if (getLangOpts().CPlusPlus11) { 13544 Diag(DS.getStorageClassSpecLoc(), 13545 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13546 : diag::warn_deprecated_register) 13547 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13548 } 13549 } else if (getLangOpts().CPlusPlus && 13550 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13551 SC = SC_Auto; 13552 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13553 Diag(DS.getStorageClassSpecLoc(), 13554 diag::err_invalid_storage_class_in_func_decl); 13555 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13556 } 13557 13558 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13559 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13560 << DeclSpec::getSpecifierName(TSCS); 13561 if (DS.isInlineSpecified()) 13562 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13563 << getLangOpts().CPlusPlus17; 13564 if (DS.hasConstexprSpecifier()) 13565 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13566 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13567 13568 DiagnoseFunctionSpecifiers(DS); 13569 13570 CheckFunctionOrTemplateParamDeclarator(S, D); 13571 13572 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13573 QualType parmDeclType = TInfo->getType(); 13574 13575 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13576 IdentifierInfo *II = D.getIdentifier(); 13577 if (II) { 13578 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13579 ForVisibleRedeclaration); 13580 LookupName(R, S); 13581 if (R.isSingleResult()) { 13582 NamedDecl *PrevDecl = R.getFoundDecl(); 13583 if (PrevDecl->isTemplateParameter()) { 13584 // Maybe we will complain about the shadowed template parameter. 13585 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13586 // Just pretend that we didn't see the previous declaration. 13587 PrevDecl = nullptr; 13588 } else if (S->isDeclScope(PrevDecl)) { 13589 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13590 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13591 13592 // Recover by removing the name 13593 II = nullptr; 13594 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13595 D.setInvalidType(true); 13596 } 13597 } 13598 } 13599 13600 // Temporarily put parameter variables in the translation unit, not 13601 // the enclosing context. This prevents them from accidentally 13602 // looking like class members in C++. 13603 ParmVarDecl *New = 13604 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13605 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13606 13607 if (D.isInvalidType()) 13608 New->setInvalidDecl(); 13609 13610 assert(S->isFunctionPrototypeScope()); 13611 assert(S->getFunctionPrototypeDepth() >= 1); 13612 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13613 S->getNextFunctionPrototypeIndex()); 13614 13615 // Add the parameter declaration into this scope. 13616 S->AddDecl(New); 13617 if (II) 13618 IdResolver.AddDecl(New); 13619 13620 ProcessDeclAttributes(S, New, D); 13621 13622 if (D.getDeclSpec().isModulePrivateSpecified()) 13623 Diag(New->getLocation(), diag::err_module_private_local) 13624 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13625 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13626 13627 if (New->hasAttr<BlocksAttr>()) { 13628 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13629 } 13630 13631 if (getLangOpts().OpenCL) 13632 deduceOpenCLAddressSpace(New); 13633 13634 return New; 13635 } 13636 13637 /// Synthesizes a variable for a parameter arising from a 13638 /// typedef. 13639 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13640 SourceLocation Loc, 13641 QualType T) { 13642 /* FIXME: setting StartLoc == Loc. 13643 Would it be worth to modify callers so as to provide proper source 13644 location for the unnamed parameters, embedding the parameter's type? */ 13645 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13646 T, Context.getTrivialTypeSourceInfo(T, Loc), 13647 SC_None, nullptr); 13648 Param->setImplicit(); 13649 return Param; 13650 } 13651 13652 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13653 // Don't diagnose unused-parameter errors in template instantiations; we 13654 // will already have done so in the template itself. 13655 if (inTemplateInstantiation()) 13656 return; 13657 13658 for (const ParmVarDecl *Parameter : Parameters) { 13659 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13660 !Parameter->hasAttr<UnusedAttr>()) { 13661 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13662 << Parameter->getDeclName(); 13663 } 13664 } 13665 } 13666 13667 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13668 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13669 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13670 return; 13671 13672 // Warn if the return value is pass-by-value and larger than the specified 13673 // threshold. 13674 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13675 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13676 if (Size > LangOpts.NumLargeByValueCopy) 13677 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13678 } 13679 13680 // Warn if any parameter is pass-by-value and larger than the specified 13681 // threshold. 13682 for (const ParmVarDecl *Parameter : Parameters) { 13683 QualType T = Parameter->getType(); 13684 if (T->isDependentType() || !T.isPODType(Context)) 13685 continue; 13686 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13687 if (Size > LangOpts.NumLargeByValueCopy) 13688 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13689 << Parameter << Size; 13690 } 13691 } 13692 13693 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13694 SourceLocation NameLoc, IdentifierInfo *Name, 13695 QualType T, TypeSourceInfo *TSInfo, 13696 StorageClass SC) { 13697 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13698 if (getLangOpts().ObjCAutoRefCount && 13699 T.getObjCLifetime() == Qualifiers::OCL_None && 13700 T->isObjCLifetimeType()) { 13701 13702 Qualifiers::ObjCLifetime lifetime; 13703 13704 // Special cases for arrays: 13705 // - if it's const, use __unsafe_unretained 13706 // - otherwise, it's an error 13707 if (T->isArrayType()) { 13708 if (!T.isConstQualified()) { 13709 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13710 DelayedDiagnostics.add( 13711 sema::DelayedDiagnostic::makeForbiddenType( 13712 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13713 else 13714 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13715 << TSInfo->getTypeLoc().getSourceRange(); 13716 } 13717 lifetime = Qualifiers::OCL_ExplicitNone; 13718 } else { 13719 lifetime = T->getObjCARCImplicitLifetime(); 13720 } 13721 T = Context.getLifetimeQualifiedType(T, lifetime); 13722 } 13723 13724 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13725 Context.getAdjustedParameterType(T), 13726 TSInfo, SC, nullptr); 13727 13728 // Make a note if we created a new pack in the scope of a lambda, so that 13729 // we know that references to that pack must also be expanded within the 13730 // lambda scope. 13731 if (New->isParameterPack()) 13732 if (auto *LSI = getEnclosingLambda()) 13733 LSI->LocalPacks.push_back(New); 13734 13735 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13736 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13737 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13738 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13739 13740 // Parameters can not be abstract class types. 13741 // For record types, this is done by the AbstractClassUsageDiagnoser once 13742 // the class has been completely parsed. 13743 if (!CurContext->isRecord() && 13744 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13745 AbstractParamType)) 13746 New->setInvalidDecl(); 13747 13748 // Parameter declarators cannot be interface types. All ObjC objects are 13749 // passed by reference. 13750 if (T->isObjCObjectType()) { 13751 SourceLocation TypeEndLoc = 13752 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13753 Diag(NameLoc, 13754 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13755 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13756 T = Context.getObjCObjectPointerType(T); 13757 New->setType(T); 13758 } 13759 13760 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13761 // duration shall not be qualified by an address-space qualifier." 13762 // Since all parameters have automatic store duration, they can not have 13763 // an address space. 13764 if (T.getAddressSpace() != LangAS::Default && 13765 // OpenCL allows function arguments declared to be an array of a type 13766 // to be qualified with an address space. 13767 !(getLangOpts().OpenCL && 13768 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13769 Diag(NameLoc, diag::err_arg_with_address_space); 13770 New->setInvalidDecl(); 13771 } 13772 13773 // PPC MMA non-pointer types are not allowed as function argument types. 13774 if (Context.getTargetInfo().getTriple().isPPC64() && 13775 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13776 New->setInvalidDecl(); 13777 } 13778 13779 return New; 13780 } 13781 13782 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13783 SourceLocation LocAfterDecls) { 13784 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13785 13786 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13787 // for a K&R function. 13788 if (!FTI.hasPrototype) { 13789 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13790 --i; 13791 if (FTI.Params[i].Param == nullptr) { 13792 SmallString<256> Code; 13793 llvm::raw_svector_ostream(Code) 13794 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13795 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13796 << FTI.Params[i].Ident 13797 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13798 13799 // Implicitly declare the argument as type 'int' for lack of a better 13800 // type. 13801 AttributeFactory attrs; 13802 DeclSpec DS(attrs); 13803 const char* PrevSpec; // unused 13804 unsigned DiagID; // unused 13805 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13806 DiagID, Context.getPrintingPolicy()); 13807 // Use the identifier location for the type source range. 13808 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13809 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13810 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13811 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13812 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13813 } 13814 } 13815 } 13816 } 13817 13818 Decl * 13819 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13820 MultiTemplateParamsArg TemplateParameterLists, 13821 SkipBodyInfo *SkipBody) { 13822 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13823 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13824 Scope *ParentScope = FnBodyScope->getParent(); 13825 13826 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13827 // we define a non-templated function definition, we will create a declaration 13828 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13829 // The base function declaration will have the equivalent of an `omp declare 13830 // variant` annotation which specifies the mangled definition as a 13831 // specialization function under the OpenMP context defined as part of the 13832 // `omp begin declare variant`. 13833 SmallVector<FunctionDecl *, 4> Bases; 13834 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13835 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13836 ParentScope, D, TemplateParameterLists, Bases); 13837 13838 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13839 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13840 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13841 13842 if (!Bases.empty()) 13843 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13844 13845 return Dcl; 13846 } 13847 13848 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13849 Consumer.HandleInlineFunctionDefinition(D); 13850 } 13851 13852 static bool 13853 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13854 const FunctionDecl *&PossiblePrototype) { 13855 // Don't warn about invalid declarations. 13856 if (FD->isInvalidDecl()) 13857 return false; 13858 13859 // Or declarations that aren't global. 13860 if (!FD->isGlobal()) 13861 return false; 13862 13863 // Don't warn about C++ member functions. 13864 if (isa<CXXMethodDecl>(FD)) 13865 return false; 13866 13867 // Don't warn about 'main'. 13868 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13869 if (IdentifierInfo *II = FD->getIdentifier()) 13870 if (II->isStr("main")) 13871 return false; 13872 13873 // Don't warn about inline functions. 13874 if (FD->isInlined()) 13875 return false; 13876 13877 // Don't warn about function templates. 13878 if (FD->getDescribedFunctionTemplate()) 13879 return false; 13880 13881 // Don't warn about function template specializations. 13882 if (FD->isFunctionTemplateSpecialization()) 13883 return false; 13884 13885 // Don't warn for OpenCL kernels. 13886 if (FD->hasAttr<OpenCLKernelAttr>()) 13887 return false; 13888 13889 // Don't warn on explicitly deleted functions. 13890 if (FD->isDeleted()) 13891 return false; 13892 13893 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13894 Prev; Prev = Prev->getPreviousDecl()) { 13895 // Ignore any declarations that occur in function or method 13896 // scope, because they aren't visible from the header. 13897 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13898 continue; 13899 13900 PossiblePrototype = Prev; 13901 return Prev->getType()->isFunctionNoProtoType(); 13902 } 13903 13904 return true; 13905 } 13906 13907 void 13908 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13909 const FunctionDecl *EffectiveDefinition, 13910 SkipBodyInfo *SkipBody) { 13911 const FunctionDecl *Definition = EffectiveDefinition; 13912 if (!Definition && 13913 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13914 return; 13915 13916 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13917 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13918 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13919 // A merged copy of the same function, instantiated as a member of 13920 // the same class, is OK. 13921 if (declaresSameEntity(OrigFD, OrigDef) && 13922 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13923 cast<Decl>(FD->getLexicalDeclContext()))) 13924 return; 13925 } 13926 } 13927 } 13928 13929 if (canRedefineFunction(Definition, getLangOpts())) 13930 return; 13931 13932 // Don't emit an error when this is redefinition of a typo-corrected 13933 // definition. 13934 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13935 return; 13936 13937 // If we don't have a visible definition of the function, and it's inline or 13938 // a template, skip the new definition. 13939 if (SkipBody && !hasVisibleDefinition(Definition) && 13940 (Definition->getFormalLinkage() == InternalLinkage || 13941 Definition->isInlined() || 13942 Definition->getDescribedFunctionTemplate() || 13943 Definition->getNumTemplateParameterLists())) { 13944 SkipBody->ShouldSkip = true; 13945 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13946 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13947 makeMergedDefinitionVisible(TD); 13948 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13949 return; 13950 } 13951 13952 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13953 Definition->getStorageClass() == SC_Extern) 13954 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13955 << FD << getLangOpts().CPlusPlus; 13956 else 13957 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13958 13959 Diag(Definition->getLocation(), diag::note_previous_definition); 13960 FD->setInvalidDecl(); 13961 } 13962 13963 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13964 Sema &S) { 13965 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13966 13967 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13968 LSI->CallOperator = CallOperator; 13969 LSI->Lambda = LambdaClass; 13970 LSI->ReturnType = CallOperator->getReturnType(); 13971 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13972 13973 if (LCD == LCD_None) 13974 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13975 else if (LCD == LCD_ByCopy) 13976 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13977 else if (LCD == LCD_ByRef) 13978 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13979 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13980 13981 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13982 LSI->Mutable = !CallOperator->isConst(); 13983 13984 // Add the captures to the LSI so they can be noted as already 13985 // captured within tryCaptureVar. 13986 auto I = LambdaClass->field_begin(); 13987 for (const auto &C : LambdaClass->captures()) { 13988 if (C.capturesVariable()) { 13989 VarDecl *VD = C.getCapturedVar(); 13990 if (VD->isInitCapture()) 13991 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13992 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13993 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13994 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13995 /*EllipsisLoc*/C.isPackExpansion() 13996 ? C.getEllipsisLoc() : SourceLocation(), 13997 I->getType(), /*Invalid*/false); 13998 13999 } else if (C.capturesThis()) { 14000 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14001 C.getCaptureKind() == LCK_StarThis); 14002 } else { 14003 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14004 I->getType()); 14005 } 14006 ++I; 14007 } 14008 } 14009 14010 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14011 SkipBodyInfo *SkipBody) { 14012 if (!D) { 14013 // Parsing the function declaration failed in some way. Push on a fake scope 14014 // anyway so we can try to parse the function body. 14015 PushFunctionScope(); 14016 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14017 return D; 14018 } 14019 14020 FunctionDecl *FD = nullptr; 14021 14022 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14023 FD = FunTmpl->getTemplatedDecl(); 14024 else 14025 FD = cast<FunctionDecl>(D); 14026 14027 // Do not push if it is a lambda because one is already pushed when building 14028 // the lambda in ActOnStartOfLambdaDefinition(). 14029 if (!isLambdaCallOperator(FD)) 14030 PushExpressionEvaluationContext( 14031 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14032 : ExprEvalContexts.back().Context); 14033 14034 // Check for defining attributes before the check for redefinition. 14035 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14036 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14037 FD->dropAttr<AliasAttr>(); 14038 FD->setInvalidDecl(); 14039 } 14040 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14041 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14042 FD->dropAttr<IFuncAttr>(); 14043 FD->setInvalidDecl(); 14044 } 14045 14046 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14047 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14048 Ctor->isDefaultConstructor() && 14049 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14050 // If this is an MS ABI dllexport default constructor, instantiate any 14051 // default arguments. 14052 InstantiateDefaultCtorDefaultArgs(Ctor); 14053 } 14054 } 14055 14056 // See if this is a redefinition. If 'will have body' (or similar) is already 14057 // set, then these checks were already performed when it was set. 14058 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14059 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14060 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14061 14062 // If we're skipping the body, we're done. Don't enter the scope. 14063 if (SkipBody && SkipBody->ShouldSkip) 14064 return D; 14065 } 14066 14067 // Mark this function as "will have a body eventually". This lets users to 14068 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14069 // this function. 14070 FD->setWillHaveBody(); 14071 14072 // If we are instantiating a generic lambda call operator, push 14073 // a LambdaScopeInfo onto the function stack. But use the information 14074 // that's already been calculated (ActOnLambdaExpr) to prime the current 14075 // LambdaScopeInfo. 14076 // When the template operator is being specialized, the LambdaScopeInfo, 14077 // has to be properly restored so that tryCaptureVariable doesn't try 14078 // and capture any new variables. In addition when calculating potential 14079 // captures during transformation of nested lambdas, it is necessary to 14080 // have the LSI properly restored. 14081 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14082 assert(inTemplateInstantiation() && 14083 "There should be an active template instantiation on the stack " 14084 "when instantiating a generic lambda!"); 14085 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14086 } else { 14087 // Enter a new function scope 14088 PushFunctionScope(); 14089 } 14090 14091 // Builtin functions cannot be defined. 14092 if (unsigned BuiltinID = FD->getBuiltinID()) { 14093 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14094 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14095 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14096 FD->setInvalidDecl(); 14097 } 14098 } 14099 14100 // The return type of a function definition must be complete 14101 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14102 QualType ResultType = FD->getReturnType(); 14103 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14104 !FD->isInvalidDecl() && 14105 RequireCompleteType(FD->getLocation(), ResultType, 14106 diag::err_func_def_incomplete_result)) 14107 FD->setInvalidDecl(); 14108 14109 if (FnBodyScope) 14110 PushDeclContext(FnBodyScope, FD); 14111 14112 // Check the validity of our function parameters 14113 CheckParmsForFunctionDef(FD->parameters(), 14114 /*CheckParameterNames=*/true); 14115 14116 // Add non-parameter declarations already in the function to the current 14117 // scope. 14118 if (FnBodyScope) { 14119 for (Decl *NPD : FD->decls()) { 14120 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14121 if (!NonParmDecl) 14122 continue; 14123 assert(!isa<ParmVarDecl>(NonParmDecl) && 14124 "parameters should not be in newly created FD yet"); 14125 14126 // If the decl has a name, make it accessible in the current scope. 14127 if (NonParmDecl->getDeclName()) 14128 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14129 14130 // Similarly, dive into enums and fish their constants out, making them 14131 // accessible in this scope. 14132 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14133 for (auto *EI : ED->enumerators()) 14134 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14135 } 14136 } 14137 } 14138 14139 // Introduce our parameters into the function scope 14140 for (auto Param : FD->parameters()) { 14141 Param->setOwningFunction(FD); 14142 14143 // If this has an identifier, add it to the scope stack. 14144 if (Param->getIdentifier() && FnBodyScope) { 14145 CheckShadow(FnBodyScope, Param); 14146 14147 PushOnScopeChains(Param, FnBodyScope); 14148 } 14149 } 14150 14151 // Ensure that the function's exception specification is instantiated. 14152 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14153 ResolveExceptionSpec(D->getLocation(), FPT); 14154 14155 // dllimport cannot be applied to non-inline function definitions. 14156 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14157 !FD->isTemplateInstantiation()) { 14158 assert(!FD->hasAttr<DLLExportAttr>()); 14159 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14160 FD->setInvalidDecl(); 14161 return D; 14162 } 14163 // We want to attach documentation to original Decl (which might be 14164 // a function template). 14165 ActOnDocumentableDecl(D); 14166 if (getCurLexicalContext()->isObjCContainer() && 14167 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14168 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14169 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14170 14171 return D; 14172 } 14173 14174 /// Given the set of return statements within a function body, 14175 /// compute the variables that are subject to the named return value 14176 /// optimization. 14177 /// 14178 /// Each of the variables that is subject to the named return value 14179 /// optimization will be marked as NRVO variables in the AST, and any 14180 /// return statement that has a marked NRVO variable as its NRVO candidate can 14181 /// use the named return value optimization. 14182 /// 14183 /// This function applies a very simplistic algorithm for NRVO: if every return 14184 /// statement in the scope of a variable has the same NRVO candidate, that 14185 /// candidate is an NRVO variable. 14186 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14187 ReturnStmt **Returns = Scope->Returns.data(); 14188 14189 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14190 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14191 if (!NRVOCandidate->isNRVOVariable()) 14192 Returns[I]->setNRVOCandidate(nullptr); 14193 } 14194 } 14195 } 14196 14197 bool Sema::canDelayFunctionBody(const Declarator &D) { 14198 // We can't delay parsing the body of a constexpr function template (yet). 14199 if (D.getDeclSpec().hasConstexprSpecifier()) 14200 return false; 14201 14202 // We can't delay parsing the body of a function template with a deduced 14203 // return type (yet). 14204 if (D.getDeclSpec().hasAutoTypeSpec()) { 14205 // If the placeholder introduces a non-deduced trailing return type, 14206 // we can still delay parsing it. 14207 if (D.getNumTypeObjects()) { 14208 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14209 if (Outer.Kind == DeclaratorChunk::Function && 14210 Outer.Fun.hasTrailingReturnType()) { 14211 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14212 return Ty.isNull() || !Ty->isUndeducedType(); 14213 } 14214 } 14215 return false; 14216 } 14217 14218 return true; 14219 } 14220 14221 bool Sema::canSkipFunctionBody(Decl *D) { 14222 // We cannot skip the body of a function (or function template) which is 14223 // constexpr, since we may need to evaluate its body in order to parse the 14224 // rest of the file. 14225 // We cannot skip the body of a function with an undeduced return type, 14226 // because any callers of that function need to know the type. 14227 if (const FunctionDecl *FD = D->getAsFunction()) { 14228 if (FD->isConstexpr()) 14229 return false; 14230 // We can't simply call Type::isUndeducedType here, because inside template 14231 // auto can be deduced to a dependent type, which is not considered 14232 // "undeduced". 14233 if (FD->getReturnType()->getContainedDeducedType()) 14234 return false; 14235 } 14236 return Consumer.shouldSkipFunctionBody(D); 14237 } 14238 14239 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14240 if (!Decl) 14241 return nullptr; 14242 if (FunctionDecl *FD = Decl->getAsFunction()) 14243 FD->setHasSkippedBody(); 14244 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14245 MD->setHasSkippedBody(); 14246 return Decl; 14247 } 14248 14249 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14250 return ActOnFinishFunctionBody(D, BodyArg, false); 14251 } 14252 14253 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14254 /// body. 14255 class ExitFunctionBodyRAII { 14256 public: 14257 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14258 ~ExitFunctionBodyRAII() { 14259 if (!IsLambda) 14260 S.PopExpressionEvaluationContext(); 14261 } 14262 14263 private: 14264 Sema &S; 14265 bool IsLambda = false; 14266 }; 14267 14268 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14269 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14270 14271 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14272 if (EscapeInfo.count(BD)) 14273 return EscapeInfo[BD]; 14274 14275 bool R = false; 14276 const BlockDecl *CurBD = BD; 14277 14278 do { 14279 R = !CurBD->doesNotEscape(); 14280 if (R) 14281 break; 14282 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14283 } while (CurBD); 14284 14285 return EscapeInfo[BD] = R; 14286 }; 14287 14288 // If the location where 'self' is implicitly retained is inside a escaping 14289 // block, emit a diagnostic. 14290 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14291 S.ImplicitlyRetainedSelfLocs) 14292 if (IsOrNestedInEscapingBlock(P.second)) 14293 S.Diag(P.first, diag::warn_implicitly_retains_self) 14294 << FixItHint::CreateInsertion(P.first, "self->"); 14295 } 14296 14297 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14298 bool IsInstantiation) { 14299 FunctionScopeInfo *FSI = getCurFunction(); 14300 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14301 14302 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14303 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14304 14305 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14306 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14307 14308 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14309 CheckCompletedCoroutineBody(FD, Body); 14310 14311 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14312 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14313 // meant to pop the context added in ActOnStartOfFunctionDef(). 14314 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14315 14316 if (FD) { 14317 FD->setBody(Body); 14318 FD->setWillHaveBody(false); 14319 14320 if (getLangOpts().CPlusPlus14) { 14321 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14322 FD->getReturnType()->isUndeducedType()) { 14323 // If the function has a deduced result type but contains no 'return' 14324 // statements, the result type as written must be exactly 'auto', and 14325 // the deduced result type is 'void'. 14326 if (!FD->getReturnType()->getAs<AutoType>()) { 14327 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14328 << FD->getReturnType(); 14329 FD->setInvalidDecl(); 14330 } else { 14331 // Substitute 'void' for the 'auto' in the type. 14332 TypeLoc ResultType = getReturnTypeLoc(FD); 14333 Context.adjustDeducedFunctionResultType( 14334 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14335 } 14336 } 14337 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14338 // In C++11, we don't use 'auto' deduction rules for lambda call 14339 // operators because we don't support return type deduction. 14340 auto *LSI = getCurLambda(); 14341 if (LSI->HasImplicitReturnType) { 14342 deduceClosureReturnType(*LSI); 14343 14344 // C++11 [expr.prim.lambda]p4: 14345 // [...] if there are no return statements in the compound-statement 14346 // [the deduced type is] the type void 14347 QualType RetType = 14348 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14349 14350 // Update the return type to the deduced type. 14351 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14352 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14353 Proto->getExtProtoInfo())); 14354 } 14355 } 14356 14357 // If the function implicitly returns zero (like 'main') or is naked, 14358 // don't complain about missing return statements. 14359 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14360 WP.disableCheckFallThrough(); 14361 14362 // MSVC permits the use of pure specifier (=0) on function definition, 14363 // defined at class scope, warn about this non-standard construct. 14364 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14365 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14366 14367 if (!FD->isInvalidDecl()) { 14368 // Don't diagnose unused parameters of defaulted or deleted functions. 14369 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14370 DiagnoseUnusedParameters(FD->parameters()); 14371 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14372 FD->getReturnType(), FD); 14373 14374 // If this is a structor, we need a vtable. 14375 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14376 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14377 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14378 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14379 14380 // Try to apply the named return value optimization. We have to check 14381 // if we can do this here because lambdas keep return statements around 14382 // to deduce an implicit return type. 14383 if (FD->getReturnType()->isRecordType() && 14384 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14385 computeNRVO(Body, FSI); 14386 } 14387 14388 // GNU warning -Wmissing-prototypes: 14389 // Warn if a global function is defined without a previous 14390 // prototype declaration. This warning is issued even if the 14391 // definition itself provides a prototype. The aim is to detect 14392 // global functions that fail to be declared in header files. 14393 const FunctionDecl *PossiblePrototype = nullptr; 14394 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14395 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14396 14397 if (PossiblePrototype) { 14398 // We found a declaration that is not a prototype, 14399 // but that could be a zero-parameter prototype 14400 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14401 TypeLoc TL = TI->getTypeLoc(); 14402 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14403 Diag(PossiblePrototype->getLocation(), 14404 diag::note_declaration_not_a_prototype) 14405 << (FD->getNumParams() != 0) 14406 << (FD->getNumParams() == 0 14407 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14408 : FixItHint{}); 14409 } 14410 } else { 14411 // Returns true if the token beginning at this Loc is `const`. 14412 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14413 const LangOptions &LangOpts) { 14414 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14415 if (LocInfo.first.isInvalid()) 14416 return false; 14417 14418 bool Invalid = false; 14419 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14420 if (Invalid) 14421 return false; 14422 14423 if (LocInfo.second > Buffer.size()) 14424 return false; 14425 14426 const char *LexStart = Buffer.data() + LocInfo.second; 14427 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14428 14429 return StartTok.consume_front("const") && 14430 (StartTok.empty() || isWhitespace(StartTok[0]) || 14431 StartTok.startswith("/*") || StartTok.startswith("//")); 14432 }; 14433 14434 auto findBeginLoc = [&]() { 14435 // If the return type has `const` qualifier, we want to insert 14436 // `static` before `const` (and not before the typename). 14437 if ((FD->getReturnType()->isAnyPointerType() && 14438 FD->getReturnType()->getPointeeType().isConstQualified()) || 14439 FD->getReturnType().isConstQualified()) { 14440 // But only do this if we can determine where the `const` is. 14441 14442 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14443 getLangOpts())) 14444 14445 return FD->getBeginLoc(); 14446 } 14447 return FD->getTypeSpecStartLoc(); 14448 }; 14449 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14450 << /* function */ 1 14451 << (FD->getStorageClass() == SC_None 14452 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14453 : FixItHint{}); 14454 } 14455 14456 // GNU warning -Wstrict-prototypes 14457 // Warn if K&R function is defined without a previous declaration. 14458 // This warning is issued only if the definition itself does not provide 14459 // a prototype. Only K&R definitions do not provide a prototype. 14460 if (!FD->hasWrittenPrototype()) { 14461 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14462 TypeLoc TL = TI->getTypeLoc(); 14463 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14464 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14465 } 14466 } 14467 14468 // Warn on CPUDispatch with an actual body. 14469 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14470 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14471 if (!CmpndBody->body_empty()) 14472 Diag(CmpndBody->body_front()->getBeginLoc(), 14473 diag::warn_dispatch_body_ignored); 14474 14475 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14476 const CXXMethodDecl *KeyFunction; 14477 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14478 MD->isVirtual() && 14479 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14480 MD == KeyFunction->getCanonicalDecl()) { 14481 // Update the key-function state if necessary for this ABI. 14482 if (FD->isInlined() && 14483 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14484 Context.setNonKeyFunction(MD); 14485 14486 // If the newly-chosen key function is already defined, then we 14487 // need to mark the vtable as used retroactively. 14488 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14489 const FunctionDecl *Definition; 14490 if (KeyFunction && KeyFunction->isDefined(Definition)) 14491 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14492 } else { 14493 // We just defined they key function; mark the vtable as used. 14494 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14495 } 14496 } 14497 } 14498 14499 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14500 "Function parsing confused"); 14501 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14502 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14503 MD->setBody(Body); 14504 if (!MD->isInvalidDecl()) { 14505 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14506 MD->getReturnType(), MD); 14507 14508 if (Body) 14509 computeNRVO(Body, FSI); 14510 } 14511 if (FSI->ObjCShouldCallSuper) { 14512 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14513 << MD->getSelector().getAsString(); 14514 FSI->ObjCShouldCallSuper = false; 14515 } 14516 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14517 const ObjCMethodDecl *InitMethod = nullptr; 14518 bool isDesignated = 14519 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14520 assert(isDesignated && InitMethod); 14521 (void)isDesignated; 14522 14523 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14524 auto IFace = MD->getClassInterface(); 14525 if (!IFace) 14526 return false; 14527 auto SuperD = IFace->getSuperClass(); 14528 if (!SuperD) 14529 return false; 14530 return SuperD->getIdentifier() == 14531 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14532 }; 14533 // Don't issue this warning for unavailable inits or direct subclasses 14534 // of NSObject. 14535 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14536 Diag(MD->getLocation(), 14537 diag::warn_objc_designated_init_missing_super_call); 14538 Diag(InitMethod->getLocation(), 14539 diag::note_objc_designated_init_marked_here); 14540 } 14541 FSI->ObjCWarnForNoDesignatedInitChain = false; 14542 } 14543 if (FSI->ObjCWarnForNoInitDelegation) { 14544 // Don't issue this warning for unavaialable inits. 14545 if (!MD->isUnavailable()) 14546 Diag(MD->getLocation(), 14547 diag::warn_objc_secondary_init_missing_init_call); 14548 FSI->ObjCWarnForNoInitDelegation = false; 14549 } 14550 14551 diagnoseImplicitlyRetainedSelf(*this); 14552 } else { 14553 // Parsing the function declaration failed in some way. Pop the fake scope 14554 // we pushed on. 14555 PopFunctionScopeInfo(ActivePolicy, dcl); 14556 return nullptr; 14557 } 14558 14559 if (Body && FSI->HasPotentialAvailabilityViolations) 14560 DiagnoseUnguardedAvailabilityViolations(dcl); 14561 14562 assert(!FSI->ObjCShouldCallSuper && 14563 "This should only be set for ObjC methods, which should have been " 14564 "handled in the block above."); 14565 14566 // Verify and clean out per-function state. 14567 if (Body && (!FD || !FD->isDefaulted())) { 14568 // C++ constructors that have function-try-blocks can't have return 14569 // statements in the handlers of that block. (C++ [except.handle]p14) 14570 // Verify this. 14571 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14572 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14573 14574 // Verify that gotos and switch cases don't jump into scopes illegally. 14575 if (FSI->NeedsScopeChecking() && 14576 !PP.isCodeCompletionEnabled()) 14577 DiagnoseInvalidJumps(Body); 14578 14579 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14580 if (!Destructor->getParent()->isDependentType()) 14581 CheckDestructor(Destructor); 14582 14583 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14584 Destructor->getParent()); 14585 } 14586 14587 // If any errors have occurred, clear out any temporaries that may have 14588 // been leftover. This ensures that these temporaries won't be picked up for 14589 // deletion in some later function. 14590 if (hasUncompilableErrorOccurred() || 14591 getDiagnostics().getSuppressAllDiagnostics()) { 14592 DiscardCleanupsInEvaluationContext(); 14593 } 14594 if (!hasUncompilableErrorOccurred() && 14595 !isa<FunctionTemplateDecl>(dcl)) { 14596 // Since the body is valid, issue any analysis-based warnings that are 14597 // enabled. 14598 ActivePolicy = &WP; 14599 } 14600 14601 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14602 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14603 FD->setInvalidDecl(); 14604 14605 if (FD && FD->hasAttr<NakedAttr>()) { 14606 for (const Stmt *S : Body->children()) { 14607 // Allow local register variables without initializer as they don't 14608 // require prologue. 14609 bool RegisterVariables = false; 14610 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14611 for (const auto *Decl : DS->decls()) { 14612 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14613 RegisterVariables = 14614 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14615 if (!RegisterVariables) 14616 break; 14617 } 14618 } 14619 } 14620 if (RegisterVariables) 14621 continue; 14622 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14623 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14624 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14625 FD->setInvalidDecl(); 14626 break; 14627 } 14628 } 14629 } 14630 14631 assert(ExprCleanupObjects.size() == 14632 ExprEvalContexts.back().NumCleanupObjects && 14633 "Leftover temporaries in function"); 14634 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14635 assert(MaybeODRUseExprs.empty() && 14636 "Leftover expressions for odr-use checking"); 14637 } 14638 14639 if (!IsInstantiation) 14640 PopDeclContext(); 14641 14642 PopFunctionScopeInfo(ActivePolicy, dcl); 14643 // If any errors have occurred, clear out any temporaries that may have 14644 // been leftover. This ensures that these temporaries won't be picked up for 14645 // deletion in some later function. 14646 if (hasUncompilableErrorOccurred()) { 14647 DiscardCleanupsInEvaluationContext(); 14648 } 14649 14650 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14651 auto ES = getEmissionStatus(FD); 14652 if (ES == Sema::FunctionEmissionStatus::Emitted || 14653 ES == Sema::FunctionEmissionStatus::Unknown) 14654 DeclsToCheckForDeferredDiags.push_back(FD); 14655 } 14656 14657 return dcl; 14658 } 14659 14660 /// When we finish delayed parsing of an attribute, we must attach it to the 14661 /// relevant Decl. 14662 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14663 ParsedAttributes &Attrs) { 14664 // Always attach attributes to the underlying decl. 14665 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14666 D = TD->getTemplatedDecl(); 14667 ProcessDeclAttributeList(S, D, Attrs); 14668 14669 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14670 if (Method->isStatic()) 14671 checkThisInStaticMemberFunctionAttributes(Method); 14672 } 14673 14674 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14675 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14676 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14677 IdentifierInfo &II, Scope *S) { 14678 // Find the scope in which the identifier is injected and the corresponding 14679 // DeclContext. 14680 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14681 // In that case, we inject the declaration into the translation unit scope 14682 // instead. 14683 Scope *BlockScope = S; 14684 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14685 BlockScope = BlockScope->getParent(); 14686 14687 Scope *ContextScope = BlockScope; 14688 while (!ContextScope->getEntity()) 14689 ContextScope = ContextScope->getParent(); 14690 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14691 14692 // Before we produce a declaration for an implicitly defined 14693 // function, see whether there was a locally-scoped declaration of 14694 // this name as a function or variable. If so, use that 14695 // (non-visible) declaration, and complain about it. 14696 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14697 if (ExternCPrev) { 14698 // We still need to inject the function into the enclosing block scope so 14699 // that later (non-call) uses can see it. 14700 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14701 14702 // C89 footnote 38: 14703 // If in fact it is not defined as having type "function returning int", 14704 // the behavior is undefined. 14705 if (!isa<FunctionDecl>(ExternCPrev) || 14706 !Context.typesAreCompatible( 14707 cast<FunctionDecl>(ExternCPrev)->getType(), 14708 Context.getFunctionNoProtoType(Context.IntTy))) { 14709 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14710 << ExternCPrev << !getLangOpts().C99; 14711 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14712 return ExternCPrev; 14713 } 14714 } 14715 14716 // Extension in C99. Legal in C90, but warn about it. 14717 unsigned diag_id; 14718 if (II.getName().startswith("__builtin_")) 14719 diag_id = diag::warn_builtin_unknown; 14720 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14721 else if (getLangOpts().OpenCL) 14722 diag_id = diag::err_opencl_implicit_function_decl; 14723 else if (getLangOpts().C99) 14724 diag_id = diag::ext_implicit_function_decl; 14725 else 14726 diag_id = diag::warn_implicit_function_decl; 14727 Diag(Loc, diag_id) << &II; 14728 14729 // If we found a prior declaration of this function, don't bother building 14730 // another one. We've already pushed that one into scope, so there's nothing 14731 // more to do. 14732 if (ExternCPrev) 14733 return ExternCPrev; 14734 14735 // Because typo correction is expensive, only do it if the implicit 14736 // function declaration is going to be treated as an error. 14737 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14738 TypoCorrection Corrected; 14739 DeclFilterCCC<FunctionDecl> CCC{}; 14740 if (S && (Corrected = 14741 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14742 S, nullptr, CCC, CTK_NonError))) 14743 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14744 /*ErrorRecovery*/false); 14745 } 14746 14747 // Set a Declarator for the implicit definition: int foo(); 14748 const char *Dummy; 14749 AttributeFactory attrFactory; 14750 DeclSpec DS(attrFactory); 14751 unsigned DiagID; 14752 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14753 Context.getPrintingPolicy()); 14754 (void)Error; // Silence warning. 14755 assert(!Error && "Error setting up implicit decl!"); 14756 SourceLocation NoLoc; 14757 Declarator D(DS, DeclaratorContext::Block); 14758 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14759 /*IsAmbiguous=*/false, 14760 /*LParenLoc=*/NoLoc, 14761 /*Params=*/nullptr, 14762 /*NumParams=*/0, 14763 /*EllipsisLoc=*/NoLoc, 14764 /*RParenLoc=*/NoLoc, 14765 /*RefQualifierIsLvalueRef=*/true, 14766 /*RefQualifierLoc=*/NoLoc, 14767 /*MutableLoc=*/NoLoc, EST_None, 14768 /*ESpecRange=*/SourceRange(), 14769 /*Exceptions=*/nullptr, 14770 /*ExceptionRanges=*/nullptr, 14771 /*NumExceptions=*/0, 14772 /*NoexceptExpr=*/nullptr, 14773 /*ExceptionSpecTokens=*/nullptr, 14774 /*DeclsInPrototype=*/None, Loc, 14775 Loc, D), 14776 std::move(DS.getAttributes()), SourceLocation()); 14777 D.SetIdentifier(&II, Loc); 14778 14779 // Insert this function into the enclosing block scope. 14780 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14781 FD->setImplicit(); 14782 14783 AddKnownFunctionAttributes(FD); 14784 14785 return FD; 14786 } 14787 14788 /// If this function is a C++ replaceable global allocation function 14789 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14790 /// adds any function attributes that we know a priori based on the standard. 14791 /// 14792 /// We need to check for duplicate attributes both here and where user-written 14793 /// attributes are applied to declarations. 14794 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14795 FunctionDecl *FD) { 14796 if (FD->isInvalidDecl()) 14797 return; 14798 14799 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14800 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14801 return; 14802 14803 Optional<unsigned> AlignmentParam; 14804 bool IsNothrow = false; 14805 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14806 return; 14807 14808 // C++2a [basic.stc.dynamic.allocation]p4: 14809 // An allocation function that has a non-throwing exception specification 14810 // indicates failure by returning a null pointer value. Any other allocation 14811 // function never returns a null pointer value and indicates failure only by 14812 // throwing an exception [...] 14813 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14814 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14815 14816 // C++2a [basic.stc.dynamic.allocation]p2: 14817 // An allocation function attempts to allocate the requested amount of 14818 // storage. [...] If the request succeeds, the value returned by a 14819 // replaceable allocation function is a [...] pointer value p0 different 14820 // from any previously returned value p1 [...] 14821 // 14822 // However, this particular information is being added in codegen, 14823 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14824 14825 // C++2a [basic.stc.dynamic.allocation]p2: 14826 // An allocation function attempts to allocate the requested amount of 14827 // storage. If it is successful, it returns the address of the start of a 14828 // block of storage whose length in bytes is at least as large as the 14829 // requested size. 14830 if (!FD->hasAttr<AllocSizeAttr>()) { 14831 FD->addAttr(AllocSizeAttr::CreateImplicit( 14832 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14833 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14834 } 14835 14836 // C++2a [basic.stc.dynamic.allocation]p3: 14837 // For an allocation function [...], the pointer returned on a successful 14838 // call shall represent the address of storage that is aligned as follows: 14839 // (3.1) If the allocation function takes an argument of type 14840 // std::align_val_t, the storage will have the alignment 14841 // specified by the value of this argument. 14842 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14843 FD->addAttr(AllocAlignAttr::CreateImplicit( 14844 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14845 } 14846 14847 // FIXME: 14848 // C++2a [basic.stc.dynamic.allocation]p3: 14849 // For an allocation function [...], the pointer returned on a successful 14850 // call shall represent the address of storage that is aligned as follows: 14851 // (3.2) Otherwise, if the allocation function is named operator new[], 14852 // the storage is aligned for any object that does not have 14853 // new-extended alignment ([basic.align]) and is no larger than the 14854 // requested size. 14855 // (3.3) Otherwise, the storage is aligned for any object that does not 14856 // have new-extended alignment and is of the requested size. 14857 } 14858 14859 /// Adds any function attributes that we know a priori based on 14860 /// the declaration of this function. 14861 /// 14862 /// These attributes can apply both to implicitly-declared builtins 14863 /// (like __builtin___printf_chk) or to library-declared functions 14864 /// like NSLog or printf. 14865 /// 14866 /// We need to check for duplicate attributes both here and where user-written 14867 /// attributes are applied to declarations. 14868 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14869 if (FD->isInvalidDecl()) 14870 return; 14871 14872 // If this is a built-in function, map its builtin attributes to 14873 // actual attributes. 14874 if (unsigned BuiltinID = FD->getBuiltinID()) { 14875 // Handle printf-formatting attributes. 14876 unsigned FormatIdx; 14877 bool HasVAListArg; 14878 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14879 if (!FD->hasAttr<FormatAttr>()) { 14880 const char *fmt = "printf"; 14881 unsigned int NumParams = FD->getNumParams(); 14882 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14883 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14884 fmt = "NSString"; 14885 FD->addAttr(FormatAttr::CreateImplicit(Context, 14886 &Context.Idents.get(fmt), 14887 FormatIdx+1, 14888 HasVAListArg ? 0 : FormatIdx+2, 14889 FD->getLocation())); 14890 } 14891 } 14892 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14893 HasVAListArg)) { 14894 if (!FD->hasAttr<FormatAttr>()) 14895 FD->addAttr(FormatAttr::CreateImplicit(Context, 14896 &Context.Idents.get("scanf"), 14897 FormatIdx+1, 14898 HasVAListArg ? 0 : FormatIdx+2, 14899 FD->getLocation())); 14900 } 14901 14902 // Handle automatically recognized callbacks. 14903 SmallVector<int, 4> Encoding; 14904 if (!FD->hasAttr<CallbackAttr>() && 14905 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14906 FD->addAttr(CallbackAttr::CreateImplicit( 14907 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14908 14909 // Mark const if we don't care about errno and that is the only thing 14910 // preventing the function from being const. This allows IRgen to use LLVM 14911 // intrinsics for such functions. 14912 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14913 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14914 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14915 14916 // We make "fma" on some platforms const because we know it does not set 14917 // errno in those environments even though it could set errno based on the 14918 // C standard. 14919 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14920 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14921 !FD->hasAttr<ConstAttr>()) { 14922 switch (BuiltinID) { 14923 case Builtin::BI__builtin_fma: 14924 case Builtin::BI__builtin_fmaf: 14925 case Builtin::BI__builtin_fmal: 14926 case Builtin::BIfma: 14927 case Builtin::BIfmaf: 14928 case Builtin::BIfmal: 14929 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14930 break; 14931 default: 14932 break; 14933 } 14934 } 14935 14936 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14937 !FD->hasAttr<ReturnsTwiceAttr>()) 14938 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14939 FD->getLocation())); 14940 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14941 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14942 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14943 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14944 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14945 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14946 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14947 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14948 // Add the appropriate attribute, depending on the CUDA compilation mode 14949 // and which target the builtin belongs to. For example, during host 14950 // compilation, aux builtins are __device__, while the rest are __host__. 14951 if (getLangOpts().CUDAIsDevice != 14952 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14953 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14954 else 14955 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14956 } 14957 } 14958 14959 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14960 14961 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14962 // throw, add an implicit nothrow attribute to any extern "C" function we come 14963 // across. 14964 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14965 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14966 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14967 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14968 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14969 } 14970 14971 IdentifierInfo *Name = FD->getIdentifier(); 14972 if (!Name) 14973 return; 14974 if ((!getLangOpts().CPlusPlus && 14975 FD->getDeclContext()->isTranslationUnit()) || 14976 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14977 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14978 LinkageSpecDecl::lang_c)) { 14979 // Okay: this could be a libc/libm/Objective-C function we know 14980 // about. 14981 } else 14982 return; 14983 14984 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14985 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14986 // target-specific builtins, perhaps? 14987 if (!FD->hasAttr<FormatAttr>()) 14988 FD->addAttr(FormatAttr::CreateImplicit(Context, 14989 &Context.Idents.get("printf"), 2, 14990 Name->isStr("vasprintf") ? 0 : 3, 14991 FD->getLocation())); 14992 } 14993 14994 if (Name->isStr("__CFStringMakeConstantString")) { 14995 // We already have a __builtin___CFStringMakeConstantString, 14996 // but builds that use -fno-constant-cfstrings don't go through that. 14997 if (!FD->hasAttr<FormatArgAttr>()) 14998 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14999 FD->getLocation())); 15000 } 15001 } 15002 15003 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15004 TypeSourceInfo *TInfo) { 15005 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15006 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15007 15008 if (!TInfo) { 15009 assert(D.isInvalidType() && "no declarator info for valid type"); 15010 TInfo = Context.getTrivialTypeSourceInfo(T); 15011 } 15012 15013 // Scope manipulation handled by caller. 15014 TypedefDecl *NewTD = 15015 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15016 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15017 15018 // Bail out immediately if we have an invalid declaration. 15019 if (D.isInvalidType()) { 15020 NewTD->setInvalidDecl(); 15021 return NewTD; 15022 } 15023 15024 if (D.getDeclSpec().isModulePrivateSpecified()) { 15025 if (CurContext->isFunctionOrMethod()) 15026 Diag(NewTD->getLocation(), diag::err_module_private_local) 15027 << 2 << NewTD 15028 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15029 << FixItHint::CreateRemoval( 15030 D.getDeclSpec().getModulePrivateSpecLoc()); 15031 else 15032 NewTD->setModulePrivate(); 15033 } 15034 15035 // C++ [dcl.typedef]p8: 15036 // If the typedef declaration defines an unnamed class (or 15037 // enum), the first typedef-name declared by the declaration 15038 // to be that class type (or enum type) is used to denote the 15039 // class type (or enum type) for linkage purposes only. 15040 // We need to check whether the type was declared in the declaration. 15041 switch (D.getDeclSpec().getTypeSpecType()) { 15042 case TST_enum: 15043 case TST_struct: 15044 case TST_interface: 15045 case TST_union: 15046 case TST_class: { 15047 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15048 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15049 break; 15050 } 15051 15052 default: 15053 break; 15054 } 15055 15056 return NewTD; 15057 } 15058 15059 /// Check that this is a valid underlying type for an enum declaration. 15060 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15061 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15062 QualType T = TI->getType(); 15063 15064 if (T->isDependentType()) 15065 return false; 15066 15067 // This doesn't use 'isIntegralType' despite the error message mentioning 15068 // integral type because isIntegralType would also allow enum types in C. 15069 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15070 if (BT->isInteger()) 15071 return false; 15072 15073 if (T->isExtIntType()) 15074 return false; 15075 15076 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15077 } 15078 15079 /// Check whether this is a valid redeclaration of a previous enumeration. 15080 /// \return true if the redeclaration was invalid. 15081 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15082 QualType EnumUnderlyingTy, bool IsFixed, 15083 const EnumDecl *Prev) { 15084 if (IsScoped != Prev->isScoped()) { 15085 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15086 << Prev->isScoped(); 15087 Diag(Prev->getLocation(), diag::note_previous_declaration); 15088 return true; 15089 } 15090 15091 if (IsFixed && Prev->isFixed()) { 15092 if (!EnumUnderlyingTy->isDependentType() && 15093 !Prev->getIntegerType()->isDependentType() && 15094 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15095 Prev->getIntegerType())) { 15096 // TODO: Highlight the underlying type of the redeclaration. 15097 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15098 << EnumUnderlyingTy << Prev->getIntegerType(); 15099 Diag(Prev->getLocation(), diag::note_previous_declaration) 15100 << Prev->getIntegerTypeRange(); 15101 return true; 15102 } 15103 } else if (IsFixed != Prev->isFixed()) { 15104 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15105 << Prev->isFixed(); 15106 Diag(Prev->getLocation(), diag::note_previous_declaration); 15107 return true; 15108 } 15109 15110 return false; 15111 } 15112 15113 /// Get diagnostic %select index for tag kind for 15114 /// redeclaration diagnostic message. 15115 /// WARNING: Indexes apply to particular diagnostics only! 15116 /// 15117 /// \returns diagnostic %select index. 15118 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15119 switch (Tag) { 15120 case TTK_Struct: return 0; 15121 case TTK_Interface: return 1; 15122 case TTK_Class: return 2; 15123 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15124 } 15125 } 15126 15127 /// Determine if tag kind is a class-key compatible with 15128 /// class for redeclaration (class, struct, or __interface). 15129 /// 15130 /// \returns true iff the tag kind is compatible. 15131 static bool isClassCompatTagKind(TagTypeKind Tag) 15132 { 15133 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15134 } 15135 15136 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15137 TagTypeKind TTK) { 15138 if (isa<TypedefDecl>(PrevDecl)) 15139 return NTK_Typedef; 15140 else if (isa<TypeAliasDecl>(PrevDecl)) 15141 return NTK_TypeAlias; 15142 else if (isa<ClassTemplateDecl>(PrevDecl)) 15143 return NTK_Template; 15144 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15145 return NTK_TypeAliasTemplate; 15146 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15147 return NTK_TemplateTemplateArgument; 15148 switch (TTK) { 15149 case TTK_Struct: 15150 case TTK_Interface: 15151 case TTK_Class: 15152 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15153 case TTK_Union: 15154 return NTK_NonUnion; 15155 case TTK_Enum: 15156 return NTK_NonEnum; 15157 } 15158 llvm_unreachable("invalid TTK"); 15159 } 15160 15161 /// Determine whether a tag with a given kind is acceptable 15162 /// as a redeclaration of the given tag declaration. 15163 /// 15164 /// \returns true if the new tag kind is acceptable, false otherwise. 15165 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15166 TagTypeKind NewTag, bool isDefinition, 15167 SourceLocation NewTagLoc, 15168 const IdentifierInfo *Name) { 15169 // C++ [dcl.type.elab]p3: 15170 // The class-key or enum keyword present in the 15171 // elaborated-type-specifier shall agree in kind with the 15172 // declaration to which the name in the elaborated-type-specifier 15173 // refers. This rule also applies to the form of 15174 // elaborated-type-specifier that declares a class-name or 15175 // friend class since it can be construed as referring to the 15176 // definition of the class. Thus, in any 15177 // elaborated-type-specifier, the enum keyword shall be used to 15178 // refer to an enumeration (7.2), the union class-key shall be 15179 // used to refer to a union (clause 9), and either the class or 15180 // struct class-key shall be used to refer to a class (clause 9) 15181 // declared using the class or struct class-key. 15182 TagTypeKind OldTag = Previous->getTagKind(); 15183 if (OldTag != NewTag && 15184 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15185 return false; 15186 15187 // Tags are compatible, but we might still want to warn on mismatched tags. 15188 // Non-class tags can't be mismatched at this point. 15189 if (!isClassCompatTagKind(NewTag)) 15190 return true; 15191 15192 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15193 // by our warning analysis. We don't want to warn about mismatches with (eg) 15194 // declarations in system headers that are designed to be specialized, but if 15195 // a user asks us to warn, we should warn if their code contains mismatched 15196 // declarations. 15197 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15198 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15199 Loc); 15200 }; 15201 if (IsIgnoredLoc(NewTagLoc)) 15202 return true; 15203 15204 auto IsIgnored = [&](const TagDecl *Tag) { 15205 return IsIgnoredLoc(Tag->getLocation()); 15206 }; 15207 while (IsIgnored(Previous)) { 15208 Previous = Previous->getPreviousDecl(); 15209 if (!Previous) 15210 return true; 15211 OldTag = Previous->getTagKind(); 15212 } 15213 15214 bool isTemplate = false; 15215 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15216 isTemplate = Record->getDescribedClassTemplate(); 15217 15218 if (inTemplateInstantiation()) { 15219 if (OldTag != NewTag) { 15220 // In a template instantiation, do not offer fix-its for tag mismatches 15221 // since they usually mess up the template instead of fixing the problem. 15222 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15223 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15224 << getRedeclDiagFromTagKind(OldTag); 15225 // FIXME: Note previous location? 15226 } 15227 return true; 15228 } 15229 15230 if (isDefinition) { 15231 // On definitions, check all previous tags and issue a fix-it for each 15232 // one that doesn't match the current tag. 15233 if (Previous->getDefinition()) { 15234 // Don't suggest fix-its for redefinitions. 15235 return true; 15236 } 15237 15238 bool previousMismatch = false; 15239 for (const TagDecl *I : Previous->redecls()) { 15240 if (I->getTagKind() != NewTag) { 15241 // Ignore previous declarations for which the warning was disabled. 15242 if (IsIgnored(I)) 15243 continue; 15244 15245 if (!previousMismatch) { 15246 previousMismatch = true; 15247 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15248 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15249 << getRedeclDiagFromTagKind(I->getTagKind()); 15250 } 15251 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15252 << getRedeclDiagFromTagKind(NewTag) 15253 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15254 TypeWithKeyword::getTagTypeKindName(NewTag)); 15255 } 15256 } 15257 return true; 15258 } 15259 15260 // Identify the prevailing tag kind: this is the kind of the definition (if 15261 // there is a non-ignored definition), or otherwise the kind of the prior 15262 // (non-ignored) declaration. 15263 const TagDecl *PrevDef = Previous->getDefinition(); 15264 if (PrevDef && IsIgnored(PrevDef)) 15265 PrevDef = nullptr; 15266 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15267 if (Redecl->getTagKind() != NewTag) { 15268 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15269 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15270 << getRedeclDiagFromTagKind(OldTag); 15271 Diag(Redecl->getLocation(), diag::note_previous_use); 15272 15273 // If there is a previous definition, suggest a fix-it. 15274 if (PrevDef) { 15275 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15276 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15277 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15278 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15279 } 15280 } 15281 15282 return true; 15283 } 15284 15285 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15286 /// from an outer enclosing namespace or file scope inside a friend declaration. 15287 /// This should provide the commented out code in the following snippet: 15288 /// namespace N { 15289 /// struct X; 15290 /// namespace M { 15291 /// struct Y { friend struct /*N::*/ X; }; 15292 /// } 15293 /// } 15294 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15295 SourceLocation NameLoc) { 15296 // While the decl is in a namespace, do repeated lookup of that name and see 15297 // if we get the same namespace back. If we do not, continue until 15298 // translation unit scope, at which point we have a fully qualified NNS. 15299 SmallVector<IdentifierInfo *, 4> Namespaces; 15300 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15301 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15302 // This tag should be declared in a namespace, which can only be enclosed by 15303 // other namespaces. Bail if there's an anonymous namespace in the chain. 15304 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15305 if (!Namespace || Namespace->isAnonymousNamespace()) 15306 return FixItHint(); 15307 IdentifierInfo *II = Namespace->getIdentifier(); 15308 Namespaces.push_back(II); 15309 NamedDecl *Lookup = SemaRef.LookupSingleName( 15310 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15311 if (Lookup == Namespace) 15312 break; 15313 } 15314 15315 // Once we have all the namespaces, reverse them to go outermost first, and 15316 // build an NNS. 15317 SmallString<64> Insertion; 15318 llvm::raw_svector_ostream OS(Insertion); 15319 if (DC->isTranslationUnit()) 15320 OS << "::"; 15321 std::reverse(Namespaces.begin(), Namespaces.end()); 15322 for (auto *II : Namespaces) 15323 OS << II->getName() << "::"; 15324 return FixItHint::CreateInsertion(NameLoc, Insertion); 15325 } 15326 15327 /// Determine whether a tag originally declared in context \p OldDC can 15328 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15329 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15330 /// using-declaration). 15331 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15332 DeclContext *NewDC) { 15333 OldDC = OldDC->getRedeclContext(); 15334 NewDC = NewDC->getRedeclContext(); 15335 15336 if (OldDC->Equals(NewDC)) 15337 return true; 15338 15339 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15340 // encloses the other). 15341 if (S.getLangOpts().MSVCCompat && 15342 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15343 return true; 15344 15345 return false; 15346 } 15347 15348 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15349 /// former case, Name will be non-null. In the later case, Name will be null. 15350 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15351 /// reference/declaration/definition of a tag. 15352 /// 15353 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15354 /// trailing-type-specifier) other than one in an alias-declaration. 15355 /// 15356 /// \param SkipBody If non-null, will be set to indicate if the caller should 15357 /// skip the definition of this tag and treat it as if it were a declaration. 15358 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15359 SourceLocation KWLoc, CXXScopeSpec &SS, 15360 IdentifierInfo *Name, SourceLocation NameLoc, 15361 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15362 SourceLocation ModulePrivateLoc, 15363 MultiTemplateParamsArg TemplateParameterLists, 15364 bool &OwnedDecl, bool &IsDependent, 15365 SourceLocation ScopedEnumKWLoc, 15366 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15367 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15368 SkipBodyInfo *SkipBody) { 15369 // If this is not a definition, it must have a name. 15370 IdentifierInfo *OrigName = Name; 15371 assert((Name != nullptr || TUK == TUK_Definition) && 15372 "Nameless record must be a definition!"); 15373 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15374 15375 OwnedDecl = false; 15376 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15377 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15378 15379 // FIXME: Check member specializations more carefully. 15380 bool isMemberSpecialization = false; 15381 bool Invalid = false; 15382 15383 // We only need to do this matching if we have template parameters 15384 // or a scope specifier, which also conveniently avoids this work 15385 // for non-C++ cases. 15386 if (TemplateParameterLists.size() > 0 || 15387 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15388 if (TemplateParameterList *TemplateParams = 15389 MatchTemplateParametersToScopeSpecifier( 15390 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15391 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15392 if (Kind == TTK_Enum) { 15393 Diag(KWLoc, diag::err_enum_template); 15394 return nullptr; 15395 } 15396 15397 if (TemplateParams->size() > 0) { 15398 // This is a declaration or definition of a class template (which may 15399 // be a member of another template). 15400 15401 if (Invalid) 15402 return nullptr; 15403 15404 OwnedDecl = false; 15405 DeclResult Result = CheckClassTemplate( 15406 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15407 AS, ModulePrivateLoc, 15408 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15409 TemplateParameterLists.data(), SkipBody); 15410 return Result.get(); 15411 } else { 15412 // The "template<>" header is extraneous. 15413 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15414 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15415 isMemberSpecialization = true; 15416 } 15417 } 15418 15419 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15420 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15421 return nullptr; 15422 } 15423 15424 // Figure out the underlying type if this a enum declaration. We need to do 15425 // this early, because it's needed to detect if this is an incompatible 15426 // redeclaration. 15427 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15428 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15429 15430 if (Kind == TTK_Enum) { 15431 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15432 // No underlying type explicitly specified, or we failed to parse the 15433 // type, default to int. 15434 EnumUnderlying = Context.IntTy.getTypePtr(); 15435 } else if (UnderlyingType.get()) { 15436 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15437 // integral type; any cv-qualification is ignored. 15438 TypeSourceInfo *TI = nullptr; 15439 GetTypeFromParser(UnderlyingType.get(), &TI); 15440 EnumUnderlying = TI; 15441 15442 if (CheckEnumUnderlyingType(TI)) 15443 // Recover by falling back to int. 15444 EnumUnderlying = Context.IntTy.getTypePtr(); 15445 15446 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15447 UPPC_FixedUnderlyingType)) 15448 EnumUnderlying = Context.IntTy.getTypePtr(); 15449 15450 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15451 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15452 // of 'int'. However, if this is an unfixed forward declaration, don't set 15453 // the underlying type unless the user enables -fms-compatibility. This 15454 // makes unfixed forward declared enums incomplete and is more conforming. 15455 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15456 EnumUnderlying = Context.IntTy.getTypePtr(); 15457 } 15458 } 15459 15460 DeclContext *SearchDC = CurContext; 15461 DeclContext *DC = CurContext; 15462 bool isStdBadAlloc = false; 15463 bool isStdAlignValT = false; 15464 15465 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15466 if (TUK == TUK_Friend || TUK == TUK_Reference) 15467 Redecl = NotForRedeclaration; 15468 15469 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15470 /// implemented asks for structural equivalence checking, the returned decl 15471 /// here is passed back to the parser, allowing the tag body to be parsed. 15472 auto createTagFromNewDecl = [&]() -> TagDecl * { 15473 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15474 // If there is an identifier, use the location of the identifier as the 15475 // location of the decl, otherwise use the location of the struct/union 15476 // keyword. 15477 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15478 TagDecl *New = nullptr; 15479 15480 if (Kind == TTK_Enum) { 15481 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15482 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15483 // If this is an undefined enum, bail. 15484 if (TUK != TUK_Definition && !Invalid) 15485 return nullptr; 15486 if (EnumUnderlying) { 15487 EnumDecl *ED = cast<EnumDecl>(New); 15488 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15489 ED->setIntegerTypeSourceInfo(TI); 15490 else 15491 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15492 ED->setPromotionType(ED->getIntegerType()); 15493 } 15494 } else { // struct/union 15495 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15496 nullptr); 15497 } 15498 15499 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15500 // Add alignment attributes if necessary; these attributes are checked 15501 // when the ASTContext lays out the structure. 15502 // 15503 // It is important for implementing the correct semantics that this 15504 // happen here (in ActOnTag). The #pragma pack stack is 15505 // maintained as a result of parser callbacks which can occur at 15506 // many points during the parsing of a struct declaration (because 15507 // the #pragma tokens are effectively skipped over during the 15508 // parsing of the struct). 15509 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15510 AddAlignmentAttributesForRecord(RD); 15511 AddMsStructLayoutForRecord(RD); 15512 } 15513 } 15514 New->setLexicalDeclContext(CurContext); 15515 return New; 15516 }; 15517 15518 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15519 if (Name && SS.isNotEmpty()) { 15520 // We have a nested-name tag ('struct foo::bar'). 15521 15522 // Check for invalid 'foo::'. 15523 if (SS.isInvalid()) { 15524 Name = nullptr; 15525 goto CreateNewDecl; 15526 } 15527 15528 // If this is a friend or a reference to a class in a dependent 15529 // context, don't try to make a decl for it. 15530 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15531 DC = computeDeclContext(SS, false); 15532 if (!DC) { 15533 IsDependent = true; 15534 return nullptr; 15535 } 15536 } else { 15537 DC = computeDeclContext(SS, true); 15538 if (!DC) { 15539 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15540 << SS.getRange(); 15541 return nullptr; 15542 } 15543 } 15544 15545 if (RequireCompleteDeclContext(SS, DC)) 15546 return nullptr; 15547 15548 SearchDC = DC; 15549 // Look-up name inside 'foo::'. 15550 LookupQualifiedName(Previous, DC); 15551 15552 if (Previous.isAmbiguous()) 15553 return nullptr; 15554 15555 if (Previous.empty()) { 15556 // Name lookup did not find anything. However, if the 15557 // nested-name-specifier refers to the current instantiation, 15558 // and that current instantiation has any dependent base 15559 // classes, we might find something at instantiation time: treat 15560 // this as a dependent elaborated-type-specifier. 15561 // But this only makes any sense for reference-like lookups. 15562 if (Previous.wasNotFoundInCurrentInstantiation() && 15563 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15564 IsDependent = true; 15565 return nullptr; 15566 } 15567 15568 // A tag 'foo::bar' must already exist. 15569 Diag(NameLoc, diag::err_not_tag_in_scope) 15570 << Kind << Name << DC << SS.getRange(); 15571 Name = nullptr; 15572 Invalid = true; 15573 goto CreateNewDecl; 15574 } 15575 } else if (Name) { 15576 // C++14 [class.mem]p14: 15577 // If T is the name of a class, then each of the following shall have a 15578 // name different from T: 15579 // -- every member of class T that is itself a type 15580 if (TUK != TUK_Reference && TUK != TUK_Friend && 15581 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15582 return nullptr; 15583 15584 // If this is a named struct, check to see if there was a previous forward 15585 // declaration or definition. 15586 // FIXME: We're looking into outer scopes here, even when we 15587 // shouldn't be. Doing so can result in ambiguities that we 15588 // shouldn't be diagnosing. 15589 LookupName(Previous, S); 15590 15591 // When declaring or defining a tag, ignore ambiguities introduced 15592 // by types using'ed into this scope. 15593 if (Previous.isAmbiguous() && 15594 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15595 LookupResult::Filter F = Previous.makeFilter(); 15596 while (F.hasNext()) { 15597 NamedDecl *ND = F.next(); 15598 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15599 SearchDC->getRedeclContext())) 15600 F.erase(); 15601 } 15602 F.done(); 15603 } 15604 15605 // C++11 [namespace.memdef]p3: 15606 // If the name in a friend declaration is neither qualified nor 15607 // a template-id and the declaration is a function or an 15608 // elaborated-type-specifier, the lookup to determine whether 15609 // the entity has been previously declared shall not consider 15610 // any scopes outside the innermost enclosing namespace. 15611 // 15612 // MSVC doesn't implement the above rule for types, so a friend tag 15613 // declaration may be a redeclaration of a type declared in an enclosing 15614 // scope. They do implement this rule for friend functions. 15615 // 15616 // Does it matter that this should be by scope instead of by 15617 // semantic context? 15618 if (!Previous.empty() && TUK == TUK_Friend) { 15619 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15620 LookupResult::Filter F = Previous.makeFilter(); 15621 bool FriendSawTagOutsideEnclosingNamespace = false; 15622 while (F.hasNext()) { 15623 NamedDecl *ND = F.next(); 15624 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15625 if (DC->isFileContext() && 15626 !EnclosingNS->Encloses(ND->getDeclContext())) { 15627 if (getLangOpts().MSVCCompat) 15628 FriendSawTagOutsideEnclosingNamespace = true; 15629 else 15630 F.erase(); 15631 } 15632 } 15633 F.done(); 15634 15635 // Diagnose this MSVC extension in the easy case where lookup would have 15636 // unambiguously found something outside the enclosing namespace. 15637 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15638 NamedDecl *ND = Previous.getFoundDecl(); 15639 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15640 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15641 } 15642 } 15643 15644 // Note: there used to be some attempt at recovery here. 15645 if (Previous.isAmbiguous()) 15646 return nullptr; 15647 15648 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15649 // FIXME: This makes sure that we ignore the contexts associated 15650 // with C structs, unions, and enums when looking for a matching 15651 // tag declaration or definition. See the similar lookup tweak 15652 // in Sema::LookupName; is there a better way to deal with this? 15653 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15654 SearchDC = SearchDC->getParent(); 15655 } 15656 } 15657 15658 if (Previous.isSingleResult() && 15659 Previous.getFoundDecl()->isTemplateParameter()) { 15660 // Maybe we will complain about the shadowed template parameter. 15661 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15662 // Just pretend that we didn't see the previous declaration. 15663 Previous.clear(); 15664 } 15665 15666 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15667 DC->Equals(getStdNamespace())) { 15668 if (Name->isStr("bad_alloc")) { 15669 // This is a declaration of or a reference to "std::bad_alloc". 15670 isStdBadAlloc = true; 15671 15672 // If std::bad_alloc has been implicitly declared (but made invisible to 15673 // name lookup), fill in this implicit declaration as the previous 15674 // declaration, so that the declarations get chained appropriately. 15675 if (Previous.empty() && StdBadAlloc) 15676 Previous.addDecl(getStdBadAlloc()); 15677 } else if (Name->isStr("align_val_t")) { 15678 isStdAlignValT = true; 15679 if (Previous.empty() && StdAlignValT) 15680 Previous.addDecl(getStdAlignValT()); 15681 } 15682 } 15683 15684 // If we didn't find a previous declaration, and this is a reference 15685 // (or friend reference), move to the correct scope. In C++, we 15686 // also need to do a redeclaration lookup there, just in case 15687 // there's a shadow friend decl. 15688 if (Name && Previous.empty() && 15689 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15690 if (Invalid) goto CreateNewDecl; 15691 assert(SS.isEmpty()); 15692 15693 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15694 // C++ [basic.scope.pdecl]p5: 15695 // -- for an elaborated-type-specifier of the form 15696 // 15697 // class-key identifier 15698 // 15699 // if the elaborated-type-specifier is used in the 15700 // decl-specifier-seq or parameter-declaration-clause of a 15701 // function defined in namespace scope, the identifier is 15702 // declared as a class-name in the namespace that contains 15703 // the declaration; otherwise, except as a friend 15704 // declaration, the identifier is declared in the smallest 15705 // non-class, non-function-prototype scope that contains the 15706 // declaration. 15707 // 15708 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15709 // C structs and unions. 15710 // 15711 // It is an error in C++ to declare (rather than define) an enum 15712 // type, including via an elaborated type specifier. We'll 15713 // diagnose that later; for now, declare the enum in the same 15714 // scope as we would have picked for any other tag type. 15715 // 15716 // GNU C also supports this behavior as part of its incomplete 15717 // enum types extension, while GNU C++ does not. 15718 // 15719 // Find the context where we'll be declaring the tag. 15720 // FIXME: We would like to maintain the current DeclContext as the 15721 // lexical context, 15722 SearchDC = getTagInjectionContext(SearchDC); 15723 15724 // Find the scope where we'll be declaring the tag. 15725 S = getTagInjectionScope(S, getLangOpts()); 15726 } else { 15727 assert(TUK == TUK_Friend); 15728 // C++ [namespace.memdef]p3: 15729 // If a friend declaration in a non-local class first declares a 15730 // class or function, the friend class or function is a member of 15731 // the innermost enclosing namespace. 15732 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15733 } 15734 15735 // In C++, we need to do a redeclaration lookup to properly 15736 // diagnose some problems. 15737 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15738 // hidden declaration so that we don't get ambiguity errors when using a 15739 // type declared by an elaborated-type-specifier. In C that is not correct 15740 // and we should instead merge compatible types found by lookup. 15741 if (getLangOpts().CPlusPlus) { 15742 // FIXME: This can perform qualified lookups into function contexts, 15743 // which are meaningless. 15744 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15745 LookupQualifiedName(Previous, SearchDC); 15746 } else { 15747 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15748 LookupName(Previous, S); 15749 } 15750 } 15751 15752 // If we have a known previous declaration to use, then use it. 15753 if (Previous.empty() && SkipBody && SkipBody->Previous) 15754 Previous.addDecl(SkipBody->Previous); 15755 15756 if (!Previous.empty()) { 15757 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15758 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15759 15760 // It's okay to have a tag decl in the same scope as a typedef 15761 // which hides a tag decl in the same scope. Finding this 15762 // insanity with a redeclaration lookup can only actually happen 15763 // in C++. 15764 // 15765 // This is also okay for elaborated-type-specifiers, which is 15766 // technically forbidden by the current standard but which is 15767 // okay according to the likely resolution of an open issue; 15768 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15769 if (getLangOpts().CPlusPlus) { 15770 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15771 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15772 TagDecl *Tag = TT->getDecl(); 15773 if (Tag->getDeclName() == Name && 15774 Tag->getDeclContext()->getRedeclContext() 15775 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15776 PrevDecl = Tag; 15777 Previous.clear(); 15778 Previous.addDecl(Tag); 15779 Previous.resolveKind(); 15780 } 15781 } 15782 } 15783 } 15784 15785 // If this is a redeclaration of a using shadow declaration, it must 15786 // declare a tag in the same context. In MSVC mode, we allow a 15787 // redefinition if either context is within the other. 15788 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15789 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15790 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15791 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15792 !(OldTag && isAcceptableTagRedeclContext( 15793 *this, OldTag->getDeclContext(), SearchDC))) { 15794 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15795 Diag(Shadow->getTargetDecl()->getLocation(), 15796 diag::note_using_decl_target); 15797 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15798 << 0; 15799 // Recover by ignoring the old declaration. 15800 Previous.clear(); 15801 goto CreateNewDecl; 15802 } 15803 } 15804 15805 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15806 // If this is a use of a previous tag, or if the tag is already declared 15807 // in the same scope (so that the definition/declaration completes or 15808 // rementions the tag), reuse the decl. 15809 if (TUK == TUK_Reference || TUK == TUK_Friend || 15810 isDeclInScope(DirectPrevDecl, SearchDC, S, 15811 SS.isNotEmpty() || isMemberSpecialization)) { 15812 // Make sure that this wasn't declared as an enum and now used as a 15813 // struct or something similar. 15814 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15815 TUK == TUK_Definition, KWLoc, 15816 Name)) { 15817 bool SafeToContinue 15818 = (PrevTagDecl->getTagKind() != TTK_Enum && 15819 Kind != TTK_Enum); 15820 if (SafeToContinue) 15821 Diag(KWLoc, diag::err_use_with_wrong_tag) 15822 << Name 15823 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15824 PrevTagDecl->getKindName()); 15825 else 15826 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15827 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15828 15829 if (SafeToContinue) 15830 Kind = PrevTagDecl->getTagKind(); 15831 else { 15832 // Recover by making this an anonymous redefinition. 15833 Name = nullptr; 15834 Previous.clear(); 15835 Invalid = true; 15836 } 15837 } 15838 15839 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15840 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15841 if (TUK == TUK_Reference || TUK == TUK_Friend) 15842 return PrevTagDecl; 15843 15844 QualType EnumUnderlyingTy; 15845 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15846 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15847 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15848 EnumUnderlyingTy = QualType(T, 0); 15849 15850 // All conflicts with previous declarations are recovered by 15851 // returning the previous declaration, unless this is a definition, 15852 // in which case we want the caller to bail out. 15853 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15854 ScopedEnum, EnumUnderlyingTy, 15855 IsFixed, PrevEnum)) 15856 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15857 } 15858 15859 // C++11 [class.mem]p1: 15860 // A member shall not be declared twice in the member-specification, 15861 // except that a nested class or member class template can be declared 15862 // and then later defined. 15863 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15864 S->isDeclScope(PrevDecl)) { 15865 Diag(NameLoc, diag::ext_member_redeclared); 15866 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15867 } 15868 15869 if (!Invalid) { 15870 // If this is a use, just return the declaration we found, unless 15871 // we have attributes. 15872 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15873 if (!Attrs.empty()) { 15874 // FIXME: Diagnose these attributes. For now, we create a new 15875 // declaration to hold them. 15876 } else if (TUK == TUK_Reference && 15877 (PrevTagDecl->getFriendObjectKind() == 15878 Decl::FOK_Undeclared || 15879 PrevDecl->getOwningModule() != getCurrentModule()) && 15880 SS.isEmpty()) { 15881 // This declaration is a reference to an existing entity, but 15882 // has different visibility from that entity: it either makes 15883 // a friend visible or it makes a type visible in a new module. 15884 // In either case, create a new declaration. We only do this if 15885 // the declaration would have meant the same thing if no prior 15886 // declaration were found, that is, if it was found in the same 15887 // scope where we would have injected a declaration. 15888 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15889 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15890 return PrevTagDecl; 15891 // This is in the injected scope, create a new declaration in 15892 // that scope. 15893 S = getTagInjectionScope(S, getLangOpts()); 15894 } else { 15895 return PrevTagDecl; 15896 } 15897 } 15898 15899 // Diagnose attempts to redefine a tag. 15900 if (TUK == TUK_Definition) { 15901 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15902 // If we're defining a specialization and the previous definition 15903 // is from an implicit instantiation, don't emit an error 15904 // here; we'll catch this in the general case below. 15905 bool IsExplicitSpecializationAfterInstantiation = false; 15906 if (isMemberSpecialization) { 15907 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15908 IsExplicitSpecializationAfterInstantiation = 15909 RD->getTemplateSpecializationKind() != 15910 TSK_ExplicitSpecialization; 15911 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15912 IsExplicitSpecializationAfterInstantiation = 15913 ED->getTemplateSpecializationKind() != 15914 TSK_ExplicitSpecialization; 15915 } 15916 15917 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15918 // not keep more that one definition around (merge them). However, 15919 // ensure the decl passes the structural compatibility check in 15920 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15921 NamedDecl *Hidden = nullptr; 15922 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15923 // There is a definition of this tag, but it is not visible. We 15924 // explicitly make use of C++'s one definition rule here, and 15925 // assume that this definition is identical to the hidden one 15926 // we already have. Make the existing definition visible and 15927 // use it in place of this one. 15928 if (!getLangOpts().CPlusPlus) { 15929 // Postpone making the old definition visible until after we 15930 // complete parsing the new one and do the structural 15931 // comparison. 15932 SkipBody->CheckSameAsPrevious = true; 15933 SkipBody->New = createTagFromNewDecl(); 15934 SkipBody->Previous = Def; 15935 return Def; 15936 } else { 15937 SkipBody->ShouldSkip = true; 15938 SkipBody->Previous = Def; 15939 makeMergedDefinitionVisible(Hidden); 15940 // Carry on and handle it like a normal definition. We'll 15941 // skip starting the definitiion later. 15942 } 15943 } else if (!IsExplicitSpecializationAfterInstantiation) { 15944 // A redeclaration in function prototype scope in C isn't 15945 // visible elsewhere, so merely issue a warning. 15946 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15947 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15948 else 15949 Diag(NameLoc, diag::err_redefinition) << Name; 15950 notePreviousDefinition(Def, 15951 NameLoc.isValid() ? NameLoc : KWLoc); 15952 // If this is a redefinition, recover by making this 15953 // struct be anonymous, which will make any later 15954 // references get the previous definition. 15955 Name = nullptr; 15956 Previous.clear(); 15957 Invalid = true; 15958 } 15959 } else { 15960 // If the type is currently being defined, complain 15961 // about a nested redefinition. 15962 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15963 if (TD->isBeingDefined()) { 15964 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15965 Diag(PrevTagDecl->getLocation(), 15966 diag::note_previous_definition); 15967 Name = nullptr; 15968 Previous.clear(); 15969 Invalid = true; 15970 } 15971 } 15972 15973 // Okay, this is definition of a previously declared or referenced 15974 // tag. We're going to create a new Decl for it. 15975 } 15976 15977 // Okay, we're going to make a redeclaration. If this is some kind 15978 // of reference, make sure we build the redeclaration in the same DC 15979 // as the original, and ignore the current access specifier. 15980 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15981 SearchDC = PrevTagDecl->getDeclContext(); 15982 AS = AS_none; 15983 } 15984 } 15985 // If we get here we have (another) forward declaration or we 15986 // have a definition. Just create a new decl. 15987 15988 } else { 15989 // If we get here, this is a definition of a new tag type in a nested 15990 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15991 // new decl/type. We set PrevDecl to NULL so that the entities 15992 // have distinct types. 15993 Previous.clear(); 15994 } 15995 // If we get here, we're going to create a new Decl. If PrevDecl 15996 // is non-NULL, it's a definition of the tag declared by 15997 // PrevDecl. If it's NULL, we have a new definition. 15998 15999 // Otherwise, PrevDecl is not a tag, but was found with tag 16000 // lookup. This is only actually possible in C++, where a few 16001 // things like templates still live in the tag namespace. 16002 } else { 16003 // Use a better diagnostic if an elaborated-type-specifier 16004 // found the wrong kind of type on the first 16005 // (non-redeclaration) lookup. 16006 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16007 !Previous.isForRedeclaration()) { 16008 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16009 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16010 << Kind; 16011 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16012 Invalid = true; 16013 16014 // Otherwise, only diagnose if the declaration is in scope. 16015 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16016 SS.isNotEmpty() || isMemberSpecialization)) { 16017 // do nothing 16018 16019 // Diagnose implicit declarations introduced by elaborated types. 16020 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16021 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16022 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16023 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16024 Invalid = true; 16025 16026 // Otherwise it's a declaration. Call out a particularly common 16027 // case here. 16028 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16029 unsigned Kind = 0; 16030 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16031 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16032 << Name << Kind << TND->getUnderlyingType(); 16033 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16034 Invalid = true; 16035 16036 // Otherwise, diagnose. 16037 } else { 16038 // The tag name clashes with something else in the target scope, 16039 // issue an error and recover by making this tag be anonymous. 16040 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16041 notePreviousDefinition(PrevDecl, NameLoc); 16042 Name = nullptr; 16043 Invalid = true; 16044 } 16045 16046 // The existing declaration isn't relevant to us; we're in a 16047 // new scope, so clear out the previous declaration. 16048 Previous.clear(); 16049 } 16050 } 16051 16052 CreateNewDecl: 16053 16054 TagDecl *PrevDecl = nullptr; 16055 if (Previous.isSingleResult()) 16056 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16057 16058 // If there is an identifier, use the location of the identifier as the 16059 // location of the decl, otherwise use the location of the struct/union 16060 // keyword. 16061 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16062 16063 // Otherwise, create a new declaration. If there is a previous 16064 // declaration of the same entity, the two will be linked via 16065 // PrevDecl. 16066 TagDecl *New; 16067 16068 if (Kind == TTK_Enum) { 16069 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16070 // enum X { A, B, C } D; D should chain to X. 16071 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16072 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16073 ScopedEnumUsesClassTag, IsFixed); 16074 16075 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16076 StdAlignValT = cast<EnumDecl>(New); 16077 16078 // If this is an undefined enum, warn. 16079 if (TUK != TUK_Definition && !Invalid) { 16080 TagDecl *Def; 16081 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16082 // C++0x: 7.2p2: opaque-enum-declaration. 16083 // Conflicts are diagnosed above. Do nothing. 16084 } 16085 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16086 Diag(Loc, diag::ext_forward_ref_enum_def) 16087 << New; 16088 Diag(Def->getLocation(), diag::note_previous_definition); 16089 } else { 16090 unsigned DiagID = diag::ext_forward_ref_enum; 16091 if (getLangOpts().MSVCCompat) 16092 DiagID = diag::ext_ms_forward_ref_enum; 16093 else if (getLangOpts().CPlusPlus) 16094 DiagID = diag::err_forward_ref_enum; 16095 Diag(Loc, DiagID); 16096 } 16097 } 16098 16099 if (EnumUnderlying) { 16100 EnumDecl *ED = cast<EnumDecl>(New); 16101 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16102 ED->setIntegerTypeSourceInfo(TI); 16103 else 16104 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16105 ED->setPromotionType(ED->getIntegerType()); 16106 assert(ED->isComplete() && "enum with type should be complete"); 16107 } 16108 } else { 16109 // struct/union/class 16110 16111 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16112 // struct X { int A; } D; D should chain to X. 16113 if (getLangOpts().CPlusPlus) { 16114 // FIXME: Look for a way to use RecordDecl for simple structs. 16115 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16116 cast_or_null<CXXRecordDecl>(PrevDecl)); 16117 16118 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16119 StdBadAlloc = cast<CXXRecordDecl>(New); 16120 } else 16121 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16122 cast_or_null<RecordDecl>(PrevDecl)); 16123 } 16124 16125 // C++11 [dcl.type]p3: 16126 // A type-specifier-seq shall not define a class or enumeration [...]. 16127 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16128 TUK == TUK_Definition) { 16129 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16130 << Context.getTagDeclType(New); 16131 Invalid = true; 16132 } 16133 16134 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16135 DC->getDeclKind() == Decl::Enum) { 16136 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16137 << Context.getTagDeclType(New); 16138 Invalid = true; 16139 } 16140 16141 // Maybe add qualifier info. 16142 if (SS.isNotEmpty()) { 16143 if (SS.isSet()) { 16144 // If this is either a declaration or a definition, check the 16145 // nested-name-specifier against the current context. 16146 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16147 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16148 isMemberSpecialization)) 16149 Invalid = true; 16150 16151 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16152 if (TemplateParameterLists.size() > 0) { 16153 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16154 } 16155 } 16156 else 16157 Invalid = true; 16158 } 16159 16160 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16161 // Add alignment attributes if necessary; these attributes are checked when 16162 // the ASTContext lays out the structure. 16163 // 16164 // It is important for implementing the correct semantics that this 16165 // happen here (in ActOnTag). The #pragma pack stack is 16166 // maintained as a result of parser callbacks which can occur at 16167 // many points during the parsing of a struct declaration (because 16168 // the #pragma tokens are effectively skipped over during the 16169 // parsing of the struct). 16170 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16171 AddAlignmentAttributesForRecord(RD); 16172 AddMsStructLayoutForRecord(RD); 16173 } 16174 } 16175 16176 if (ModulePrivateLoc.isValid()) { 16177 if (isMemberSpecialization) 16178 Diag(New->getLocation(), diag::err_module_private_specialization) 16179 << 2 16180 << FixItHint::CreateRemoval(ModulePrivateLoc); 16181 // __module_private__ does not apply to local classes. However, we only 16182 // diagnose this as an error when the declaration specifiers are 16183 // freestanding. Here, we just ignore the __module_private__. 16184 else if (!SearchDC->isFunctionOrMethod()) 16185 New->setModulePrivate(); 16186 } 16187 16188 // If this is a specialization of a member class (of a class template), 16189 // check the specialization. 16190 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16191 Invalid = true; 16192 16193 // If we're declaring or defining a tag in function prototype scope in C, 16194 // note that this type can only be used within the function and add it to 16195 // the list of decls to inject into the function definition scope. 16196 if ((Name || Kind == TTK_Enum) && 16197 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16198 if (getLangOpts().CPlusPlus) { 16199 // C++ [dcl.fct]p6: 16200 // Types shall not be defined in return or parameter types. 16201 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16202 Diag(Loc, diag::err_type_defined_in_param_type) 16203 << Name; 16204 Invalid = true; 16205 } 16206 } else if (!PrevDecl) { 16207 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16208 } 16209 } 16210 16211 if (Invalid) 16212 New->setInvalidDecl(); 16213 16214 // Set the lexical context. If the tag has a C++ scope specifier, the 16215 // lexical context will be different from the semantic context. 16216 New->setLexicalDeclContext(CurContext); 16217 16218 // Mark this as a friend decl if applicable. 16219 // In Microsoft mode, a friend declaration also acts as a forward 16220 // declaration so we always pass true to setObjectOfFriendDecl to make 16221 // the tag name visible. 16222 if (TUK == TUK_Friend) 16223 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16224 16225 // Set the access specifier. 16226 if (!Invalid && SearchDC->isRecord()) 16227 SetMemberAccessSpecifier(New, PrevDecl, AS); 16228 16229 if (PrevDecl) 16230 CheckRedeclarationModuleOwnership(New, PrevDecl); 16231 16232 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16233 New->startDefinition(); 16234 16235 ProcessDeclAttributeList(S, New, Attrs); 16236 AddPragmaAttributes(S, New); 16237 16238 // If this has an identifier, add it to the scope stack. 16239 if (TUK == TUK_Friend) { 16240 // We might be replacing an existing declaration in the lookup tables; 16241 // if so, borrow its access specifier. 16242 if (PrevDecl) 16243 New->setAccess(PrevDecl->getAccess()); 16244 16245 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16246 DC->makeDeclVisibleInContext(New); 16247 if (Name) // can be null along some error paths 16248 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16249 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16250 } else if (Name) { 16251 S = getNonFieldDeclScope(S); 16252 PushOnScopeChains(New, S, true); 16253 } else { 16254 CurContext->addDecl(New); 16255 } 16256 16257 // If this is the C FILE type, notify the AST context. 16258 if (IdentifierInfo *II = New->getIdentifier()) 16259 if (!New->isInvalidDecl() && 16260 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16261 II->isStr("FILE")) 16262 Context.setFILEDecl(New); 16263 16264 if (PrevDecl) 16265 mergeDeclAttributes(New, PrevDecl); 16266 16267 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16268 inferGslOwnerPointerAttribute(CXXRD); 16269 16270 // If there's a #pragma GCC visibility in scope, set the visibility of this 16271 // record. 16272 AddPushedVisibilityAttribute(New); 16273 16274 if (isMemberSpecialization && !New->isInvalidDecl()) 16275 CompleteMemberSpecialization(New, Previous); 16276 16277 OwnedDecl = true; 16278 // In C++, don't return an invalid declaration. We can't recover well from 16279 // the cases where we make the type anonymous. 16280 if (Invalid && getLangOpts().CPlusPlus) { 16281 if (New->isBeingDefined()) 16282 if (auto RD = dyn_cast<RecordDecl>(New)) 16283 RD->completeDefinition(); 16284 return nullptr; 16285 } else if (SkipBody && SkipBody->ShouldSkip) { 16286 return SkipBody->Previous; 16287 } else { 16288 return New; 16289 } 16290 } 16291 16292 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16293 AdjustDeclIfTemplate(TagD); 16294 TagDecl *Tag = cast<TagDecl>(TagD); 16295 16296 // Enter the tag context. 16297 PushDeclContext(S, Tag); 16298 16299 ActOnDocumentableDecl(TagD); 16300 16301 // If there's a #pragma GCC visibility in scope, set the visibility of this 16302 // record. 16303 AddPushedVisibilityAttribute(Tag); 16304 } 16305 16306 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16307 SkipBodyInfo &SkipBody) { 16308 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16309 return false; 16310 16311 // Make the previous decl visible. 16312 makeMergedDefinitionVisible(SkipBody.Previous); 16313 return true; 16314 } 16315 16316 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16317 assert(isa<ObjCContainerDecl>(IDecl) && 16318 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16319 DeclContext *OCD = cast<DeclContext>(IDecl); 16320 assert(OCD->getLexicalParent() == CurContext && 16321 "The next DeclContext should be lexically contained in the current one."); 16322 CurContext = OCD; 16323 return IDecl; 16324 } 16325 16326 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16327 SourceLocation FinalLoc, 16328 bool IsFinalSpelledSealed, 16329 SourceLocation LBraceLoc) { 16330 AdjustDeclIfTemplate(TagD); 16331 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16332 16333 FieldCollector->StartClass(); 16334 16335 if (!Record->getIdentifier()) 16336 return; 16337 16338 if (FinalLoc.isValid()) 16339 Record->addAttr(FinalAttr::Create( 16340 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16341 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16342 16343 // C++ [class]p2: 16344 // [...] The class-name is also inserted into the scope of the 16345 // class itself; this is known as the injected-class-name. For 16346 // purposes of access checking, the injected-class-name is treated 16347 // as if it were a public member name. 16348 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16349 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16350 Record->getLocation(), Record->getIdentifier(), 16351 /*PrevDecl=*/nullptr, 16352 /*DelayTypeCreation=*/true); 16353 Context.getTypeDeclType(InjectedClassName, Record); 16354 InjectedClassName->setImplicit(); 16355 InjectedClassName->setAccess(AS_public); 16356 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16357 InjectedClassName->setDescribedClassTemplate(Template); 16358 PushOnScopeChains(InjectedClassName, S); 16359 assert(InjectedClassName->isInjectedClassName() && 16360 "Broken injected-class-name"); 16361 } 16362 16363 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16364 SourceRange BraceRange) { 16365 AdjustDeclIfTemplate(TagD); 16366 TagDecl *Tag = cast<TagDecl>(TagD); 16367 Tag->setBraceRange(BraceRange); 16368 16369 // Make sure we "complete" the definition even it is invalid. 16370 if (Tag->isBeingDefined()) { 16371 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16372 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16373 RD->completeDefinition(); 16374 } 16375 16376 if (isa<CXXRecordDecl>(Tag)) { 16377 FieldCollector->FinishClass(); 16378 } 16379 16380 // Exit this scope of this tag's definition. 16381 PopDeclContext(); 16382 16383 if (getCurLexicalContext()->isObjCContainer() && 16384 Tag->getDeclContext()->isFileContext()) 16385 Tag->setTopLevelDeclInObjCContainer(); 16386 16387 // Notify the consumer that we've defined a tag. 16388 if (!Tag->isInvalidDecl()) 16389 Consumer.HandleTagDeclDefinition(Tag); 16390 } 16391 16392 void Sema::ActOnObjCContainerFinishDefinition() { 16393 // Exit this scope of this interface definition. 16394 PopDeclContext(); 16395 } 16396 16397 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16398 assert(DC == CurContext && "Mismatch of container contexts"); 16399 OriginalLexicalContext = DC; 16400 ActOnObjCContainerFinishDefinition(); 16401 } 16402 16403 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16404 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16405 OriginalLexicalContext = nullptr; 16406 } 16407 16408 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16409 AdjustDeclIfTemplate(TagD); 16410 TagDecl *Tag = cast<TagDecl>(TagD); 16411 Tag->setInvalidDecl(); 16412 16413 // Make sure we "complete" the definition even it is invalid. 16414 if (Tag->isBeingDefined()) { 16415 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16416 RD->completeDefinition(); 16417 } 16418 16419 // We're undoing ActOnTagStartDefinition here, not 16420 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16421 // the FieldCollector. 16422 16423 PopDeclContext(); 16424 } 16425 16426 // Note that FieldName may be null for anonymous bitfields. 16427 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16428 IdentifierInfo *FieldName, 16429 QualType FieldTy, bool IsMsStruct, 16430 Expr *BitWidth, bool *ZeroWidth) { 16431 assert(BitWidth); 16432 if (BitWidth->containsErrors()) 16433 return ExprError(); 16434 16435 // Default to true; that shouldn't confuse checks for emptiness 16436 if (ZeroWidth) 16437 *ZeroWidth = true; 16438 16439 // C99 6.7.2.1p4 - verify the field type. 16440 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16441 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16442 // Handle incomplete and sizeless types with a specific error. 16443 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16444 diag::err_field_incomplete_or_sizeless)) 16445 return ExprError(); 16446 if (FieldName) 16447 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16448 << FieldName << FieldTy << BitWidth->getSourceRange(); 16449 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16450 << FieldTy << BitWidth->getSourceRange(); 16451 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16452 UPPC_BitFieldWidth)) 16453 return ExprError(); 16454 16455 // If the bit-width is type- or value-dependent, don't try to check 16456 // it now. 16457 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16458 return BitWidth; 16459 16460 llvm::APSInt Value; 16461 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16462 if (ICE.isInvalid()) 16463 return ICE; 16464 BitWidth = ICE.get(); 16465 16466 if (Value != 0 && ZeroWidth) 16467 *ZeroWidth = false; 16468 16469 // Zero-width bitfield is ok for anonymous field. 16470 if (Value == 0 && FieldName) 16471 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16472 16473 if (Value.isSigned() && Value.isNegative()) { 16474 if (FieldName) 16475 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16476 << FieldName << Value.toString(10); 16477 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16478 << Value.toString(10); 16479 } 16480 16481 // The size of the bit-field must not exceed our maximum permitted object 16482 // size. 16483 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16484 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16485 << !FieldName << FieldName << Value.toString(10); 16486 } 16487 16488 if (!FieldTy->isDependentType()) { 16489 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16490 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16491 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16492 16493 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16494 // ABI. 16495 bool CStdConstraintViolation = 16496 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16497 bool MSBitfieldViolation = 16498 Value.ugt(TypeStorageSize) && 16499 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16500 if (CStdConstraintViolation || MSBitfieldViolation) { 16501 unsigned DiagWidth = 16502 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16503 if (FieldName) 16504 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16505 << FieldName << Value.toString(10) 16506 << !CStdConstraintViolation << DiagWidth; 16507 16508 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16509 << Value.toString(10) << !CStdConstraintViolation 16510 << DiagWidth; 16511 } 16512 16513 // Warn on types where the user might conceivably expect to get all 16514 // specified bits as value bits: that's all integral types other than 16515 // 'bool'. 16516 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16517 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16518 << FieldName << Value.toString(10) 16519 << (unsigned)TypeWidth; 16520 } 16521 } 16522 16523 return BitWidth; 16524 } 16525 16526 /// ActOnField - Each field of a C struct/union is passed into this in order 16527 /// to create a FieldDecl object for it. 16528 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16529 Declarator &D, Expr *BitfieldWidth) { 16530 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16531 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16532 /*InitStyle=*/ICIS_NoInit, AS_public); 16533 return Res; 16534 } 16535 16536 /// HandleField - Analyze a field of a C struct or a C++ data member. 16537 /// 16538 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16539 SourceLocation DeclStart, 16540 Declarator &D, Expr *BitWidth, 16541 InClassInitStyle InitStyle, 16542 AccessSpecifier AS) { 16543 if (D.isDecompositionDeclarator()) { 16544 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16545 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16546 << Decomp.getSourceRange(); 16547 return nullptr; 16548 } 16549 16550 IdentifierInfo *II = D.getIdentifier(); 16551 SourceLocation Loc = DeclStart; 16552 if (II) Loc = D.getIdentifierLoc(); 16553 16554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16555 QualType T = TInfo->getType(); 16556 if (getLangOpts().CPlusPlus) { 16557 CheckExtraCXXDefaultArguments(D); 16558 16559 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16560 UPPC_DataMemberType)) { 16561 D.setInvalidType(); 16562 T = Context.IntTy; 16563 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16564 } 16565 } 16566 16567 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16568 16569 if (D.getDeclSpec().isInlineSpecified()) 16570 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16571 << getLangOpts().CPlusPlus17; 16572 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16573 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16574 diag::err_invalid_thread) 16575 << DeclSpec::getSpecifierName(TSCS); 16576 16577 // Check to see if this name was declared as a member previously 16578 NamedDecl *PrevDecl = nullptr; 16579 LookupResult Previous(*this, II, Loc, LookupMemberName, 16580 ForVisibleRedeclaration); 16581 LookupName(Previous, S); 16582 switch (Previous.getResultKind()) { 16583 case LookupResult::Found: 16584 case LookupResult::FoundUnresolvedValue: 16585 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16586 break; 16587 16588 case LookupResult::FoundOverloaded: 16589 PrevDecl = Previous.getRepresentativeDecl(); 16590 break; 16591 16592 case LookupResult::NotFound: 16593 case LookupResult::NotFoundInCurrentInstantiation: 16594 case LookupResult::Ambiguous: 16595 break; 16596 } 16597 Previous.suppressDiagnostics(); 16598 16599 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16600 // Maybe we will complain about the shadowed template parameter. 16601 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16602 // Just pretend that we didn't see the previous declaration. 16603 PrevDecl = nullptr; 16604 } 16605 16606 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16607 PrevDecl = nullptr; 16608 16609 bool Mutable 16610 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16611 SourceLocation TSSL = D.getBeginLoc(); 16612 FieldDecl *NewFD 16613 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16614 TSSL, AS, PrevDecl, &D); 16615 16616 if (NewFD->isInvalidDecl()) 16617 Record->setInvalidDecl(); 16618 16619 if (D.getDeclSpec().isModulePrivateSpecified()) 16620 NewFD->setModulePrivate(); 16621 16622 if (NewFD->isInvalidDecl() && PrevDecl) { 16623 // Don't introduce NewFD into scope; there's already something 16624 // with the same name in the same scope. 16625 } else if (II) { 16626 PushOnScopeChains(NewFD, S); 16627 } else 16628 Record->addDecl(NewFD); 16629 16630 return NewFD; 16631 } 16632 16633 /// Build a new FieldDecl and check its well-formedness. 16634 /// 16635 /// This routine builds a new FieldDecl given the fields name, type, 16636 /// record, etc. \p PrevDecl should refer to any previous declaration 16637 /// with the same name and in the same scope as the field to be 16638 /// created. 16639 /// 16640 /// \returns a new FieldDecl. 16641 /// 16642 /// \todo The Declarator argument is a hack. It will be removed once 16643 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16644 TypeSourceInfo *TInfo, 16645 RecordDecl *Record, SourceLocation Loc, 16646 bool Mutable, Expr *BitWidth, 16647 InClassInitStyle InitStyle, 16648 SourceLocation TSSL, 16649 AccessSpecifier AS, NamedDecl *PrevDecl, 16650 Declarator *D) { 16651 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16652 bool InvalidDecl = false; 16653 if (D) InvalidDecl = D->isInvalidType(); 16654 16655 // If we receive a broken type, recover by assuming 'int' and 16656 // marking this declaration as invalid. 16657 if (T.isNull() || T->containsErrors()) { 16658 InvalidDecl = true; 16659 T = Context.IntTy; 16660 } 16661 16662 QualType EltTy = Context.getBaseElementType(T); 16663 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16664 if (RequireCompleteSizedType(Loc, EltTy, 16665 diag::err_field_incomplete_or_sizeless)) { 16666 // Fields of incomplete type force their record to be invalid. 16667 Record->setInvalidDecl(); 16668 InvalidDecl = true; 16669 } else { 16670 NamedDecl *Def; 16671 EltTy->isIncompleteType(&Def); 16672 if (Def && Def->isInvalidDecl()) { 16673 Record->setInvalidDecl(); 16674 InvalidDecl = true; 16675 } 16676 } 16677 } 16678 16679 // TR 18037 does not allow fields to be declared with address space 16680 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16681 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16682 Diag(Loc, diag::err_field_with_address_space); 16683 Record->setInvalidDecl(); 16684 InvalidDecl = true; 16685 } 16686 16687 if (LangOpts.OpenCL) { 16688 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16689 // used as structure or union field: image, sampler, event or block types. 16690 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16691 T->isBlockPointerType()) { 16692 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16693 Record->setInvalidDecl(); 16694 InvalidDecl = true; 16695 } 16696 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16697 if (BitWidth) { 16698 Diag(Loc, diag::err_opencl_bitfields); 16699 InvalidDecl = true; 16700 } 16701 } 16702 16703 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16704 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16705 T.hasQualifiers()) { 16706 InvalidDecl = true; 16707 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16708 } 16709 16710 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16711 // than a variably modified type. 16712 if (!InvalidDecl && T->isVariablyModifiedType()) { 16713 if (!tryToFixVariablyModifiedVarType( 16714 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16715 InvalidDecl = true; 16716 } 16717 16718 // Fields can not have abstract class types 16719 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16720 diag::err_abstract_type_in_decl, 16721 AbstractFieldType)) 16722 InvalidDecl = true; 16723 16724 bool ZeroWidth = false; 16725 if (InvalidDecl) 16726 BitWidth = nullptr; 16727 // If this is declared as a bit-field, check the bit-field. 16728 if (BitWidth) { 16729 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16730 &ZeroWidth).get(); 16731 if (!BitWidth) { 16732 InvalidDecl = true; 16733 BitWidth = nullptr; 16734 ZeroWidth = false; 16735 } 16736 } 16737 16738 // Check that 'mutable' is consistent with the type of the declaration. 16739 if (!InvalidDecl && Mutable) { 16740 unsigned DiagID = 0; 16741 if (T->isReferenceType()) 16742 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16743 : diag::err_mutable_reference; 16744 else if (T.isConstQualified()) 16745 DiagID = diag::err_mutable_const; 16746 16747 if (DiagID) { 16748 SourceLocation ErrLoc = Loc; 16749 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16750 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16751 Diag(ErrLoc, DiagID); 16752 if (DiagID != diag::ext_mutable_reference) { 16753 Mutable = false; 16754 InvalidDecl = true; 16755 } 16756 } 16757 } 16758 16759 // C++11 [class.union]p8 (DR1460): 16760 // At most one variant member of a union may have a 16761 // brace-or-equal-initializer. 16762 if (InitStyle != ICIS_NoInit) 16763 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16764 16765 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16766 BitWidth, Mutable, InitStyle); 16767 if (InvalidDecl) 16768 NewFD->setInvalidDecl(); 16769 16770 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16771 Diag(Loc, diag::err_duplicate_member) << II; 16772 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16773 NewFD->setInvalidDecl(); 16774 } 16775 16776 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16777 if (Record->isUnion()) { 16778 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16779 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16780 if (RDecl->getDefinition()) { 16781 // C++ [class.union]p1: An object of a class with a non-trivial 16782 // constructor, a non-trivial copy constructor, a non-trivial 16783 // destructor, or a non-trivial copy assignment operator 16784 // cannot be a member of a union, nor can an array of such 16785 // objects. 16786 if (CheckNontrivialField(NewFD)) 16787 NewFD->setInvalidDecl(); 16788 } 16789 } 16790 16791 // C++ [class.union]p1: If a union contains a member of reference type, 16792 // the program is ill-formed, except when compiling with MSVC extensions 16793 // enabled. 16794 if (EltTy->isReferenceType()) { 16795 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16796 diag::ext_union_member_of_reference_type : 16797 diag::err_union_member_of_reference_type) 16798 << NewFD->getDeclName() << EltTy; 16799 if (!getLangOpts().MicrosoftExt) 16800 NewFD->setInvalidDecl(); 16801 } 16802 } 16803 } 16804 16805 // FIXME: We need to pass in the attributes given an AST 16806 // representation, not a parser representation. 16807 if (D) { 16808 // FIXME: The current scope is almost... but not entirely... correct here. 16809 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16810 16811 if (NewFD->hasAttrs()) 16812 CheckAlignasUnderalignment(NewFD); 16813 } 16814 16815 // In auto-retain/release, infer strong retension for fields of 16816 // retainable type. 16817 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16818 NewFD->setInvalidDecl(); 16819 16820 if (T.isObjCGCWeak()) 16821 Diag(Loc, diag::warn_attribute_weak_on_field); 16822 16823 // PPC MMA non-pointer types are not allowed as field types. 16824 if (Context.getTargetInfo().getTriple().isPPC64() && 16825 CheckPPCMMAType(T, NewFD->getLocation())) 16826 NewFD->setInvalidDecl(); 16827 16828 NewFD->setAccess(AS); 16829 return NewFD; 16830 } 16831 16832 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16833 assert(FD); 16834 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16835 16836 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16837 return false; 16838 16839 QualType EltTy = Context.getBaseElementType(FD->getType()); 16840 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16841 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16842 if (RDecl->getDefinition()) { 16843 // We check for copy constructors before constructors 16844 // because otherwise we'll never get complaints about 16845 // copy constructors. 16846 16847 CXXSpecialMember member = CXXInvalid; 16848 // We're required to check for any non-trivial constructors. Since the 16849 // implicit default constructor is suppressed if there are any 16850 // user-declared constructors, we just need to check that there is a 16851 // trivial default constructor and a trivial copy constructor. (We don't 16852 // worry about move constructors here, since this is a C++98 check.) 16853 if (RDecl->hasNonTrivialCopyConstructor()) 16854 member = CXXCopyConstructor; 16855 else if (!RDecl->hasTrivialDefaultConstructor()) 16856 member = CXXDefaultConstructor; 16857 else if (RDecl->hasNonTrivialCopyAssignment()) 16858 member = CXXCopyAssignment; 16859 else if (RDecl->hasNonTrivialDestructor()) 16860 member = CXXDestructor; 16861 16862 if (member != CXXInvalid) { 16863 if (!getLangOpts().CPlusPlus11 && 16864 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16865 // Objective-C++ ARC: it is an error to have a non-trivial field of 16866 // a union. However, system headers in Objective-C programs 16867 // occasionally have Objective-C lifetime objects within unions, 16868 // and rather than cause the program to fail, we make those 16869 // members unavailable. 16870 SourceLocation Loc = FD->getLocation(); 16871 if (getSourceManager().isInSystemHeader(Loc)) { 16872 if (!FD->hasAttr<UnavailableAttr>()) 16873 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16874 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16875 return false; 16876 } 16877 } 16878 16879 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16880 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16881 diag::err_illegal_union_or_anon_struct_member) 16882 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16883 DiagnoseNontrivial(RDecl, member); 16884 return !getLangOpts().CPlusPlus11; 16885 } 16886 } 16887 } 16888 16889 return false; 16890 } 16891 16892 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16893 /// AST enum value. 16894 static ObjCIvarDecl::AccessControl 16895 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16896 switch (ivarVisibility) { 16897 default: llvm_unreachable("Unknown visitibility kind"); 16898 case tok::objc_private: return ObjCIvarDecl::Private; 16899 case tok::objc_public: return ObjCIvarDecl::Public; 16900 case tok::objc_protected: return ObjCIvarDecl::Protected; 16901 case tok::objc_package: return ObjCIvarDecl::Package; 16902 } 16903 } 16904 16905 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16906 /// in order to create an IvarDecl object for it. 16907 Decl *Sema::ActOnIvar(Scope *S, 16908 SourceLocation DeclStart, 16909 Declarator &D, Expr *BitfieldWidth, 16910 tok::ObjCKeywordKind Visibility) { 16911 16912 IdentifierInfo *II = D.getIdentifier(); 16913 Expr *BitWidth = (Expr*)BitfieldWidth; 16914 SourceLocation Loc = DeclStart; 16915 if (II) Loc = D.getIdentifierLoc(); 16916 16917 // FIXME: Unnamed fields can be handled in various different ways, for 16918 // example, unnamed unions inject all members into the struct namespace! 16919 16920 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16921 QualType T = TInfo->getType(); 16922 16923 if (BitWidth) { 16924 // 6.7.2.1p3, 6.7.2.1p4 16925 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16926 if (!BitWidth) 16927 D.setInvalidType(); 16928 } else { 16929 // Not a bitfield. 16930 16931 // validate II. 16932 16933 } 16934 if (T->isReferenceType()) { 16935 Diag(Loc, diag::err_ivar_reference_type); 16936 D.setInvalidType(); 16937 } 16938 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16939 // than a variably modified type. 16940 else if (T->isVariablyModifiedType()) { 16941 if (!tryToFixVariablyModifiedVarType( 16942 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 16943 D.setInvalidType(); 16944 } 16945 16946 // Get the visibility (access control) for this ivar. 16947 ObjCIvarDecl::AccessControl ac = 16948 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16949 : ObjCIvarDecl::None; 16950 // Must set ivar's DeclContext to its enclosing interface. 16951 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16952 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16953 return nullptr; 16954 ObjCContainerDecl *EnclosingContext; 16955 if (ObjCImplementationDecl *IMPDecl = 16956 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16957 if (LangOpts.ObjCRuntime.isFragile()) { 16958 // Case of ivar declared in an implementation. Context is that of its class. 16959 EnclosingContext = IMPDecl->getClassInterface(); 16960 assert(EnclosingContext && "Implementation has no class interface!"); 16961 } 16962 else 16963 EnclosingContext = EnclosingDecl; 16964 } else { 16965 if (ObjCCategoryDecl *CDecl = 16966 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16967 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16968 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16969 return nullptr; 16970 } 16971 } 16972 EnclosingContext = EnclosingDecl; 16973 } 16974 16975 // Construct the decl. 16976 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16977 DeclStart, Loc, II, T, 16978 TInfo, ac, (Expr *)BitfieldWidth); 16979 16980 if (II) { 16981 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16982 ForVisibleRedeclaration); 16983 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16984 && !isa<TagDecl>(PrevDecl)) { 16985 Diag(Loc, diag::err_duplicate_member) << II; 16986 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16987 NewID->setInvalidDecl(); 16988 } 16989 } 16990 16991 // Process attributes attached to the ivar. 16992 ProcessDeclAttributes(S, NewID, D); 16993 16994 if (D.isInvalidType()) 16995 NewID->setInvalidDecl(); 16996 16997 // In ARC, infer 'retaining' for ivars of retainable type. 16998 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16999 NewID->setInvalidDecl(); 17000 17001 if (D.getDeclSpec().isModulePrivateSpecified()) 17002 NewID->setModulePrivate(); 17003 17004 if (II) { 17005 // FIXME: When interfaces are DeclContexts, we'll need to add 17006 // these to the interface. 17007 S->AddDecl(NewID); 17008 IdResolver.AddDecl(NewID); 17009 } 17010 17011 if (LangOpts.ObjCRuntime.isNonFragile() && 17012 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17013 Diag(Loc, diag::warn_ivars_in_interface); 17014 17015 return NewID; 17016 } 17017 17018 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17019 /// class and class extensions. For every class \@interface and class 17020 /// extension \@interface, if the last ivar is a bitfield of any type, 17021 /// then add an implicit `char :0` ivar to the end of that interface. 17022 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17023 SmallVectorImpl<Decl *> &AllIvarDecls) { 17024 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17025 return; 17026 17027 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17028 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17029 17030 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17031 return; 17032 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17033 if (!ID) { 17034 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17035 if (!CD->IsClassExtension()) 17036 return; 17037 } 17038 // No need to add this to end of @implementation. 17039 else 17040 return; 17041 } 17042 // All conditions are met. Add a new bitfield to the tail end of ivars. 17043 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17044 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17045 17046 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17047 DeclLoc, DeclLoc, nullptr, 17048 Context.CharTy, 17049 Context.getTrivialTypeSourceInfo(Context.CharTy, 17050 DeclLoc), 17051 ObjCIvarDecl::Private, BW, 17052 true); 17053 AllIvarDecls.push_back(Ivar); 17054 } 17055 17056 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17057 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17058 SourceLocation RBrac, 17059 const ParsedAttributesView &Attrs) { 17060 assert(EnclosingDecl && "missing record or interface decl"); 17061 17062 // If this is an Objective-C @implementation or category and we have 17063 // new fields here we should reset the layout of the interface since 17064 // it will now change. 17065 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17066 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17067 switch (DC->getKind()) { 17068 default: break; 17069 case Decl::ObjCCategory: 17070 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17071 break; 17072 case Decl::ObjCImplementation: 17073 Context. 17074 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17075 break; 17076 } 17077 } 17078 17079 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17080 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17081 17082 // Start counting up the number of named members; make sure to include 17083 // members of anonymous structs and unions in the total. 17084 unsigned NumNamedMembers = 0; 17085 if (Record) { 17086 for (const auto *I : Record->decls()) { 17087 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17088 if (IFD->getDeclName()) 17089 ++NumNamedMembers; 17090 } 17091 } 17092 17093 // Verify that all the fields are okay. 17094 SmallVector<FieldDecl*, 32> RecFields; 17095 17096 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17097 i != end; ++i) { 17098 FieldDecl *FD = cast<FieldDecl>(*i); 17099 17100 // Get the type for the field. 17101 const Type *FDTy = FD->getType().getTypePtr(); 17102 17103 if (!FD->isAnonymousStructOrUnion()) { 17104 // Remember all fields written by the user. 17105 RecFields.push_back(FD); 17106 } 17107 17108 // If the field is already invalid for some reason, don't emit more 17109 // diagnostics about it. 17110 if (FD->isInvalidDecl()) { 17111 EnclosingDecl->setInvalidDecl(); 17112 continue; 17113 } 17114 17115 // C99 6.7.2.1p2: 17116 // A structure or union shall not contain a member with 17117 // incomplete or function type (hence, a structure shall not 17118 // contain an instance of itself, but may contain a pointer to 17119 // an instance of itself), except that the last member of a 17120 // structure with more than one named member may have incomplete 17121 // array type; such a structure (and any union containing, 17122 // possibly recursively, a member that is such a structure) 17123 // shall not be a member of a structure or an element of an 17124 // array. 17125 bool IsLastField = (i + 1 == Fields.end()); 17126 if (FDTy->isFunctionType()) { 17127 // Field declared as a function. 17128 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17129 << FD->getDeclName(); 17130 FD->setInvalidDecl(); 17131 EnclosingDecl->setInvalidDecl(); 17132 continue; 17133 } else if (FDTy->isIncompleteArrayType() && 17134 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17135 if (Record) { 17136 // Flexible array member. 17137 // Microsoft and g++ is more permissive regarding flexible array. 17138 // It will accept flexible array in union and also 17139 // as the sole element of a struct/class. 17140 unsigned DiagID = 0; 17141 if (!Record->isUnion() && !IsLastField) { 17142 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17143 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17144 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17145 FD->setInvalidDecl(); 17146 EnclosingDecl->setInvalidDecl(); 17147 continue; 17148 } else if (Record->isUnion()) 17149 DiagID = getLangOpts().MicrosoftExt 17150 ? diag::ext_flexible_array_union_ms 17151 : getLangOpts().CPlusPlus 17152 ? diag::ext_flexible_array_union_gnu 17153 : diag::err_flexible_array_union; 17154 else if (NumNamedMembers < 1) 17155 DiagID = getLangOpts().MicrosoftExt 17156 ? diag::ext_flexible_array_empty_aggregate_ms 17157 : getLangOpts().CPlusPlus 17158 ? diag::ext_flexible_array_empty_aggregate_gnu 17159 : diag::err_flexible_array_empty_aggregate; 17160 17161 if (DiagID) 17162 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17163 << Record->getTagKind(); 17164 // While the layout of types that contain virtual bases is not specified 17165 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17166 // virtual bases after the derived members. This would make a flexible 17167 // array member declared at the end of an object not adjacent to the end 17168 // of the type. 17169 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17170 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17171 << FD->getDeclName() << Record->getTagKind(); 17172 if (!getLangOpts().C99) 17173 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17174 << FD->getDeclName() << Record->getTagKind(); 17175 17176 // If the element type has a non-trivial destructor, we would not 17177 // implicitly destroy the elements, so disallow it for now. 17178 // 17179 // FIXME: GCC allows this. We should probably either implicitly delete 17180 // the destructor of the containing class, or just allow this. 17181 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17182 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17183 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17184 << FD->getDeclName() << FD->getType(); 17185 FD->setInvalidDecl(); 17186 EnclosingDecl->setInvalidDecl(); 17187 continue; 17188 } 17189 // Okay, we have a legal flexible array member at the end of the struct. 17190 Record->setHasFlexibleArrayMember(true); 17191 } else { 17192 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17193 // unless they are followed by another ivar. That check is done 17194 // elsewhere, after synthesized ivars are known. 17195 } 17196 } else if (!FDTy->isDependentType() && 17197 RequireCompleteSizedType( 17198 FD->getLocation(), FD->getType(), 17199 diag::err_field_incomplete_or_sizeless)) { 17200 // Incomplete type 17201 FD->setInvalidDecl(); 17202 EnclosingDecl->setInvalidDecl(); 17203 continue; 17204 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17205 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17206 // A type which contains a flexible array member is considered to be a 17207 // flexible array member. 17208 Record->setHasFlexibleArrayMember(true); 17209 if (!Record->isUnion()) { 17210 // If this is a struct/class and this is not the last element, reject 17211 // it. Note that GCC supports variable sized arrays in the middle of 17212 // structures. 17213 if (!IsLastField) 17214 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17215 << FD->getDeclName() << FD->getType(); 17216 else { 17217 // We support flexible arrays at the end of structs in 17218 // other structs as an extension. 17219 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17220 << FD->getDeclName(); 17221 } 17222 } 17223 } 17224 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17225 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17226 diag::err_abstract_type_in_decl, 17227 AbstractIvarType)) { 17228 // Ivars can not have abstract class types 17229 FD->setInvalidDecl(); 17230 } 17231 if (Record && FDTTy->getDecl()->hasObjectMember()) 17232 Record->setHasObjectMember(true); 17233 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17234 Record->setHasVolatileMember(true); 17235 } else if (FDTy->isObjCObjectType()) { 17236 /// A field cannot be an Objective-c object 17237 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17238 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17239 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17240 FD->setType(T); 17241 } else if (Record && Record->isUnion() && 17242 FD->getType().hasNonTrivialObjCLifetime() && 17243 getSourceManager().isInSystemHeader(FD->getLocation()) && 17244 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17245 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17246 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17247 // For backward compatibility, fields of C unions declared in system 17248 // headers that have non-trivial ObjC ownership qualifications are marked 17249 // as unavailable unless the qualifier is explicit and __strong. This can 17250 // break ABI compatibility between programs compiled with ARC and MRR, but 17251 // is a better option than rejecting programs using those unions under 17252 // ARC. 17253 FD->addAttr(UnavailableAttr::CreateImplicit( 17254 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17255 FD->getLocation())); 17256 } else if (getLangOpts().ObjC && 17257 getLangOpts().getGC() != LangOptions::NonGC && Record && 17258 !Record->hasObjectMember()) { 17259 if (FD->getType()->isObjCObjectPointerType() || 17260 FD->getType().isObjCGCStrong()) 17261 Record->setHasObjectMember(true); 17262 else if (Context.getAsArrayType(FD->getType())) { 17263 QualType BaseType = Context.getBaseElementType(FD->getType()); 17264 if (BaseType->isRecordType() && 17265 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17266 Record->setHasObjectMember(true); 17267 else if (BaseType->isObjCObjectPointerType() || 17268 BaseType.isObjCGCStrong()) 17269 Record->setHasObjectMember(true); 17270 } 17271 } 17272 17273 if (Record && !getLangOpts().CPlusPlus && 17274 !shouldIgnoreForRecordTriviality(FD)) { 17275 QualType FT = FD->getType(); 17276 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17277 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17278 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17279 Record->isUnion()) 17280 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17281 } 17282 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17283 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17284 Record->setNonTrivialToPrimitiveCopy(true); 17285 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17286 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17287 } 17288 if (FT.isDestructedType()) { 17289 Record->setNonTrivialToPrimitiveDestroy(true); 17290 Record->setParamDestroyedInCallee(true); 17291 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17292 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17293 } 17294 17295 if (const auto *RT = FT->getAs<RecordType>()) { 17296 if (RT->getDecl()->getArgPassingRestrictions() == 17297 RecordDecl::APK_CanNeverPassInRegs) 17298 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17299 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17300 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17301 } 17302 17303 if (Record && FD->getType().isVolatileQualified()) 17304 Record->setHasVolatileMember(true); 17305 // Keep track of the number of named members. 17306 if (FD->getIdentifier()) 17307 ++NumNamedMembers; 17308 } 17309 17310 // Okay, we successfully defined 'Record'. 17311 if (Record) { 17312 bool Completed = false; 17313 if (CXXRecord) { 17314 if (!CXXRecord->isInvalidDecl()) { 17315 // Set access bits correctly on the directly-declared conversions. 17316 for (CXXRecordDecl::conversion_iterator 17317 I = CXXRecord->conversion_begin(), 17318 E = CXXRecord->conversion_end(); I != E; ++I) 17319 I.setAccess((*I)->getAccess()); 17320 } 17321 17322 // Add any implicitly-declared members to this class. 17323 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17324 17325 if (!CXXRecord->isDependentType()) { 17326 if (!CXXRecord->isInvalidDecl()) { 17327 // If we have virtual base classes, we may end up finding multiple 17328 // final overriders for a given virtual function. Check for this 17329 // problem now. 17330 if (CXXRecord->getNumVBases()) { 17331 CXXFinalOverriderMap FinalOverriders; 17332 CXXRecord->getFinalOverriders(FinalOverriders); 17333 17334 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17335 MEnd = FinalOverriders.end(); 17336 M != MEnd; ++M) { 17337 for (OverridingMethods::iterator SO = M->second.begin(), 17338 SOEnd = M->second.end(); 17339 SO != SOEnd; ++SO) { 17340 assert(SO->second.size() > 0 && 17341 "Virtual function without overriding functions?"); 17342 if (SO->second.size() == 1) 17343 continue; 17344 17345 // C++ [class.virtual]p2: 17346 // In a derived class, if a virtual member function of a base 17347 // class subobject has more than one final overrider the 17348 // program is ill-formed. 17349 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17350 << (const NamedDecl *)M->first << Record; 17351 Diag(M->first->getLocation(), 17352 diag::note_overridden_virtual_function); 17353 for (OverridingMethods::overriding_iterator 17354 OM = SO->second.begin(), 17355 OMEnd = SO->second.end(); 17356 OM != OMEnd; ++OM) 17357 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17358 << (const NamedDecl *)M->first << OM->Method->getParent(); 17359 17360 Record->setInvalidDecl(); 17361 } 17362 } 17363 CXXRecord->completeDefinition(&FinalOverriders); 17364 Completed = true; 17365 } 17366 } 17367 } 17368 } 17369 17370 if (!Completed) 17371 Record->completeDefinition(); 17372 17373 // Handle attributes before checking the layout. 17374 ProcessDeclAttributeList(S, Record, Attrs); 17375 17376 // We may have deferred checking for a deleted destructor. Check now. 17377 if (CXXRecord) { 17378 auto *Dtor = CXXRecord->getDestructor(); 17379 if (Dtor && Dtor->isImplicit() && 17380 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17381 CXXRecord->setImplicitDestructorIsDeleted(); 17382 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17383 } 17384 } 17385 17386 if (Record->hasAttrs()) { 17387 CheckAlignasUnderalignment(Record); 17388 17389 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17390 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17391 IA->getRange(), IA->getBestCase(), 17392 IA->getInheritanceModel()); 17393 } 17394 17395 // Check if the structure/union declaration is a type that can have zero 17396 // size in C. For C this is a language extension, for C++ it may cause 17397 // compatibility problems. 17398 bool CheckForZeroSize; 17399 if (!getLangOpts().CPlusPlus) { 17400 CheckForZeroSize = true; 17401 } else { 17402 // For C++ filter out types that cannot be referenced in C code. 17403 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17404 CheckForZeroSize = 17405 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17406 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17407 CXXRecord->isCLike(); 17408 } 17409 if (CheckForZeroSize) { 17410 bool ZeroSize = true; 17411 bool IsEmpty = true; 17412 unsigned NonBitFields = 0; 17413 for (RecordDecl::field_iterator I = Record->field_begin(), 17414 E = Record->field_end(); 17415 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17416 IsEmpty = false; 17417 if (I->isUnnamedBitfield()) { 17418 if (!I->isZeroLengthBitField(Context)) 17419 ZeroSize = false; 17420 } else { 17421 ++NonBitFields; 17422 QualType FieldType = I->getType(); 17423 if (FieldType->isIncompleteType() || 17424 !Context.getTypeSizeInChars(FieldType).isZero()) 17425 ZeroSize = false; 17426 } 17427 } 17428 17429 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17430 // allowed in C++, but warn if its declaration is inside 17431 // extern "C" block. 17432 if (ZeroSize) { 17433 Diag(RecLoc, getLangOpts().CPlusPlus ? 17434 diag::warn_zero_size_struct_union_in_extern_c : 17435 diag::warn_zero_size_struct_union_compat) 17436 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17437 } 17438 17439 // Structs without named members are extension in C (C99 6.7.2.1p7), 17440 // but are accepted by GCC. 17441 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17442 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17443 diag::ext_no_named_members_in_struct_union) 17444 << Record->isUnion(); 17445 } 17446 } 17447 } else { 17448 ObjCIvarDecl **ClsFields = 17449 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17450 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17451 ID->setEndOfDefinitionLoc(RBrac); 17452 // Add ivar's to class's DeclContext. 17453 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17454 ClsFields[i]->setLexicalDeclContext(ID); 17455 ID->addDecl(ClsFields[i]); 17456 } 17457 // Must enforce the rule that ivars in the base classes may not be 17458 // duplicates. 17459 if (ID->getSuperClass()) 17460 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17461 } else if (ObjCImplementationDecl *IMPDecl = 17462 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17463 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17464 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17465 // Ivar declared in @implementation never belongs to the implementation. 17466 // Only it is in implementation's lexical context. 17467 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17468 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17469 IMPDecl->setIvarLBraceLoc(LBrac); 17470 IMPDecl->setIvarRBraceLoc(RBrac); 17471 } else if (ObjCCategoryDecl *CDecl = 17472 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17473 // case of ivars in class extension; all other cases have been 17474 // reported as errors elsewhere. 17475 // FIXME. Class extension does not have a LocEnd field. 17476 // CDecl->setLocEnd(RBrac); 17477 // Add ivar's to class extension's DeclContext. 17478 // Diagnose redeclaration of private ivars. 17479 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17480 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17481 if (IDecl) { 17482 if (const ObjCIvarDecl *ClsIvar = 17483 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17484 Diag(ClsFields[i]->getLocation(), 17485 diag::err_duplicate_ivar_declaration); 17486 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17487 continue; 17488 } 17489 for (const auto *Ext : IDecl->known_extensions()) { 17490 if (const ObjCIvarDecl *ClsExtIvar 17491 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17492 Diag(ClsFields[i]->getLocation(), 17493 diag::err_duplicate_ivar_declaration); 17494 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17495 continue; 17496 } 17497 } 17498 } 17499 ClsFields[i]->setLexicalDeclContext(CDecl); 17500 CDecl->addDecl(ClsFields[i]); 17501 } 17502 CDecl->setIvarLBraceLoc(LBrac); 17503 CDecl->setIvarRBraceLoc(RBrac); 17504 } 17505 } 17506 } 17507 17508 /// Determine whether the given integral value is representable within 17509 /// the given type T. 17510 static bool isRepresentableIntegerValue(ASTContext &Context, 17511 llvm::APSInt &Value, 17512 QualType T) { 17513 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17514 "Integral type required!"); 17515 unsigned BitWidth = Context.getIntWidth(T); 17516 17517 if (Value.isUnsigned() || Value.isNonNegative()) { 17518 if (T->isSignedIntegerOrEnumerationType()) 17519 --BitWidth; 17520 return Value.getActiveBits() <= BitWidth; 17521 } 17522 return Value.getMinSignedBits() <= BitWidth; 17523 } 17524 17525 // Given an integral type, return the next larger integral type 17526 // (or a NULL type of no such type exists). 17527 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17528 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17529 // enum checking below. 17530 assert((T->isIntegralType(Context) || 17531 T->isEnumeralType()) && "Integral type required!"); 17532 const unsigned NumTypes = 4; 17533 QualType SignedIntegralTypes[NumTypes] = { 17534 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17535 }; 17536 QualType UnsignedIntegralTypes[NumTypes] = { 17537 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17538 Context.UnsignedLongLongTy 17539 }; 17540 17541 unsigned BitWidth = Context.getTypeSize(T); 17542 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17543 : UnsignedIntegralTypes; 17544 for (unsigned I = 0; I != NumTypes; ++I) 17545 if (Context.getTypeSize(Types[I]) > BitWidth) 17546 return Types[I]; 17547 17548 return QualType(); 17549 } 17550 17551 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17552 EnumConstantDecl *LastEnumConst, 17553 SourceLocation IdLoc, 17554 IdentifierInfo *Id, 17555 Expr *Val) { 17556 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17557 llvm::APSInt EnumVal(IntWidth); 17558 QualType EltTy; 17559 17560 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17561 Val = nullptr; 17562 17563 if (Val) 17564 Val = DefaultLvalueConversion(Val).get(); 17565 17566 if (Val) { 17567 if (Enum->isDependentType() || Val->isTypeDependent()) 17568 EltTy = Context.DependentTy; 17569 else { 17570 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17571 // underlying type, but do allow it in all other contexts. 17572 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17573 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17574 // constant-expression in the enumerator-definition shall be a converted 17575 // constant expression of the underlying type. 17576 EltTy = Enum->getIntegerType(); 17577 ExprResult Converted = 17578 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17579 CCEK_Enumerator); 17580 if (Converted.isInvalid()) 17581 Val = nullptr; 17582 else 17583 Val = Converted.get(); 17584 } else if (!Val->isValueDependent() && 17585 !(Val = 17586 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17587 .get())) { 17588 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17589 } else { 17590 if (Enum->isComplete()) { 17591 EltTy = Enum->getIntegerType(); 17592 17593 // In Obj-C and Microsoft mode, require the enumeration value to be 17594 // representable in the underlying type of the enumeration. In C++11, 17595 // we perform a non-narrowing conversion as part of converted constant 17596 // expression checking. 17597 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17598 if (Context.getTargetInfo() 17599 .getTriple() 17600 .isWindowsMSVCEnvironment()) { 17601 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17602 } else { 17603 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17604 } 17605 } 17606 17607 // Cast to the underlying type. 17608 Val = ImpCastExprToType(Val, EltTy, 17609 EltTy->isBooleanType() ? CK_IntegralToBoolean 17610 : CK_IntegralCast) 17611 .get(); 17612 } else if (getLangOpts().CPlusPlus) { 17613 // C++11 [dcl.enum]p5: 17614 // If the underlying type is not fixed, the type of each enumerator 17615 // is the type of its initializing value: 17616 // - If an initializer is specified for an enumerator, the 17617 // initializing value has the same type as the expression. 17618 EltTy = Val->getType(); 17619 } else { 17620 // C99 6.7.2.2p2: 17621 // The expression that defines the value of an enumeration constant 17622 // shall be an integer constant expression that has a value 17623 // representable as an int. 17624 17625 // Complain if the value is not representable in an int. 17626 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17627 Diag(IdLoc, diag::ext_enum_value_not_int) 17628 << EnumVal.toString(10) << Val->getSourceRange() 17629 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17630 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17631 // Force the type of the expression to 'int'. 17632 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17633 } 17634 EltTy = Val->getType(); 17635 } 17636 } 17637 } 17638 } 17639 17640 if (!Val) { 17641 if (Enum->isDependentType()) 17642 EltTy = Context.DependentTy; 17643 else if (!LastEnumConst) { 17644 // C++0x [dcl.enum]p5: 17645 // If the underlying type is not fixed, the type of each enumerator 17646 // is the type of its initializing value: 17647 // - If no initializer is specified for the first enumerator, the 17648 // initializing value has an unspecified integral type. 17649 // 17650 // GCC uses 'int' for its unspecified integral type, as does 17651 // C99 6.7.2.2p3. 17652 if (Enum->isFixed()) { 17653 EltTy = Enum->getIntegerType(); 17654 } 17655 else { 17656 EltTy = Context.IntTy; 17657 } 17658 } else { 17659 // Assign the last value + 1. 17660 EnumVal = LastEnumConst->getInitVal(); 17661 ++EnumVal; 17662 EltTy = LastEnumConst->getType(); 17663 17664 // Check for overflow on increment. 17665 if (EnumVal < LastEnumConst->getInitVal()) { 17666 // C++0x [dcl.enum]p5: 17667 // If the underlying type is not fixed, the type of each enumerator 17668 // is the type of its initializing value: 17669 // 17670 // - Otherwise the type of the initializing value is the same as 17671 // the type of the initializing value of the preceding enumerator 17672 // unless the incremented value is not representable in that type, 17673 // in which case the type is an unspecified integral type 17674 // sufficient to contain the incremented value. If no such type 17675 // exists, the program is ill-formed. 17676 QualType T = getNextLargerIntegralType(Context, EltTy); 17677 if (T.isNull() || Enum->isFixed()) { 17678 // There is no integral type larger enough to represent this 17679 // value. Complain, then allow the value to wrap around. 17680 EnumVal = LastEnumConst->getInitVal(); 17681 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17682 ++EnumVal; 17683 if (Enum->isFixed()) 17684 // When the underlying type is fixed, this is ill-formed. 17685 Diag(IdLoc, diag::err_enumerator_wrapped) 17686 << EnumVal.toString(10) 17687 << EltTy; 17688 else 17689 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17690 << EnumVal.toString(10); 17691 } else { 17692 EltTy = T; 17693 } 17694 17695 // Retrieve the last enumerator's value, extent that type to the 17696 // type that is supposed to be large enough to represent the incremented 17697 // value, then increment. 17698 EnumVal = LastEnumConst->getInitVal(); 17699 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17700 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17701 ++EnumVal; 17702 17703 // If we're not in C++, diagnose the overflow of enumerator values, 17704 // which in C99 means that the enumerator value is not representable in 17705 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17706 // permits enumerator values that are representable in some larger 17707 // integral type. 17708 if (!getLangOpts().CPlusPlus && !T.isNull()) 17709 Diag(IdLoc, diag::warn_enum_value_overflow); 17710 } else if (!getLangOpts().CPlusPlus && 17711 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17712 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17713 Diag(IdLoc, diag::ext_enum_value_not_int) 17714 << EnumVal.toString(10) << 1; 17715 } 17716 } 17717 } 17718 17719 if (!EltTy->isDependentType()) { 17720 // Make the enumerator value match the signedness and size of the 17721 // enumerator's type. 17722 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17723 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17724 } 17725 17726 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17727 Val, EnumVal); 17728 } 17729 17730 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17731 SourceLocation IILoc) { 17732 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17733 !getLangOpts().CPlusPlus) 17734 return SkipBodyInfo(); 17735 17736 // We have an anonymous enum definition. Look up the first enumerator to 17737 // determine if we should merge the definition with an existing one and 17738 // skip the body. 17739 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17740 forRedeclarationInCurContext()); 17741 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17742 if (!PrevECD) 17743 return SkipBodyInfo(); 17744 17745 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17746 NamedDecl *Hidden; 17747 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17748 SkipBodyInfo Skip; 17749 Skip.Previous = Hidden; 17750 return Skip; 17751 } 17752 17753 return SkipBodyInfo(); 17754 } 17755 17756 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17757 SourceLocation IdLoc, IdentifierInfo *Id, 17758 const ParsedAttributesView &Attrs, 17759 SourceLocation EqualLoc, Expr *Val) { 17760 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17761 EnumConstantDecl *LastEnumConst = 17762 cast_or_null<EnumConstantDecl>(lastEnumConst); 17763 17764 // The scope passed in may not be a decl scope. Zip up the scope tree until 17765 // we find one that is. 17766 S = getNonFieldDeclScope(S); 17767 17768 // Verify that there isn't already something declared with this name in this 17769 // scope. 17770 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17771 LookupName(R, S); 17772 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17773 17774 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17775 // Maybe we will complain about the shadowed template parameter. 17776 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17777 // Just pretend that we didn't see the previous declaration. 17778 PrevDecl = nullptr; 17779 } 17780 17781 // C++ [class.mem]p15: 17782 // If T is the name of a class, then each of the following shall have a name 17783 // different from T: 17784 // - every enumerator of every member of class T that is an unscoped 17785 // enumerated type 17786 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17787 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17788 DeclarationNameInfo(Id, IdLoc)); 17789 17790 EnumConstantDecl *New = 17791 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17792 if (!New) 17793 return nullptr; 17794 17795 if (PrevDecl) { 17796 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17797 // Check for other kinds of shadowing not already handled. 17798 CheckShadow(New, PrevDecl, R); 17799 } 17800 17801 // When in C++, we may get a TagDecl with the same name; in this case the 17802 // enum constant will 'hide' the tag. 17803 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17804 "Received TagDecl when not in C++!"); 17805 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17806 if (isa<EnumConstantDecl>(PrevDecl)) 17807 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17808 else 17809 Diag(IdLoc, diag::err_redefinition) << Id; 17810 notePreviousDefinition(PrevDecl, IdLoc); 17811 return nullptr; 17812 } 17813 } 17814 17815 // Process attributes. 17816 ProcessDeclAttributeList(S, New, Attrs); 17817 AddPragmaAttributes(S, New); 17818 17819 // Register this decl in the current scope stack. 17820 New->setAccess(TheEnumDecl->getAccess()); 17821 PushOnScopeChains(New, S); 17822 17823 ActOnDocumentableDecl(New); 17824 17825 return New; 17826 } 17827 17828 // Returns true when the enum initial expression does not trigger the 17829 // duplicate enum warning. A few common cases are exempted as follows: 17830 // Element2 = Element1 17831 // Element2 = Element1 + 1 17832 // Element2 = Element1 - 1 17833 // Where Element2 and Element1 are from the same enum. 17834 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17835 Expr *InitExpr = ECD->getInitExpr(); 17836 if (!InitExpr) 17837 return true; 17838 InitExpr = InitExpr->IgnoreImpCasts(); 17839 17840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17841 if (!BO->isAdditiveOp()) 17842 return true; 17843 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17844 if (!IL) 17845 return true; 17846 if (IL->getValue() != 1) 17847 return true; 17848 17849 InitExpr = BO->getLHS(); 17850 } 17851 17852 // This checks if the elements are from the same enum. 17853 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17854 if (!DRE) 17855 return true; 17856 17857 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17858 if (!EnumConstant) 17859 return true; 17860 17861 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17862 Enum) 17863 return true; 17864 17865 return false; 17866 } 17867 17868 // Emits a warning when an element is implicitly set a value that 17869 // a previous element has already been set to. 17870 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17871 EnumDecl *Enum, QualType EnumType) { 17872 // Avoid anonymous enums 17873 if (!Enum->getIdentifier()) 17874 return; 17875 17876 // Only check for small enums. 17877 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17878 return; 17879 17880 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17881 return; 17882 17883 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17884 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17885 17886 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17887 17888 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17889 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17890 17891 // Use int64_t as a key to avoid needing special handling for map keys. 17892 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17893 llvm::APSInt Val = D->getInitVal(); 17894 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17895 }; 17896 17897 DuplicatesVector DupVector; 17898 ValueToVectorMap EnumMap; 17899 17900 // Populate the EnumMap with all values represented by enum constants without 17901 // an initializer. 17902 for (auto *Element : Elements) { 17903 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17904 17905 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17906 // this constant. Skip this enum since it may be ill-formed. 17907 if (!ECD) { 17908 return; 17909 } 17910 17911 // Constants with initalizers are handled in the next loop. 17912 if (ECD->getInitExpr()) 17913 continue; 17914 17915 // Duplicate values are handled in the next loop. 17916 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17917 } 17918 17919 if (EnumMap.size() == 0) 17920 return; 17921 17922 // Create vectors for any values that has duplicates. 17923 for (auto *Element : Elements) { 17924 // The last loop returned if any constant was null. 17925 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17926 if (!ValidDuplicateEnum(ECD, Enum)) 17927 continue; 17928 17929 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17930 if (Iter == EnumMap.end()) 17931 continue; 17932 17933 DeclOrVector& Entry = Iter->second; 17934 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17935 // Ensure constants are different. 17936 if (D == ECD) 17937 continue; 17938 17939 // Create new vector and push values onto it. 17940 auto Vec = std::make_unique<ECDVector>(); 17941 Vec->push_back(D); 17942 Vec->push_back(ECD); 17943 17944 // Update entry to point to the duplicates vector. 17945 Entry = Vec.get(); 17946 17947 // Store the vector somewhere we can consult later for quick emission of 17948 // diagnostics. 17949 DupVector.emplace_back(std::move(Vec)); 17950 continue; 17951 } 17952 17953 ECDVector *Vec = Entry.get<ECDVector*>(); 17954 // Make sure constants are not added more than once. 17955 if (*Vec->begin() == ECD) 17956 continue; 17957 17958 Vec->push_back(ECD); 17959 } 17960 17961 // Emit diagnostics. 17962 for (const auto &Vec : DupVector) { 17963 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17964 17965 // Emit warning for one enum constant. 17966 auto *FirstECD = Vec->front(); 17967 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17968 << FirstECD << FirstECD->getInitVal().toString(10) 17969 << FirstECD->getSourceRange(); 17970 17971 // Emit one note for each of the remaining enum constants with 17972 // the same value. 17973 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17974 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17975 << ECD << ECD->getInitVal().toString(10) 17976 << ECD->getSourceRange(); 17977 } 17978 } 17979 17980 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17981 bool AllowMask) const { 17982 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17983 assert(ED->isCompleteDefinition() && "expected enum definition"); 17984 17985 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17986 llvm::APInt &FlagBits = R.first->second; 17987 17988 if (R.second) { 17989 for (auto *E : ED->enumerators()) { 17990 const auto &EVal = E->getInitVal(); 17991 // Only single-bit enumerators introduce new flag values. 17992 if (EVal.isPowerOf2()) 17993 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17994 } 17995 } 17996 17997 // A value is in a flag enum if either its bits are a subset of the enum's 17998 // flag bits (the first condition) or we are allowing masks and the same is 17999 // true of its complement (the second condition). When masks are allowed, we 18000 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18001 // 18002 // While it's true that any value could be used as a mask, the assumption is 18003 // that a mask will have all of the insignificant bits set. Anything else is 18004 // likely a logic error. 18005 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18006 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18007 } 18008 18009 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18010 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18011 const ParsedAttributesView &Attrs) { 18012 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18013 QualType EnumType = Context.getTypeDeclType(Enum); 18014 18015 ProcessDeclAttributeList(S, Enum, Attrs); 18016 18017 if (Enum->isDependentType()) { 18018 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18019 EnumConstantDecl *ECD = 18020 cast_or_null<EnumConstantDecl>(Elements[i]); 18021 if (!ECD) continue; 18022 18023 ECD->setType(EnumType); 18024 } 18025 18026 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18027 return; 18028 } 18029 18030 // TODO: If the result value doesn't fit in an int, it must be a long or long 18031 // long value. ISO C does not support this, but GCC does as an extension, 18032 // emit a warning. 18033 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18034 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18035 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18036 18037 // Verify that all the values are okay, compute the size of the values, and 18038 // reverse the list. 18039 unsigned NumNegativeBits = 0; 18040 unsigned NumPositiveBits = 0; 18041 18042 // Keep track of whether all elements have type int. 18043 bool AllElementsInt = true; 18044 18045 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18046 EnumConstantDecl *ECD = 18047 cast_or_null<EnumConstantDecl>(Elements[i]); 18048 if (!ECD) continue; // Already issued a diagnostic. 18049 18050 const llvm::APSInt &InitVal = ECD->getInitVal(); 18051 18052 // Keep track of the size of positive and negative values. 18053 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18054 NumPositiveBits = std::max(NumPositiveBits, 18055 (unsigned)InitVal.getActiveBits()); 18056 else 18057 NumNegativeBits = std::max(NumNegativeBits, 18058 (unsigned)InitVal.getMinSignedBits()); 18059 18060 // Keep track of whether every enum element has type int (very common). 18061 if (AllElementsInt) 18062 AllElementsInt = ECD->getType() == Context.IntTy; 18063 } 18064 18065 // Figure out the type that should be used for this enum. 18066 QualType BestType; 18067 unsigned BestWidth; 18068 18069 // C++0x N3000 [conv.prom]p3: 18070 // An rvalue of an unscoped enumeration type whose underlying 18071 // type is not fixed can be converted to an rvalue of the first 18072 // of the following types that can represent all the values of 18073 // the enumeration: int, unsigned int, long int, unsigned long 18074 // int, long long int, or unsigned long long int. 18075 // C99 6.4.4.3p2: 18076 // An identifier declared as an enumeration constant has type int. 18077 // The C99 rule is modified by a gcc extension 18078 QualType BestPromotionType; 18079 18080 bool Packed = Enum->hasAttr<PackedAttr>(); 18081 // -fshort-enums is the equivalent to specifying the packed attribute on all 18082 // enum definitions. 18083 if (LangOpts.ShortEnums) 18084 Packed = true; 18085 18086 // If the enum already has a type because it is fixed or dictated by the 18087 // target, promote that type instead of analyzing the enumerators. 18088 if (Enum->isComplete()) { 18089 BestType = Enum->getIntegerType(); 18090 if (BestType->isPromotableIntegerType()) 18091 BestPromotionType = Context.getPromotedIntegerType(BestType); 18092 else 18093 BestPromotionType = BestType; 18094 18095 BestWidth = Context.getIntWidth(BestType); 18096 } 18097 else if (NumNegativeBits) { 18098 // If there is a negative value, figure out the smallest integer type (of 18099 // int/long/longlong) that fits. 18100 // If it's packed, check also if it fits a char or a short. 18101 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18102 BestType = Context.SignedCharTy; 18103 BestWidth = CharWidth; 18104 } else if (Packed && NumNegativeBits <= ShortWidth && 18105 NumPositiveBits < ShortWidth) { 18106 BestType = Context.ShortTy; 18107 BestWidth = ShortWidth; 18108 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18109 BestType = Context.IntTy; 18110 BestWidth = IntWidth; 18111 } else { 18112 BestWidth = Context.getTargetInfo().getLongWidth(); 18113 18114 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18115 BestType = Context.LongTy; 18116 } else { 18117 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18118 18119 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18120 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18121 BestType = Context.LongLongTy; 18122 } 18123 } 18124 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18125 } else { 18126 // If there is no negative value, figure out the smallest type that fits 18127 // all of the enumerator values. 18128 // If it's packed, check also if it fits a char or a short. 18129 if (Packed && NumPositiveBits <= CharWidth) { 18130 BestType = Context.UnsignedCharTy; 18131 BestPromotionType = Context.IntTy; 18132 BestWidth = CharWidth; 18133 } else if (Packed && NumPositiveBits <= ShortWidth) { 18134 BestType = Context.UnsignedShortTy; 18135 BestPromotionType = Context.IntTy; 18136 BestWidth = ShortWidth; 18137 } else if (NumPositiveBits <= IntWidth) { 18138 BestType = Context.UnsignedIntTy; 18139 BestWidth = IntWidth; 18140 BestPromotionType 18141 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18142 ? Context.UnsignedIntTy : Context.IntTy; 18143 } else if (NumPositiveBits <= 18144 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18145 BestType = Context.UnsignedLongTy; 18146 BestPromotionType 18147 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18148 ? Context.UnsignedLongTy : Context.LongTy; 18149 } else { 18150 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18151 assert(NumPositiveBits <= BestWidth && 18152 "How could an initializer get larger than ULL?"); 18153 BestType = Context.UnsignedLongLongTy; 18154 BestPromotionType 18155 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18156 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18157 } 18158 } 18159 18160 // Loop over all of the enumerator constants, changing their types to match 18161 // the type of the enum if needed. 18162 for (auto *D : Elements) { 18163 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18164 if (!ECD) continue; // Already issued a diagnostic. 18165 18166 // Standard C says the enumerators have int type, but we allow, as an 18167 // extension, the enumerators to be larger than int size. If each 18168 // enumerator value fits in an int, type it as an int, otherwise type it the 18169 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18170 // that X has type 'int', not 'unsigned'. 18171 18172 // Determine whether the value fits into an int. 18173 llvm::APSInt InitVal = ECD->getInitVal(); 18174 18175 // If it fits into an integer type, force it. Otherwise force it to match 18176 // the enum decl type. 18177 QualType NewTy; 18178 unsigned NewWidth; 18179 bool NewSign; 18180 if (!getLangOpts().CPlusPlus && 18181 !Enum->isFixed() && 18182 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18183 NewTy = Context.IntTy; 18184 NewWidth = IntWidth; 18185 NewSign = true; 18186 } else if (ECD->getType() == BestType) { 18187 // Already the right type! 18188 if (getLangOpts().CPlusPlus) 18189 // C++ [dcl.enum]p4: Following the closing brace of an 18190 // enum-specifier, each enumerator has the type of its 18191 // enumeration. 18192 ECD->setType(EnumType); 18193 continue; 18194 } else { 18195 NewTy = BestType; 18196 NewWidth = BestWidth; 18197 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18198 } 18199 18200 // Adjust the APSInt value. 18201 InitVal = InitVal.extOrTrunc(NewWidth); 18202 InitVal.setIsSigned(NewSign); 18203 ECD->setInitVal(InitVal); 18204 18205 // Adjust the Expr initializer and type. 18206 if (ECD->getInitExpr() && 18207 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18208 ECD->setInitExpr(ImplicitCastExpr::Create( 18209 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18210 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18211 if (getLangOpts().CPlusPlus) 18212 // C++ [dcl.enum]p4: Following the closing brace of an 18213 // enum-specifier, each enumerator has the type of its 18214 // enumeration. 18215 ECD->setType(EnumType); 18216 else 18217 ECD->setType(NewTy); 18218 } 18219 18220 Enum->completeDefinition(BestType, BestPromotionType, 18221 NumPositiveBits, NumNegativeBits); 18222 18223 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18224 18225 if (Enum->isClosedFlag()) { 18226 for (Decl *D : Elements) { 18227 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18228 if (!ECD) continue; // Already issued a diagnostic. 18229 18230 llvm::APSInt InitVal = ECD->getInitVal(); 18231 if (InitVal != 0 && !InitVal.isPowerOf2() && 18232 !IsValueInFlagEnum(Enum, InitVal, true)) 18233 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18234 << ECD << Enum; 18235 } 18236 } 18237 18238 // Now that the enum type is defined, ensure it's not been underaligned. 18239 if (Enum->hasAttrs()) 18240 CheckAlignasUnderalignment(Enum); 18241 } 18242 18243 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18244 SourceLocation StartLoc, 18245 SourceLocation EndLoc) { 18246 StringLiteral *AsmString = cast<StringLiteral>(expr); 18247 18248 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18249 AsmString, StartLoc, 18250 EndLoc); 18251 CurContext->addDecl(New); 18252 return New; 18253 } 18254 18255 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18256 IdentifierInfo* AliasName, 18257 SourceLocation PragmaLoc, 18258 SourceLocation NameLoc, 18259 SourceLocation AliasNameLoc) { 18260 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18261 LookupOrdinaryName); 18262 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18263 AttributeCommonInfo::AS_Pragma); 18264 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18265 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18266 18267 // If a declaration that: 18268 // 1) declares a function or a variable 18269 // 2) has external linkage 18270 // already exists, add a label attribute to it. 18271 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18272 if (isDeclExternC(PrevDecl)) 18273 PrevDecl->addAttr(Attr); 18274 else 18275 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18276 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18277 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18278 } else 18279 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18280 } 18281 18282 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18283 SourceLocation PragmaLoc, 18284 SourceLocation NameLoc) { 18285 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18286 18287 if (PrevDecl) { 18288 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18289 } else { 18290 (void)WeakUndeclaredIdentifiers.insert( 18291 std::pair<IdentifierInfo*,WeakInfo> 18292 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18293 } 18294 } 18295 18296 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18297 IdentifierInfo* AliasName, 18298 SourceLocation PragmaLoc, 18299 SourceLocation NameLoc, 18300 SourceLocation AliasNameLoc) { 18301 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18302 LookupOrdinaryName); 18303 WeakInfo W = WeakInfo(Name, NameLoc); 18304 18305 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18306 if (!PrevDecl->hasAttr<AliasAttr>()) 18307 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18308 DeclApplyPragmaWeak(TUScope, ND, W); 18309 } else { 18310 (void)WeakUndeclaredIdentifiers.insert( 18311 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18312 } 18313 } 18314 18315 Decl *Sema::getObjCDeclContext() const { 18316 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18317 } 18318 18319 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18320 bool Final) { 18321 // SYCL functions can be template, so we check if they have appropriate 18322 // attribute prior to checking if it is a template. 18323 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18324 return FunctionEmissionStatus::Emitted; 18325 18326 // Templates are emitted when they're instantiated. 18327 if (FD->isDependentContext()) 18328 return FunctionEmissionStatus::TemplateDiscarded; 18329 18330 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18331 if (LangOpts.OpenMPIsDevice) { 18332 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18333 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18334 if (DevTy.hasValue()) { 18335 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18336 OMPES = FunctionEmissionStatus::OMPDiscarded; 18337 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18338 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18339 OMPES = FunctionEmissionStatus::Emitted; 18340 } 18341 } 18342 } else if (LangOpts.OpenMP) { 18343 // In OpenMP 4.5 all the functions are host functions. 18344 if (LangOpts.OpenMP <= 45) { 18345 OMPES = FunctionEmissionStatus::Emitted; 18346 } else { 18347 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18348 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18349 // In OpenMP 5.0 or above, DevTy may be changed later by 18350 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18351 // having no value does not imply host. The emission status will be 18352 // checked again at the end of compilation unit. 18353 if (DevTy.hasValue()) { 18354 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18355 OMPES = FunctionEmissionStatus::OMPDiscarded; 18356 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18357 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18358 OMPES = FunctionEmissionStatus::Emitted; 18359 } else if (Final) 18360 OMPES = FunctionEmissionStatus::Emitted; 18361 } 18362 } 18363 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18364 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18365 return OMPES; 18366 18367 if (LangOpts.CUDA) { 18368 // When compiling for device, host functions are never emitted. Similarly, 18369 // when compiling for host, device and global functions are never emitted. 18370 // (Technically, we do emit a host-side stub for global functions, but this 18371 // doesn't count for our purposes here.) 18372 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18373 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18374 return FunctionEmissionStatus::CUDADiscarded; 18375 if (!LangOpts.CUDAIsDevice && 18376 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18377 return FunctionEmissionStatus::CUDADiscarded; 18378 18379 // Check whether this function is externally visible -- if so, it's 18380 // known-emitted. 18381 // 18382 // We have to check the GVA linkage of the function's *definition* -- if we 18383 // only have a declaration, we don't know whether or not the function will 18384 // be emitted, because (say) the definition could include "inline". 18385 FunctionDecl *Def = FD->getDefinition(); 18386 18387 if (Def && 18388 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18389 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18390 return FunctionEmissionStatus::Emitted; 18391 } 18392 18393 // Otherwise, the function is known-emitted if it's in our set of 18394 // known-emitted functions. 18395 return FunctionEmissionStatus::Unknown; 18396 } 18397 18398 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18399 // Host-side references to a __global__ function refer to the stub, so the 18400 // function itself is never emitted and therefore should not be marked. 18401 // If we have host fn calls kernel fn calls host+device, the HD function 18402 // does not get instantiated on the host. We model this by omitting at the 18403 // call to the kernel from the callgraph. This ensures that, when compiling 18404 // for host, only HD functions actually called from the host get marked as 18405 // known-emitted. 18406 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18407 IdentifyCUDATarget(Callee) == CFT_Global; 18408 } 18409