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__Float16: 142 case tok::kw___float128: 143 case tok::kw_wchar_t: 144 case tok::kw_bool: 145 case tok::kw___underlying_type: 146 case tok::kw___auto_type: 147 return true; 148 149 case tok::annot_typename: 150 case tok::kw_char16_t: 151 case tok::kw_char32_t: 152 case tok::kw_typeof: 153 case tok::annot_decltype: 154 case tok::kw_decltype: 155 return getLangOpts().CPlusPlus; 156 157 case tok::kw_char8_t: 158 return getLangOpts().Char8; 159 160 default: 161 break; 162 } 163 164 return false; 165 } 166 167 namespace { 168 enum class UnqualifiedTypeNameLookupResult { 169 NotFound, 170 FoundNonType, 171 FoundType 172 }; 173 } // end anonymous namespace 174 175 /// Tries to perform unqualified lookup of the type decls in bases for 176 /// dependent class. 177 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 178 /// type decl, \a FoundType if only type decls are found. 179 static UnqualifiedTypeNameLookupResult 180 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 181 SourceLocation NameLoc, 182 const CXXRecordDecl *RD) { 183 if (!RD->hasDefinition()) 184 return UnqualifiedTypeNameLookupResult::NotFound; 185 // Look for type decls in base classes. 186 UnqualifiedTypeNameLookupResult FoundTypeDecl = 187 UnqualifiedTypeNameLookupResult::NotFound; 188 for (const auto &Base : RD->bases()) { 189 const CXXRecordDecl *BaseRD = nullptr; 190 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 191 BaseRD = BaseTT->getAsCXXRecordDecl(); 192 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 193 // Look for type decls in dependent base classes that have known primary 194 // templates. 195 if (!TST || !TST->isDependentType()) 196 continue; 197 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 198 if (!TD) 199 continue; 200 if (auto *BasePrimaryTemplate = 201 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 202 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 203 BaseRD = BasePrimaryTemplate; 204 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 205 if (const ClassTemplatePartialSpecializationDecl *PS = 206 CTD->findPartialSpecialization(Base.getType())) 207 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 208 BaseRD = PS; 209 } 210 } 211 } 212 if (BaseRD) { 213 for (NamedDecl *ND : BaseRD->lookup(&II)) { 214 if (!isa<TypeDecl>(ND)) 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 217 } 218 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 219 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 220 case UnqualifiedTypeNameLookupResult::FoundNonType: 221 return UnqualifiedTypeNameLookupResult::FoundNonType; 222 case UnqualifiedTypeNameLookupResult::FoundType: 223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 224 break; 225 case UnqualifiedTypeNameLookupResult::NotFound: 226 break; 227 } 228 } 229 } 230 } 231 232 return FoundTypeDecl; 233 } 234 235 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 236 const IdentifierInfo &II, 237 SourceLocation NameLoc) { 238 // Lookup in the parent class template context, if any. 239 const CXXRecordDecl *RD = nullptr; 240 UnqualifiedTypeNameLookupResult FoundTypeDecl = 241 UnqualifiedTypeNameLookupResult::NotFound; 242 for (DeclContext *DC = S.CurContext; 243 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 244 DC = DC->getParent()) { 245 // Look for type decls in dependent base classes that have known primary 246 // templates. 247 RD = dyn_cast<CXXRecordDecl>(DC); 248 if (RD && RD->getDescribedClassTemplate()) 249 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 250 } 251 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 252 return nullptr; 253 254 // We found some types in dependent base classes. Recover as if the user 255 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 256 // lookup during template instantiation. 257 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 258 259 ASTContext &Context = S.Context; 260 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 261 cast<Type>(Context.getRecordType(RD))); 262 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 263 264 CXXScopeSpec SS; 265 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 266 267 TypeLocBuilder Builder; 268 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 269 DepTL.setNameLoc(NameLoc); 270 DepTL.setElaboratedKeywordLoc(SourceLocation()); 271 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 272 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 273 } 274 275 /// If the identifier refers to a type name within this scope, 276 /// return the declaration of that type. 277 /// 278 /// This routine performs ordinary name lookup of the identifier II 279 /// within the given scope, with optional C++ scope specifier SS, to 280 /// determine whether the name refers to a type. If so, returns an 281 /// opaque pointer (actually a QualType) corresponding to that 282 /// type. Otherwise, returns NULL. 283 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 284 Scope *S, CXXScopeSpec *SS, 285 bool isClassName, bool HasTrailingDot, 286 ParsedType ObjectTypePtr, 287 bool IsCtorOrDtorName, 288 bool WantNontrivialTypeSourceInfo, 289 bool IsClassTemplateDeductionContext, 290 IdentifierInfo **CorrectedII) { 291 // FIXME: Consider allowing this outside C++1z mode as an extension. 292 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 293 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 294 !isClassName && !HasTrailingDot; 295 296 // Determine where we will perform name lookup. 297 DeclContext *LookupCtx = nullptr; 298 if (ObjectTypePtr) { 299 QualType ObjectType = ObjectTypePtr.get(); 300 if (ObjectType->isRecordType()) 301 LookupCtx = computeDeclContext(ObjectType); 302 } else if (SS && SS->isNotEmpty()) { 303 LookupCtx = computeDeclContext(*SS, false); 304 305 if (!LookupCtx) { 306 if (isDependentScopeSpecifier(*SS)) { 307 // C++ [temp.res]p3: 308 // A qualified-id that refers to a type and in which the 309 // nested-name-specifier depends on a template-parameter (14.6.2) 310 // shall be prefixed by the keyword typename to indicate that the 311 // qualified-id denotes a type, forming an 312 // elaborated-type-specifier (7.1.5.3). 313 // 314 // We therefore do not perform any name lookup if the result would 315 // refer to a member of an unknown specialization. 316 if (!isClassName && !IsCtorOrDtorName) 317 return nullptr; 318 319 // We know from the grammar that this name refers to a type, 320 // so build a dependent node to describe the type. 321 if (WantNontrivialTypeSourceInfo) 322 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 323 324 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 325 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 326 II, NameLoc); 327 return ParsedType::make(T); 328 } 329 330 return nullptr; 331 } 332 333 if (!LookupCtx->isDependentContext() && 334 RequireCompleteDeclContext(*SS, LookupCtx)) 335 return nullptr; 336 } 337 338 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 339 // lookup for class-names. 340 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 341 LookupOrdinaryName; 342 LookupResult Result(*this, &II, NameLoc, Kind); 343 if (LookupCtx) { 344 // Perform "qualified" name lookup into the declaration context we 345 // computed, which is either the type of the base of a member access 346 // expression or the declaration context associated with a prior 347 // nested-name-specifier. 348 LookupQualifiedName(Result, LookupCtx); 349 350 if (ObjectTypePtr && Result.empty()) { 351 // C++ [basic.lookup.classref]p3: 352 // If the unqualified-id is ~type-name, the type-name is looked up 353 // in the context of the entire postfix-expression. If the type T of 354 // the object expression is of a class type C, the type-name is also 355 // looked up in the scope of class C. At least one of the lookups shall 356 // find a name that refers to (possibly cv-qualified) T. 357 LookupName(Result, S); 358 } 359 } else { 360 // Perform unqualified name lookup. 361 LookupName(Result, S); 362 363 // For unqualified lookup in a class template in MSVC mode, look into 364 // dependent base classes where the primary class template is known. 365 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 366 if (ParsedType TypeInBase = 367 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 368 return TypeInBase; 369 } 370 } 371 372 NamedDecl *IIDecl = nullptr; 373 switch (Result.getResultKind()) { 374 case LookupResult::NotFound: 375 case LookupResult::NotFoundInCurrentInstantiation: 376 if (CorrectedII) { 377 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 378 AllowDeducedTemplate); 379 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 380 S, SS, CCC, CTK_ErrorRecovery); 381 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 382 TemplateTy Template; 383 bool MemberOfUnknownSpecialization; 384 UnqualifiedId TemplateName; 385 TemplateName.setIdentifier(NewII, NameLoc); 386 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 387 CXXScopeSpec NewSS, *NewSSPtr = SS; 388 if (SS && NNS) { 389 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 390 NewSSPtr = &NewSS; 391 } 392 if (Correction && (NNS || NewII != &II) && 393 // Ignore a correction to a template type as the to-be-corrected 394 // identifier is not a template (typo correction for template names 395 // is handled elsewhere). 396 !(getLangOpts().CPlusPlus && NewSSPtr && 397 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 398 Template, MemberOfUnknownSpecialization))) { 399 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 400 isClassName, HasTrailingDot, ObjectTypePtr, 401 IsCtorOrDtorName, 402 WantNontrivialTypeSourceInfo, 403 IsClassTemplateDeductionContext); 404 if (Ty) { 405 diagnoseTypo(Correction, 406 PDiag(diag::err_unknown_type_or_class_name_suggest) 407 << Result.getLookupName() << isClassName); 408 if (SS && NNS) 409 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 410 *CorrectedII = NewII; 411 return Ty; 412 } 413 } 414 } 415 // If typo correction failed or was not performed, fall through 416 LLVM_FALLTHROUGH; 417 case LookupResult::FoundOverloaded: 418 case LookupResult::FoundUnresolvedValue: 419 Result.suppressDiagnostics(); 420 return nullptr; 421 422 case LookupResult::Ambiguous: 423 // Recover from type-hiding ambiguities by hiding the type. We'll 424 // do the lookup again when looking for an object, and we can 425 // diagnose the error then. If we don't do this, then the error 426 // about hiding the type will be immediately followed by an error 427 // that only makes sense if the identifier was treated like a type. 428 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 429 Result.suppressDiagnostics(); 430 return nullptr; 431 } 432 433 // Look to see if we have a type anywhere in the list of results. 434 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 435 Res != ResEnd; ++Res) { 436 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 437 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 438 if (!IIDecl || 439 (*Res)->getLocation().getRawEncoding() < 440 IIDecl->getLocation().getRawEncoding()) 441 IIDecl = *Res; 442 } 443 } 444 445 if (!IIDecl) { 446 // None of the entities we found is a type, so there is no way 447 // to even assume that the result is a type. In this case, don't 448 // complain about the ambiguity. The parser will either try to 449 // perform this lookup again (e.g., as an object name), which 450 // will produce the ambiguity, or will complain that it expected 451 // a type name. 452 Result.suppressDiagnostics(); 453 return nullptr; 454 } 455 456 // We found a type within the ambiguous lookup; diagnose the 457 // ambiguity and then return that type. This might be the right 458 // answer, or it might not be, but it suppresses any attempt to 459 // perform the name lookup again. 460 break; 461 462 case LookupResult::Found: 463 IIDecl = Result.getFoundDecl(); 464 break; 465 } 466 467 assert(IIDecl && "Didn't find decl"); 468 469 QualType T; 470 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 471 // C++ [class.qual]p2: A lookup that would find the injected-class-name 472 // instead names the constructors of the class, except when naming a class. 473 // This is ill-formed when we're not actually forming a ctor or dtor name. 474 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 475 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 476 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 477 FoundRD->isInjectedClassName() && 478 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 479 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 480 << &II << /*Type*/1; 481 482 DiagnoseUseOfDecl(IIDecl, NameLoc); 483 484 T = Context.getTypeDeclType(TD); 485 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 486 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 487 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 488 if (!HasTrailingDot) 489 T = Context.getObjCInterfaceType(IDecl); 490 } else if (AllowDeducedTemplate) { 491 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 492 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 493 QualType(), false); 494 } 495 496 if (T.isNull()) { 497 // If it's not plausibly a type, suppress diagnostics. 498 Result.suppressDiagnostics(); 499 return nullptr; 500 } 501 502 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 503 // constructor or destructor name (in such a case, the scope specifier 504 // will be attached to the enclosing Expr or Decl node). 505 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 506 !isa<ObjCInterfaceDecl>(IIDecl)) { 507 if (WantNontrivialTypeSourceInfo) { 508 // Construct a type with type-source information. 509 TypeLocBuilder Builder; 510 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 511 512 T = getElaboratedType(ETK_None, *SS, T); 513 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 514 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 515 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 516 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 517 } else { 518 T = getElaboratedType(ETK_None, *SS, T); 519 } 520 } 521 522 return ParsedType::make(T); 523 } 524 525 // Builds a fake NNS for the given decl context. 526 static NestedNameSpecifier * 527 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 528 for (;; DC = DC->getLookupParent()) { 529 DC = DC->getPrimaryContext(); 530 auto *ND = dyn_cast<NamespaceDecl>(DC); 531 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 532 return NestedNameSpecifier::Create(Context, nullptr, ND); 533 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 534 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 535 RD->getTypeForDecl()); 536 else if (isa<TranslationUnitDecl>(DC)) 537 return NestedNameSpecifier::GlobalSpecifier(Context); 538 } 539 llvm_unreachable("something isn't in TU scope?"); 540 } 541 542 /// Find the parent class with dependent bases of the innermost enclosing method 543 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 544 /// up allowing unqualified dependent type names at class-level, which MSVC 545 /// correctly rejects. 546 static const CXXRecordDecl * 547 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 548 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 549 DC = DC->getPrimaryContext(); 550 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 551 if (MD->getParent()->hasAnyDependentBases()) 552 return MD->getParent(); 553 } 554 return nullptr; 555 } 556 557 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 558 SourceLocation NameLoc, 559 bool IsTemplateTypeArg) { 560 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 561 562 NestedNameSpecifier *NNS = nullptr; 563 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 564 // If we weren't able to parse a default template argument, delay lookup 565 // until instantiation time by making a non-dependent DependentTypeName. We 566 // pretend we saw a NestedNameSpecifier referring to the current scope, and 567 // lookup is retried. 568 // FIXME: This hurts our diagnostic quality, since we get errors like "no 569 // type named 'Foo' in 'current_namespace'" when the user didn't write any 570 // name specifiers. 571 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 572 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 573 } else if (const CXXRecordDecl *RD = 574 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 575 // Build a DependentNameType that will perform lookup into RD at 576 // instantiation time. 577 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 578 RD->getTypeForDecl()); 579 580 // Diagnose that this identifier was undeclared, and retry the lookup during 581 // template instantiation. 582 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 583 << RD; 584 } else { 585 // This is not a situation that we should recover from. 586 return ParsedType(); 587 } 588 589 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 590 591 // Build type location information. We synthesized the qualifier, so we have 592 // to build a fake NestedNameSpecifierLoc. 593 NestedNameSpecifierLocBuilder NNSLocBuilder; 594 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 595 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 596 597 TypeLocBuilder Builder; 598 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 599 DepTL.setNameLoc(NameLoc); 600 DepTL.setElaboratedKeywordLoc(SourceLocation()); 601 DepTL.setQualifierLoc(QualifierLoc); 602 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 603 } 604 605 /// isTagName() - This method is called *for error recovery purposes only* 606 /// to determine if the specified name is a valid tag name ("struct foo"). If 607 /// so, this returns the TST for the tag corresponding to it (TST_enum, 608 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 609 /// cases in C where the user forgot to specify the tag. 610 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 611 // Do a tag name lookup in this scope. 612 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 613 LookupName(R, S, false); 614 R.suppressDiagnostics(); 615 if (R.getResultKind() == LookupResult::Found) 616 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 617 switch (TD->getTagKind()) { 618 case TTK_Struct: return DeclSpec::TST_struct; 619 case TTK_Interface: return DeclSpec::TST_interface; 620 case TTK_Union: return DeclSpec::TST_union; 621 case TTK_Class: return DeclSpec::TST_class; 622 case TTK_Enum: return DeclSpec::TST_enum; 623 } 624 } 625 626 return DeclSpec::TST_unspecified; 627 } 628 629 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 630 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 631 /// then downgrade the missing typename error to a warning. 632 /// This is needed for MSVC compatibility; Example: 633 /// @code 634 /// template<class T> class A { 635 /// public: 636 /// typedef int TYPE; 637 /// }; 638 /// template<class T> class B : public A<T> { 639 /// public: 640 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 641 /// }; 642 /// @endcode 643 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 644 if (CurContext->isRecord()) { 645 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 646 return true; 647 648 const Type *Ty = SS->getScopeRep()->getAsType(); 649 650 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 651 for (const auto &Base : RD->bases()) 652 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 653 return true; 654 return S->isFunctionPrototypeScope(); 655 } 656 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 657 } 658 659 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 660 SourceLocation IILoc, 661 Scope *S, 662 CXXScopeSpec *SS, 663 ParsedType &SuggestedType, 664 bool IsTemplateName) { 665 // Don't report typename errors for editor placeholders. 666 if (II->isEditorPlaceholder()) 667 return; 668 // We don't have anything to suggest (yet). 669 SuggestedType = nullptr; 670 671 // There may have been a typo in the name of the type. Look up typo 672 // results, in case we have something that we can suggest. 673 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 674 /*AllowTemplates=*/IsTemplateName, 675 /*AllowNonTemplates=*/!IsTemplateName); 676 if (TypoCorrection Corrected = 677 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 678 CCC, CTK_ErrorRecovery)) { 679 // FIXME: Support error recovery for the template-name case. 680 bool CanRecover = !IsTemplateName; 681 if (Corrected.isKeyword()) { 682 // We corrected to a keyword. 683 diagnoseTypo(Corrected, 684 PDiag(IsTemplateName ? diag::err_no_template_suggest 685 : diag::err_unknown_typename_suggest) 686 << II); 687 II = Corrected.getCorrectionAsIdentifierInfo(); 688 } else { 689 // We found a similarly-named type or interface; suggest that. 690 if (!SS || !SS->isSet()) { 691 diagnoseTypo(Corrected, 692 PDiag(IsTemplateName ? diag::err_no_template_suggest 693 : diag::err_unknown_typename_suggest) 694 << II, CanRecover); 695 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 696 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 697 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 698 II->getName().equals(CorrectedStr); 699 diagnoseTypo(Corrected, 700 PDiag(IsTemplateName 701 ? diag::err_no_member_template_suggest 702 : diag::err_unknown_nested_typename_suggest) 703 << II << DC << DroppedSpecifier << SS->getRange(), 704 CanRecover); 705 } else { 706 llvm_unreachable("could not have corrected a typo here"); 707 } 708 709 if (!CanRecover) 710 return; 711 712 CXXScopeSpec tmpSS; 713 if (Corrected.getCorrectionSpecifier()) 714 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 715 SourceRange(IILoc)); 716 // FIXME: Support class template argument deduction here. 717 SuggestedType = 718 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 719 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 720 /*IsCtorOrDtorName=*/false, 721 /*WantNontrivialTypeSourceInfo=*/true); 722 } 723 return; 724 } 725 726 if (getLangOpts().CPlusPlus && !IsTemplateName) { 727 // See if II is a class template that the user forgot to pass arguments to. 728 UnqualifiedId Name; 729 Name.setIdentifier(II, IILoc); 730 CXXScopeSpec EmptySS; 731 TemplateTy TemplateResult; 732 bool MemberOfUnknownSpecialization; 733 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 734 Name, nullptr, true, TemplateResult, 735 MemberOfUnknownSpecialization) == TNK_Type_template) { 736 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 737 return; 738 } 739 } 740 741 // FIXME: Should we move the logic that tries to recover from a missing tag 742 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 743 744 if (!SS || (!SS->isSet() && !SS->isInvalid())) 745 Diag(IILoc, IsTemplateName ? diag::err_no_template 746 : diag::err_unknown_typename) 747 << II; 748 else if (DeclContext *DC = computeDeclContext(*SS, false)) 749 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 750 : diag::err_typename_nested_not_found) 751 << II << DC << SS->getRange(); 752 else if (isDependentScopeSpecifier(*SS)) { 753 unsigned DiagID = diag::err_typename_missing; 754 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 755 DiagID = diag::ext_typename_missing; 756 757 Diag(SS->getRange().getBegin(), DiagID) 758 << SS->getScopeRep() << II->getName() 759 << SourceRange(SS->getRange().getBegin(), IILoc) 760 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 761 SuggestedType = ActOnTypenameType(S, SourceLocation(), 762 *SS, *II, IILoc).get(); 763 } else { 764 assert(SS && SS->isInvalid() && 765 "Invalid scope specifier has already been diagnosed"); 766 } 767 } 768 769 /// Determine whether the given result set contains either a type name 770 /// or 771 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 772 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 773 NextToken.is(tok::less); 774 775 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 776 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 777 return true; 778 779 if (CheckTemplate && isa<TemplateDecl>(*I)) 780 return true; 781 } 782 783 return false; 784 } 785 786 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 787 Scope *S, CXXScopeSpec &SS, 788 IdentifierInfo *&Name, 789 SourceLocation NameLoc) { 790 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 791 SemaRef.LookupParsedName(R, S, &SS); 792 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 793 StringRef FixItTagName; 794 switch (Tag->getTagKind()) { 795 case TTK_Class: 796 FixItTagName = "class "; 797 break; 798 799 case TTK_Enum: 800 FixItTagName = "enum "; 801 break; 802 803 case TTK_Struct: 804 FixItTagName = "struct "; 805 break; 806 807 case TTK_Interface: 808 FixItTagName = "__interface "; 809 break; 810 811 case TTK_Union: 812 FixItTagName = "union "; 813 break; 814 } 815 816 StringRef TagName = FixItTagName.drop_back(); 817 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 818 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 819 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 820 821 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 822 I != IEnd; ++I) 823 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 824 << Name << TagName; 825 826 // Replace lookup results with just the tag decl. 827 Result.clear(Sema::LookupTagName); 828 SemaRef.LookupParsedName(Result, S, &SS); 829 return true; 830 } 831 832 return false; 833 } 834 835 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 836 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 837 QualType T, SourceLocation NameLoc) { 838 ASTContext &Context = S.Context; 839 840 TypeLocBuilder Builder; 841 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 842 843 T = S.getElaboratedType(ETK_None, SS, T); 844 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 845 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 846 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 847 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 848 } 849 850 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 851 IdentifierInfo *&Name, 852 SourceLocation NameLoc, 853 const Token &NextToken, 854 CorrectionCandidateCallback *CCC) { 855 DeclarationNameInfo NameInfo(Name, NameLoc); 856 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 857 858 assert(NextToken.isNot(tok::coloncolon) && 859 "parse nested name specifiers before calling ClassifyName"); 860 if (getLangOpts().CPlusPlus && SS.isSet() && 861 isCurrentClassName(*Name, S, &SS)) { 862 // Per [class.qual]p2, this names the constructors of SS, not the 863 // injected-class-name. We don't have a classification for that. 864 // There's not much point caching this result, since the parser 865 // will reject it later. 866 return NameClassification::Unknown(); 867 } 868 869 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 870 LookupParsedName(Result, S, &SS, !CurMethod); 871 872 if (SS.isInvalid()) 873 return NameClassification::Error(); 874 875 // For unqualified lookup in a class template in MSVC mode, look into 876 // dependent base classes where the primary class template is known. 877 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 878 if (ParsedType TypeInBase = 879 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 880 return TypeInBase; 881 } 882 883 // Perform lookup for Objective-C instance variables (including automatically 884 // synthesized instance variables), if we're in an Objective-C method. 885 // FIXME: This lookup really, really needs to be folded in to the normal 886 // unqualified lookup mechanism. 887 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 888 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 889 if (Ivar.isInvalid()) 890 return NameClassification::Error(); 891 if (Ivar.isUsable()) 892 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 893 894 // We defer builtin creation until after ivar lookup inside ObjC methods. 895 if (Result.empty()) 896 LookupBuiltin(Result); 897 } 898 899 bool SecondTry = false; 900 bool IsFilteredTemplateName = false; 901 902 Corrected: 903 switch (Result.getResultKind()) { 904 case LookupResult::NotFound: 905 // If an unqualified-id is followed by a '(', then we have a function 906 // call. 907 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 908 // In C++, this is an ADL-only call. 909 // FIXME: Reference? 910 if (getLangOpts().CPlusPlus) 911 return NameClassification::UndeclaredNonType(); 912 913 // C90 6.3.2.2: 914 // If the expression that precedes the parenthesized argument list in a 915 // function call consists solely of an identifier, and if no 916 // declaration is visible for this identifier, the identifier is 917 // implicitly declared exactly as if, in the innermost block containing 918 // the function call, the declaration 919 // 920 // extern int identifier (); 921 // 922 // appeared. 923 // 924 // We also allow this in C99 as an extension. 925 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 926 return NameClassification::NonType(D); 927 } 928 929 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 930 // In C++20 onwards, this could be an ADL-only call to a function 931 // template, and we're required to assume that this is a template name. 932 // 933 // FIXME: Find a way to still do typo correction in this case. 934 TemplateName Template = 935 Context.getAssumedTemplateName(NameInfo.getName()); 936 return NameClassification::UndeclaredTemplate(Template); 937 } 938 939 // In C, we first see whether there is a tag type by the same name, in 940 // which case it's likely that the user just forgot to write "enum", 941 // "struct", or "union". 942 if (!getLangOpts().CPlusPlus && !SecondTry && 943 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 944 break; 945 } 946 947 // Perform typo correction to determine if there is another name that is 948 // close to this name. 949 if (!SecondTry && CCC) { 950 SecondTry = true; 951 if (TypoCorrection Corrected = 952 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 953 &SS, *CCC, CTK_ErrorRecovery)) { 954 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 955 unsigned QualifiedDiag = diag::err_no_member_suggest; 956 957 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 958 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 959 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 960 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 961 UnqualifiedDiag = diag::err_no_template_suggest; 962 QualifiedDiag = diag::err_no_member_template_suggest; 963 } else if (UnderlyingFirstDecl && 964 (isa<TypeDecl>(UnderlyingFirstDecl) || 965 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 966 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 967 UnqualifiedDiag = diag::err_unknown_typename_suggest; 968 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 969 } 970 971 if (SS.isEmpty()) { 972 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 973 } else {// FIXME: is this even reachable? Test it. 974 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 975 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 976 Name->getName().equals(CorrectedStr); 977 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 978 << Name << computeDeclContext(SS, false) 979 << DroppedSpecifier << SS.getRange()); 980 } 981 982 // Update the name, so that the caller has the new name. 983 Name = Corrected.getCorrectionAsIdentifierInfo(); 984 985 // Typo correction corrected to a keyword. 986 if (Corrected.isKeyword()) 987 return Name; 988 989 // Also update the LookupResult... 990 // FIXME: This should probably go away at some point 991 Result.clear(); 992 Result.setLookupName(Corrected.getCorrection()); 993 if (FirstDecl) 994 Result.addDecl(FirstDecl); 995 996 // If we found an Objective-C instance variable, let 997 // LookupInObjCMethod build the appropriate expression to 998 // reference the ivar. 999 // FIXME: This is a gross hack. 1000 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1001 DeclResult R = 1002 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1003 if (R.isInvalid()) 1004 return NameClassification::Error(); 1005 if (R.isUsable()) 1006 return NameClassification::NonType(Ivar); 1007 } 1008 1009 goto Corrected; 1010 } 1011 } 1012 1013 // We failed to correct; just fall through and let the parser deal with it. 1014 Result.suppressDiagnostics(); 1015 return NameClassification::Unknown(); 1016 1017 case LookupResult::NotFoundInCurrentInstantiation: { 1018 // We performed name lookup into the current instantiation, and there were 1019 // dependent bases, so we treat this result the same way as any other 1020 // dependent nested-name-specifier. 1021 1022 // C++ [temp.res]p2: 1023 // A name used in a template declaration or definition and that is 1024 // dependent on a template-parameter is assumed not to name a type 1025 // unless the applicable name lookup finds a type name or the name is 1026 // qualified by the keyword typename. 1027 // 1028 // FIXME: If the next token is '<', we might want to ask the parser to 1029 // perform some heroics to see if we actually have a 1030 // template-argument-list, which would indicate a missing 'template' 1031 // keyword here. 1032 return NameClassification::DependentNonType(); 1033 } 1034 1035 case LookupResult::Found: 1036 case LookupResult::FoundOverloaded: 1037 case LookupResult::FoundUnresolvedValue: 1038 break; 1039 1040 case LookupResult::Ambiguous: 1041 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1042 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1043 /*AllowDependent=*/false)) { 1044 // C++ [temp.local]p3: 1045 // A lookup that finds an injected-class-name (10.2) can result in an 1046 // ambiguity in certain cases (for example, if it is found in more than 1047 // one base class). If all of the injected-class-names that are found 1048 // refer to specializations of the same class template, and if the name 1049 // is followed by a template-argument-list, the reference refers to the 1050 // class template itself and not a specialization thereof, and is not 1051 // ambiguous. 1052 // 1053 // This filtering can make an ambiguous result into an unambiguous one, 1054 // so try again after filtering out template names. 1055 FilterAcceptableTemplateNames(Result); 1056 if (!Result.isAmbiguous()) { 1057 IsFilteredTemplateName = true; 1058 break; 1059 } 1060 } 1061 1062 // Diagnose the ambiguity and return an error. 1063 return NameClassification::Error(); 1064 } 1065 1066 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1067 (IsFilteredTemplateName || 1068 hasAnyAcceptableTemplateNames( 1069 Result, /*AllowFunctionTemplates=*/true, 1070 /*AllowDependent=*/false, 1071 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1072 getLangOpts().CPlusPlus20))) { 1073 // C++ [temp.names]p3: 1074 // After name lookup (3.4) finds that a name is a template-name or that 1075 // an operator-function-id or a literal- operator-id refers to a set of 1076 // overloaded functions any member of which is a function template if 1077 // this is followed by a <, the < is always taken as the delimiter of a 1078 // template-argument-list and never as the less-than operator. 1079 // C++2a [temp.names]p2: 1080 // A name is also considered to refer to a template if it is an 1081 // unqualified-id followed by a < and name lookup finds either one 1082 // or more functions or finds nothing. 1083 if (!IsFilteredTemplateName) 1084 FilterAcceptableTemplateNames(Result); 1085 1086 bool IsFunctionTemplate; 1087 bool IsVarTemplate; 1088 TemplateName Template; 1089 if (Result.end() - Result.begin() > 1) { 1090 IsFunctionTemplate = true; 1091 Template = Context.getOverloadedTemplateName(Result.begin(), 1092 Result.end()); 1093 } else if (!Result.empty()) { 1094 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1095 *Result.begin(), /*AllowFunctionTemplates=*/true, 1096 /*AllowDependent=*/false)); 1097 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1098 IsVarTemplate = isa<VarTemplateDecl>(TD); 1099 1100 if (SS.isNotEmpty()) 1101 Template = 1102 Context.getQualifiedTemplateName(SS.getScopeRep(), 1103 /*TemplateKeyword=*/false, TD); 1104 else 1105 Template = TemplateName(TD); 1106 } else { 1107 // All results were non-template functions. This is a function template 1108 // name. 1109 IsFunctionTemplate = true; 1110 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1111 } 1112 1113 if (IsFunctionTemplate) { 1114 // Function templates always go through overload resolution, at which 1115 // point we'll perform the various checks (e.g., accessibility) we need 1116 // to based on which function we selected. 1117 Result.suppressDiagnostics(); 1118 1119 return NameClassification::FunctionTemplate(Template); 1120 } 1121 1122 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1123 : NameClassification::TypeTemplate(Template); 1124 } 1125 1126 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1127 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1128 DiagnoseUseOfDecl(Type, NameLoc); 1129 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1130 QualType T = Context.getTypeDeclType(Type); 1131 if (SS.isNotEmpty()) 1132 return buildNestedType(*this, SS, T, NameLoc); 1133 return ParsedType::make(T); 1134 } 1135 1136 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1137 if (!Class) { 1138 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1139 if (ObjCCompatibleAliasDecl *Alias = 1140 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1141 Class = Alias->getClassInterface(); 1142 } 1143 1144 if (Class) { 1145 DiagnoseUseOfDecl(Class, NameLoc); 1146 1147 if (NextToken.is(tok::period)) { 1148 // Interface. <something> is parsed as a property reference expression. 1149 // Just return "unknown" as a fall-through for now. 1150 Result.suppressDiagnostics(); 1151 return NameClassification::Unknown(); 1152 } 1153 1154 QualType T = Context.getObjCInterfaceType(Class); 1155 return ParsedType::make(T); 1156 } 1157 1158 if (isa<ConceptDecl>(FirstDecl)) 1159 return NameClassification::Concept( 1160 TemplateName(cast<TemplateDecl>(FirstDecl))); 1161 1162 // We can have a type template here if we're classifying a template argument. 1163 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1164 !isa<VarTemplateDecl>(FirstDecl)) 1165 return NameClassification::TypeTemplate( 1166 TemplateName(cast<TemplateDecl>(FirstDecl))); 1167 1168 // Check for a tag type hidden by a non-type decl in a few cases where it 1169 // seems likely a type is wanted instead of the non-type that was found. 1170 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1171 if ((NextToken.is(tok::identifier) || 1172 (NextIsOp && 1173 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1174 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1175 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1176 DiagnoseUseOfDecl(Type, NameLoc); 1177 QualType T = Context.getTypeDeclType(Type); 1178 if (SS.isNotEmpty()) 1179 return buildNestedType(*this, SS, T, NameLoc); 1180 return ParsedType::make(T); 1181 } 1182 1183 // FIXME: This is context-dependent. We need to defer building the member 1184 // expression until the classification is consumed. 1185 if (FirstDecl->isCXXClassMember()) 1186 return NameClassification::ContextIndependentExpr( 1187 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1188 S)); 1189 1190 // If we already know which single declaration is referenced, just annotate 1191 // that declaration directly. 1192 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1193 if (Result.isSingleResult() && !ADL) 1194 return NameClassification::NonType(Result.getRepresentativeDecl()); 1195 1196 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1197 // context in which we performed classification, so it's safe to do now. 1198 return NameClassification::ContextIndependentExpr( 1199 BuildDeclarationNameExpr(SS, Result, ADL)); 1200 } 1201 1202 ExprResult 1203 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1204 SourceLocation NameLoc) { 1205 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1206 CXXScopeSpec SS; 1207 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1208 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1209 } 1210 1211 ExprResult 1212 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1213 IdentifierInfo *Name, 1214 SourceLocation NameLoc, 1215 bool IsAddressOfOperand) { 1216 DeclarationNameInfo NameInfo(Name, NameLoc); 1217 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1218 NameInfo, IsAddressOfOperand, 1219 /*TemplateArgs=*/nullptr); 1220 } 1221 1222 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1223 NamedDecl *Found, 1224 SourceLocation NameLoc, 1225 const Token &NextToken) { 1226 if (getCurMethodDecl() && SS.isEmpty()) 1227 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1228 return BuildIvarRefExpr(S, NameLoc, Ivar); 1229 1230 // Reconstruct the lookup result. 1231 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1232 Result.addDecl(Found); 1233 Result.resolveKind(); 1234 1235 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1236 return BuildDeclarationNameExpr(SS, Result, ADL); 1237 } 1238 1239 Sema::TemplateNameKindForDiagnostics 1240 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1241 auto *TD = Name.getAsTemplateDecl(); 1242 if (!TD) 1243 return TemplateNameKindForDiagnostics::DependentTemplate; 1244 if (isa<ClassTemplateDecl>(TD)) 1245 return TemplateNameKindForDiagnostics::ClassTemplate; 1246 if (isa<FunctionTemplateDecl>(TD)) 1247 return TemplateNameKindForDiagnostics::FunctionTemplate; 1248 if (isa<VarTemplateDecl>(TD)) 1249 return TemplateNameKindForDiagnostics::VarTemplate; 1250 if (isa<TypeAliasTemplateDecl>(TD)) 1251 return TemplateNameKindForDiagnostics::AliasTemplate; 1252 if (isa<TemplateTemplateParmDecl>(TD)) 1253 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1254 if (isa<ConceptDecl>(TD)) 1255 return TemplateNameKindForDiagnostics::Concept; 1256 return TemplateNameKindForDiagnostics::DependentTemplate; 1257 } 1258 1259 // Determines the context to return to after temporarily entering a 1260 // context. This depends in an unnecessarily complicated way on the 1261 // exact ordering of callbacks from the parser. 1262 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1263 1264 // Functions defined inline within classes aren't parsed until we've 1265 // finished parsing the top-level class, so the top-level class is 1266 // the context we'll need to return to. 1267 // A Lambda call operator whose parent is a class must not be treated 1268 // as an inline member function. A Lambda can be used legally 1269 // either as an in-class member initializer or a default argument. These 1270 // are parsed once the class has been marked complete and so the containing 1271 // context would be the nested class (when the lambda is defined in one); 1272 // If the class is not complete, then the lambda is being used in an 1273 // ill-formed fashion (such as to specify the width of a bit-field, or 1274 // in an array-bound) - in which case we still want to return the 1275 // lexically containing DC (which could be a nested class). 1276 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1277 DC = DC->getLexicalParent(); 1278 1279 // A function not defined within a class will always return to its 1280 // lexical context. 1281 if (!isa<CXXRecordDecl>(DC)) 1282 return DC; 1283 1284 // A C++ inline method/friend is parsed *after* the topmost class 1285 // it was declared in is fully parsed ("complete"); the topmost 1286 // class is the context we need to return to. 1287 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1288 DC = RD; 1289 1290 // Return the declaration context of the topmost class the inline method is 1291 // declared in. 1292 return DC; 1293 } 1294 1295 return DC->getLexicalParent(); 1296 } 1297 1298 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1299 assert(getContainingDC(DC) == CurContext && 1300 "The next DeclContext should be lexically contained in the current one."); 1301 CurContext = DC; 1302 S->setEntity(DC); 1303 } 1304 1305 void Sema::PopDeclContext() { 1306 assert(CurContext && "DeclContext imbalance!"); 1307 1308 CurContext = getContainingDC(CurContext); 1309 assert(CurContext && "Popped translation unit!"); 1310 } 1311 1312 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1313 Decl *D) { 1314 // Unlike PushDeclContext, the context to which we return is not necessarily 1315 // the containing DC of TD, because the new context will be some pre-existing 1316 // TagDecl definition instead of a fresh one. 1317 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1318 CurContext = cast<TagDecl>(D)->getDefinition(); 1319 assert(CurContext && "skipping definition of undefined tag"); 1320 // Start lookups from the parent of the current context; we don't want to look 1321 // into the pre-existing complete definition. 1322 S->setEntity(CurContext->getLookupParent()); 1323 return Result; 1324 } 1325 1326 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1327 CurContext = static_cast<decltype(CurContext)>(Context); 1328 } 1329 1330 /// EnterDeclaratorContext - Used when we must lookup names in the context 1331 /// of a declarator's nested name specifier. 1332 /// 1333 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1334 // C++0x [basic.lookup.unqual]p13: 1335 // A name used in the definition of a static data member of class 1336 // X (after the qualified-id of the static member) is looked up as 1337 // if the name was used in a member function of X. 1338 // C++0x [basic.lookup.unqual]p14: 1339 // If a variable member of a namespace is defined outside of the 1340 // scope of its namespace then any name used in the definition of 1341 // the variable member (after the declarator-id) is looked up as 1342 // if the definition of the variable member occurred in its 1343 // namespace. 1344 // Both of these imply that we should push a scope whose context 1345 // is the semantic context of the declaration. We can't use 1346 // PushDeclContext here because that context is not necessarily 1347 // lexically contained in the current context. Fortunately, 1348 // the containing scope should have the appropriate information. 1349 1350 assert(!S->getEntity() && "scope already has entity"); 1351 1352 #ifndef NDEBUG 1353 Scope *Ancestor = S->getParent(); 1354 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1355 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1356 #endif 1357 1358 CurContext = DC; 1359 S->setEntity(DC); 1360 } 1361 1362 void Sema::ExitDeclaratorContext(Scope *S) { 1363 assert(S->getEntity() == CurContext && "Context imbalance!"); 1364 1365 // Switch back to the lexical context. The safety of this is 1366 // enforced by an assert in EnterDeclaratorContext. 1367 Scope *Ancestor = S->getParent(); 1368 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1369 CurContext = Ancestor->getEntity(); 1370 1371 // We don't need to do anything with the scope, which is going to 1372 // disappear. 1373 } 1374 1375 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1376 // We assume that the caller has already called 1377 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1378 FunctionDecl *FD = D->getAsFunction(); 1379 if (!FD) 1380 return; 1381 1382 // Same implementation as PushDeclContext, but enters the context 1383 // from the lexical parent, rather than the top-level class. 1384 assert(CurContext == FD->getLexicalParent() && 1385 "The next DeclContext should be lexically contained in the current one."); 1386 CurContext = FD; 1387 S->setEntity(CurContext); 1388 1389 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1390 ParmVarDecl *Param = FD->getParamDecl(P); 1391 // If the parameter has an identifier, then add it to the scope 1392 if (Param->getIdentifier()) { 1393 S->AddDecl(Param); 1394 IdResolver.AddDecl(Param); 1395 } 1396 } 1397 } 1398 1399 void Sema::ActOnExitFunctionContext() { 1400 // Same implementation as PopDeclContext, but returns to the lexical parent, 1401 // rather than the top-level class. 1402 assert(CurContext && "DeclContext imbalance!"); 1403 CurContext = CurContext->getLexicalParent(); 1404 assert(CurContext && "Popped translation unit!"); 1405 } 1406 1407 /// Determine whether we allow overloading of the function 1408 /// PrevDecl with another declaration. 1409 /// 1410 /// This routine determines whether overloading is possible, not 1411 /// whether some new function is actually an overload. It will return 1412 /// true in C++ (where we can always provide overloads) or, as an 1413 /// extension, in C when the previous function is already an 1414 /// overloaded function declaration or has the "overloadable" 1415 /// attribute. 1416 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1417 ASTContext &Context, 1418 const FunctionDecl *New) { 1419 if (Context.getLangOpts().CPlusPlus) 1420 return true; 1421 1422 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1423 return true; 1424 1425 return Previous.getResultKind() == LookupResult::Found && 1426 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1427 New->hasAttr<OverloadableAttr>()); 1428 } 1429 1430 /// Add this decl to the scope shadowed decl chains. 1431 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1432 // Move up the scope chain until we find the nearest enclosing 1433 // non-transparent context. The declaration will be introduced into this 1434 // scope. 1435 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1436 S = S->getParent(); 1437 1438 // Add scoped declarations into their context, so that they can be 1439 // found later. Declarations without a context won't be inserted 1440 // into any context. 1441 if (AddToContext) 1442 CurContext->addDecl(D); 1443 1444 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1445 // are function-local declarations. 1446 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1447 !D->getDeclContext()->getRedeclContext()->Equals( 1448 D->getLexicalDeclContext()->getRedeclContext()) && 1449 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1450 return; 1451 1452 // Template instantiations should also not be pushed into scope. 1453 if (isa<FunctionDecl>(D) && 1454 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1455 return; 1456 1457 // If this replaces anything in the current scope, 1458 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1459 IEnd = IdResolver.end(); 1460 for (; I != IEnd; ++I) { 1461 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1462 S->RemoveDecl(*I); 1463 IdResolver.RemoveDecl(*I); 1464 1465 // Should only need to replace one decl. 1466 break; 1467 } 1468 } 1469 1470 S->AddDecl(D); 1471 1472 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1473 // Implicitly-generated labels may end up getting generated in an order that 1474 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1475 // the label at the appropriate place in the identifier chain. 1476 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1477 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1478 if (IDC == CurContext) { 1479 if (!S->isDeclScope(*I)) 1480 continue; 1481 } else if (IDC->Encloses(CurContext)) 1482 break; 1483 } 1484 1485 IdResolver.InsertDeclAfter(I, D); 1486 } else { 1487 IdResolver.AddDecl(D); 1488 } 1489 } 1490 1491 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1492 bool AllowInlineNamespace) { 1493 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1494 } 1495 1496 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1497 DeclContext *TargetDC = DC->getPrimaryContext(); 1498 do { 1499 if (DeclContext *ScopeDC = S->getEntity()) 1500 if (ScopeDC->getPrimaryContext() == TargetDC) 1501 return S; 1502 } while ((S = S->getParent())); 1503 1504 return nullptr; 1505 } 1506 1507 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1508 DeclContext*, 1509 ASTContext&); 1510 1511 /// Filters out lookup results that don't fall within the given scope 1512 /// as determined by isDeclInScope. 1513 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1514 bool ConsiderLinkage, 1515 bool AllowInlineNamespace) { 1516 LookupResult::Filter F = R.makeFilter(); 1517 while (F.hasNext()) { 1518 NamedDecl *D = F.next(); 1519 1520 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1521 continue; 1522 1523 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1524 continue; 1525 1526 F.erase(); 1527 } 1528 1529 F.done(); 1530 } 1531 1532 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1533 /// have compatible owning modules. 1534 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1535 // FIXME: The Modules TS is not clear about how friend declarations are 1536 // to be treated. It's not meaningful to have different owning modules for 1537 // linkage in redeclarations of the same entity, so for now allow the 1538 // redeclaration and change the owning modules to match. 1539 if (New->getFriendObjectKind() && 1540 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1541 New->setLocalOwningModule(Old->getOwningModule()); 1542 makeMergedDefinitionVisible(New); 1543 return false; 1544 } 1545 1546 Module *NewM = New->getOwningModule(); 1547 Module *OldM = Old->getOwningModule(); 1548 1549 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1550 NewM = NewM->Parent; 1551 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1552 OldM = OldM->Parent; 1553 1554 if (NewM == OldM) 1555 return false; 1556 1557 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1558 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1559 if (NewIsModuleInterface || OldIsModuleInterface) { 1560 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1561 // if a declaration of D [...] appears in the purview of a module, all 1562 // other such declarations shall appear in the purview of the same module 1563 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1564 << New 1565 << NewIsModuleInterface 1566 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1567 << OldIsModuleInterface 1568 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1569 Diag(Old->getLocation(), diag::note_previous_declaration); 1570 New->setInvalidDecl(); 1571 return true; 1572 } 1573 1574 return false; 1575 } 1576 1577 static bool isUsingDecl(NamedDecl *D) { 1578 return isa<UsingShadowDecl>(D) || 1579 isa<UnresolvedUsingTypenameDecl>(D) || 1580 isa<UnresolvedUsingValueDecl>(D); 1581 } 1582 1583 /// Removes using shadow declarations from the lookup results. 1584 static void RemoveUsingDecls(LookupResult &R) { 1585 LookupResult::Filter F = R.makeFilter(); 1586 while (F.hasNext()) 1587 if (isUsingDecl(F.next())) 1588 F.erase(); 1589 1590 F.done(); 1591 } 1592 1593 /// Check for this common pattern: 1594 /// @code 1595 /// class S { 1596 /// S(const S&); // DO NOT IMPLEMENT 1597 /// void operator=(const S&); // DO NOT IMPLEMENT 1598 /// }; 1599 /// @endcode 1600 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1601 // FIXME: Should check for private access too but access is set after we get 1602 // the decl here. 1603 if (D->doesThisDeclarationHaveABody()) 1604 return false; 1605 1606 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1607 return CD->isCopyConstructor(); 1608 return D->isCopyAssignmentOperator(); 1609 } 1610 1611 // We need this to handle 1612 // 1613 // typedef struct { 1614 // void *foo() { return 0; } 1615 // } A; 1616 // 1617 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1618 // for example. If 'A', foo will have external linkage. If we have '*A', 1619 // foo will have no linkage. Since we can't know until we get to the end 1620 // of the typedef, this function finds out if D might have non-external linkage. 1621 // Callers should verify at the end of the TU if it D has external linkage or 1622 // not. 1623 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1624 const DeclContext *DC = D->getDeclContext(); 1625 while (!DC->isTranslationUnit()) { 1626 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1627 if (!RD->hasNameForLinkage()) 1628 return true; 1629 } 1630 DC = DC->getParent(); 1631 } 1632 1633 return !D->isExternallyVisible(); 1634 } 1635 1636 // FIXME: This needs to be refactored; some other isInMainFile users want 1637 // these semantics. 1638 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1639 if (S.TUKind != TU_Complete) 1640 return false; 1641 return S.SourceMgr.isInMainFile(Loc); 1642 } 1643 1644 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1645 assert(D); 1646 1647 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1648 return false; 1649 1650 // Ignore all entities declared within templates, and out-of-line definitions 1651 // of members of class templates. 1652 if (D->getDeclContext()->isDependentContext() || 1653 D->getLexicalDeclContext()->isDependentContext()) 1654 return false; 1655 1656 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1657 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1658 return false; 1659 // A non-out-of-line declaration of a member specialization was implicitly 1660 // instantiated; it's the out-of-line declaration that we're interested in. 1661 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1662 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1663 return false; 1664 1665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1666 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1667 return false; 1668 } else { 1669 // 'static inline' functions are defined in headers; don't warn. 1670 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1671 return false; 1672 } 1673 1674 if (FD->doesThisDeclarationHaveABody() && 1675 Context.DeclMustBeEmitted(FD)) 1676 return false; 1677 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1678 // Constants and utility variables are defined in headers with internal 1679 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1680 // like "inline".) 1681 if (!isMainFileLoc(*this, VD->getLocation())) 1682 return false; 1683 1684 if (Context.DeclMustBeEmitted(VD)) 1685 return false; 1686 1687 if (VD->isStaticDataMember() && 1688 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1689 return false; 1690 if (VD->isStaticDataMember() && 1691 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1693 return false; 1694 1695 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1696 return false; 1697 } else { 1698 return false; 1699 } 1700 1701 // Only warn for unused decls internal to the translation unit. 1702 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1703 // for inline functions defined in the main source file, for instance. 1704 return mightHaveNonExternalLinkage(D); 1705 } 1706 1707 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1708 if (!D) 1709 return; 1710 1711 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1712 const FunctionDecl *First = FD->getFirstDecl(); 1713 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1714 return; // First should already be in the vector. 1715 } 1716 1717 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1718 const VarDecl *First = VD->getFirstDecl(); 1719 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1720 return; // First should already be in the vector. 1721 } 1722 1723 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1724 UnusedFileScopedDecls.push_back(D); 1725 } 1726 1727 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1728 if (D->isInvalidDecl()) 1729 return false; 1730 1731 bool Referenced = false; 1732 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1733 // For a decomposition declaration, warn if none of the bindings are 1734 // referenced, instead of if the variable itself is referenced (which 1735 // it is, by the bindings' expressions). 1736 for (auto *BD : DD->bindings()) { 1737 if (BD->isReferenced()) { 1738 Referenced = true; 1739 break; 1740 } 1741 } 1742 } else if (!D->getDeclName()) { 1743 return false; 1744 } else if (D->isReferenced() || D->isUsed()) { 1745 Referenced = true; 1746 } 1747 1748 if (Referenced || D->hasAttr<UnusedAttr>() || 1749 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1750 return false; 1751 1752 if (isa<LabelDecl>(D)) 1753 return true; 1754 1755 // Except for labels, we only care about unused decls that are local to 1756 // functions. 1757 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1758 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1759 // For dependent types, the diagnostic is deferred. 1760 WithinFunction = 1761 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1762 if (!WithinFunction) 1763 return false; 1764 1765 if (isa<TypedefNameDecl>(D)) 1766 return true; 1767 1768 // White-list anything that isn't a local variable. 1769 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1770 return false; 1771 1772 // Types of valid local variables should be complete, so this should succeed. 1773 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1774 1775 // White-list anything with an __attribute__((unused)) type. 1776 const auto *Ty = VD->getType().getTypePtr(); 1777 1778 // Only look at the outermost level of typedef. 1779 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1780 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1781 return false; 1782 } 1783 1784 // If we failed to complete the type for some reason, or if the type is 1785 // dependent, don't diagnose the variable. 1786 if (Ty->isIncompleteType() || Ty->isDependentType()) 1787 return false; 1788 1789 // Look at the element type to ensure that the warning behaviour is 1790 // consistent for both scalars and arrays. 1791 Ty = Ty->getBaseElementTypeUnsafe(); 1792 1793 if (const TagType *TT = Ty->getAs<TagType>()) { 1794 const TagDecl *Tag = TT->getDecl(); 1795 if (Tag->hasAttr<UnusedAttr>()) 1796 return false; 1797 1798 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1799 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1800 return false; 1801 1802 if (const Expr *Init = VD->getInit()) { 1803 if (const ExprWithCleanups *Cleanups = 1804 dyn_cast<ExprWithCleanups>(Init)) 1805 Init = Cleanups->getSubExpr(); 1806 const CXXConstructExpr *Construct = 1807 dyn_cast<CXXConstructExpr>(Init); 1808 if (Construct && !Construct->isElidable()) { 1809 CXXConstructorDecl *CD = Construct->getConstructor(); 1810 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1811 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1812 return false; 1813 } 1814 1815 // Suppress the warning if we don't know how this is constructed, and 1816 // it could possibly be non-trivial constructor. 1817 if (Init->isTypeDependent()) 1818 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1819 if (!Ctor->isTrivial()) 1820 return false; 1821 } 1822 } 1823 } 1824 1825 // TODO: __attribute__((unused)) templates? 1826 } 1827 1828 return true; 1829 } 1830 1831 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1832 FixItHint &Hint) { 1833 if (isa<LabelDecl>(D)) { 1834 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1835 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1836 true); 1837 if (AfterColon.isInvalid()) 1838 return; 1839 Hint = FixItHint::CreateRemoval( 1840 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1841 } 1842 } 1843 1844 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1845 if (D->getTypeForDecl()->isDependentType()) 1846 return; 1847 1848 for (auto *TmpD : D->decls()) { 1849 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1850 DiagnoseUnusedDecl(T); 1851 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1852 DiagnoseUnusedNestedTypedefs(R); 1853 } 1854 } 1855 1856 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1857 /// unless they are marked attr(unused). 1858 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1859 if (!ShouldDiagnoseUnusedDecl(D)) 1860 return; 1861 1862 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1863 // typedefs can be referenced later on, so the diagnostics are emitted 1864 // at end-of-translation-unit. 1865 UnusedLocalTypedefNameCandidates.insert(TD); 1866 return; 1867 } 1868 1869 FixItHint Hint; 1870 GenerateFixForUnusedDecl(D, Context, Hint); 1871 1872 unsigned DiagID; 1873 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1874 DiagID = diag::warn_unused_exception_param; 1875 else if (isa<LabelDecl>(D)) 1876 DiagID = diag::warn_unused_label; 1877 else 1878 DiagID = diag::warn_unused_variable; 1879 1880 Diag(D->getLocation(), DiagID) << D << Hint; 1881 } 1882 1883 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1884 // Verify that we have no forward references left. If so, there was a goto 1885 // or address of a label taken, but no definition of it. Label fwd 1886 // definitions are indicated with a null substmt which is also not a resolved 1887 // MS inline assembly label name. 1888 bool Diagnose = false; 1889 if (L->isMSAsmLabel()) 1890 Diagnose = !L->isResolvedMSAsmLabel(); 1891 else 1892 Diagnose = L->getStmt() == nullptr; 1893 if (Diagnose) 1894 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1895 } 1896 1897 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1898 S->mergeNRVOIntoParent(); 1899 1900 if (S->decl_empty()) return; 1901 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1902 "Scope shouldn't contain decls!"); 1903 1904 for (auto *TmpD : S->decls()) { 1905 assert(TmpD && "This decl didn't get pushed??"); 1906 1907 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1908 NamedDecl *D = cast<NamedDecl>(TmpD); 1909 1910 // Diagnose unused variables in this scope. 1911 if (!S->hasUnrecoverableErrorOccurred()) { 1912 DiagnoseUnusedDecl(D); 1913 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1914 DiagnoseUnusedNestedTypedefs(RD); 1915 } 1916 1917 if (!D->getDeclName()) continue; 1918 1919 // If this was a forward reference to a label, verify it was defined. 1920 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1921 CheckPoppedLabel(LD, *this); 1922 1923 // Remove this name from our lexical scope, and warn on it if we haven't 1924 // already. 1925 IdResolver.RemoveDecl(D); 1926 auto ShadowI = ShadowingDecls.find(D); 1927 if (ShadowI != ShadowingDecls.end()) { 1928 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1929 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1930 << D << FD << FD->getParent(); 1931 Diag(FD->getLocation(), diag::note_previous_declaration); 1932 } 1933 ShadowingDecls.erase(ShadowI); 1934 } 1935 } 1936 } 1937 1938 /// Look for an Objective-C class in the translation unit. 1939 /// 1940 /// \param Id The name of the Objective-C class we're looking for. If 1941 /// typo-correction fixes this name, the Id will be updated 1942 /// to the fixed name. 1943 /// 1944 /// \param IdLoc The location of the name in the translation unit. 1945 /// 1946 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1947 /// if there is no class with the given name. 1948 /// 1949 /// \returns The declaration of the named Objective-C class, or NULL if the 1950 /// class could not be found. 1951 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1952 SourceLocation IdLoc, 1953 bool DoTypoCorrection) { 1954 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1955 // creation from this context. 1956 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1957 1958 if (!IDecl && DoTypoCorrection) { 1959 // Perform typo correction at the given location, but only if we 1960 // find an Objective-C class name. 1961 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1962 if (TypoCorrection C = 1963 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1964 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1965 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1966 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1967 Id = IDecl->getIdentifier(); 1968 } 1969 } 1970 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1971 // This routine must always return a class definition, if any. 1972 if (Def && Def->getDefinition()) 1973 Def = Def->getDefinition(); 1974 return Def; 1975 } 1976 1977 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1978 /// from S, where a non-field would be declared. This routine copes 1979 /// with the difference between C and C++ scoping rules in structs and 1980 /// unions. For example, the following code is well-formed in C but 1981 /// ill-formed in C++: 1982 /// @code 1983 /// struct S6 { 1984 /// enum { BAR } e; 1985 /// }; 1986 /// 1987 /// void test_S6() { 1988 /// struct S6 a; 1989 /// a.e = BAR; 1990 /// } 1991 /// @endcode 1992 /// For the declaration of BAR, this routine will return a different 1993 /// scope. The scope S will be the scope of the unnamed enumeration 1994 /// within S6. In C++, this routine will return the scope associated 1995 /// with S6, because the enumeration's scope is a transparent 1996 /// context but structures can contain non-field names. In C, this 1997 /// routine will return the translation unit scope, since the 1998 /// enumeration's scope is a transparent context and structures cannot 1999 /// contain non-field names. 2000 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2001 while (((S->getFlags() & Scope::DeclScope) == 0) || 2002 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2003 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2004 S = S->getParent(); 2005 return S; 2006 } 2007 2008 /// Looks up the declaration of "struct objc_super" and 2009 /// saves it for later use in building builtin declaration of 2010 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2011 /// pre-existing declaration exists no action takes place. 2012 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2013 IdentifierInfo *II) { 2014 if (!II->isStr("objc_msgSendSuper")) 2015 return; 2016 ASTContext &Context = ThisSema.Context; 2017 2018 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2019 SourceLocation(), Sema::LookupTagName); 2020 ThisSema.LookupName(Result, S); 2021 if (Result.getResultKind() == LookupResult::Found) 2022 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2023 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2024 } 2025 2026 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2027 ASTContext::GetBuiltinTypeError Error) { 2028 switch (Error) { 2029 case ASTContext::GE_None: 2030 return ""; 2031 case ASTContext::GE_Missing_type: 2032 return BuiltinInfo.getHeaderName(ID); 2033 case ASTContext::GE_Missing_stdio: 2034 return "stdio.h"; 2035 case ASTContext::GE_Missing_setjmp: 2036 return "setjmp.h"; 2037 case ASTContext::GE_Missing_ucontext: 2038 return "ucontext.h"; 2039 } 2040 llvm_unreachable("unhandled error kind"); 2041 } 2042 2043 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2044 /// file scope. lazily create a decl for it. ForRedeclaration is true 2045 /// if we're creating this built-in in anticipation of redeclaring the 2046 /// built-in. 2047 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2048 Scope *S, bool ForRedeclaration, 2049 SourceLocation Loc) { 2050 LookupPredefedObjCSuperType(*this, S, II); 2051 2052 ASTContext::GetBuiltinTypeError Error; 2053 QualType R = Context.GetBuiltinType(ID, Error); 2054 if (Error) { 2055 if (!ForRedeclaration) 2056 return nullptr; 2057 2058 // If we have a builtin without an associated type we should not emit a 2059 // warning when we were not able to find a type for it. 2060 if (Error == ASTContext::GE_Missing_type) 2061 return nullptr; 2062 2063 // If we could not find a type for setjmp it is because the jmp_buf type was 2064 // not defined prior to the setjmp declaration. 2065 if (Error == ASTContext::GE_Missing_setjmp) { 2066 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2067 << Context.BuiltinInfo.getName(ID); 2068 return nullptr; 2069 } 2070 2071 // Generally, we emit a warning that the declaration requires the 2072 // appropriate header. 2073 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2074 << getHeaderName(Context.BuiltinInfo, ID, Error) 2075 << Context.BuiltinInfo.getName(ID); 2076 return nullptr; 2077 } 2078 2079 if (!ForRedeclaration && 2080 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2081 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2082 Diag(Loc, diag::ext_implicit_lib_function_decl) 2083 << Context.BuiltinInfo.getName(ID) << R; 2084 if (Context.BuiltinInfo.getHeaderName(ID) && 2085 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2086 Diag(Loc, diag::note_include_header_or_declare) 2087 << Context.BuiltinInfo.getHeaderName(ID) 2088 << Context.BuiltinInfo.getName(ID); 2089 } 2090 2091 if (R.isNull()) 2092 return nullptr; 2093 2094 DeclContext *Parent = Context.getTranslationUnitDecl(); 2095 if (getLangOpts().CPlusPlus) { 2096 LinkageSpecDecl *CLinkageDecl = 2097 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2098 LinkageSpecDecl::lang_c, false); 2099 CLinkageDecl->setImplicit(); 2100 Parent->addDecl(CLinkageDecl); 2101 Parent = CLinkageDecl; 2102 } 2103 2104 FunctionDecl *New = FunctionDecl::Create(Context, 2105 Parent, 2106 Loc, Loc, II, R, /*TInfo=*/nullptr, 2107 SC_Extern, 2108 false, 2109 R->isFunctionProtoType()); 2110 New->setImplicit(); 2111 2112 // Create Decl objects for each parameter, adding them to the 2113 // FunctionDecl. 2114 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2115 SmallVector<ParmVarDecl*, 16> Params; 2116 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2117 ParmVarDecl *parm = 2118 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2119 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2120 SC_None, nullptr); 2121 parm->setScopeInfo(0, i); 2122 Params.push_back(parm); 2123 } 2124 New->setParams(Params); 2125 } 2126 2127 AddKnownFunctionAttributes(New); 2128 RegisterLocallyScopedExternCDecl(New, S); 2129 2130 // TUScope is the translation-unit scope to insert this function into. 2131 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2132 // relate Scopes to DeclContexts, and probably eliminate CurContext 2133 // entirely, but we're not there yet. 2134 DeclContext *SavedContext = CurContext; 2135 CurContext = Parent; 2136 PushOnScopeChains(New, TUScope); 2137 CurContext = SavedContext; 2138 return New; 2139 } 2140 2141 /// Typedef declarations don't have linkage, but they still denote the same 2142 /// entity if their types are the same. 2143 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2144 /// isSameEntity. 2145 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2146 TypedefNameDecl *Decl, 2147 LookupResult &Previous) { 2148 // This is only interesting when modules are enabled. 2149 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2150 return; 2151 2152 // Empty sets are uninteresting. 2153 if (Previous.empty()) 2154 return; 2155 2156 LookupResult::Filter Filter = Previous.makeFilter(); 2157 while (Filter.hasNext()) { 2158 NamedDecl *Old = Filter.next(); 2159 2160 // Non-hidden declarations are never ignored. 2161 if (S.isVisible(Old)) 2162 continue; 2163 2164 // Declarations of the same entity are not ignored, even if they have 2165 // different linkages. 2166 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2167 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2168 Decl->getUnderlyingType())) 2169 continue; 2170 2171 // If both declarations give a tag declaration a typedef name for linkage 2172 // purposes, then they declare the same entity. 2173 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2174 Decl->getAnonDeclWithTypedefName()) 2175 continue; 2176 } 2177 2178 Filter.erase(); 2179 } 2180 2181 Filter.done(); 2182 } 2183 2184 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2185 QualType OldType; 2186 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2187 OldType = OldTypedef->getUnderlyingType(); 2188 else 2189 OldType = Context.getTypeDeclType(Old); 2190 QualType NewType = New->getUnderlyingType(); 2191 2192 if (NewType->isVariablyModifiedType()) { 2193 // Must not redefine a typedef with a variably-modified type. 2194 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2195 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2196 << Kind << NewType; 2197 if (Old->getLocation().isValid()) 2198 notePreviousDefinition(Old, New->getLocation()); 2199 New->setInvalidDecl(); 2200 return true; 2201 } 2202 2203 if (OldType != NewType && 2204 !OldType->isDependentType() && 2205 !NewType->isDependentType() && 2206 !Context.hasSameType(OldType, NewType)) { 2207 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2208 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2209 << Kind << NewType << OldType; 2210 if (Old->getLocation().isValid()) 2211 notePreviousDefinition(Old, New->getLocation()); 2212 New->setInvalidDecl(); 2213 return true; 2214 } 2215 return false; 2216 } 2217 2218 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2219 /// same name and scope as a previous declaration 'Old'. Figure out 2220 /// how to resolve this situation, merging decls or emitting 2221 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2222 /// 2223 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2224 LookupResult &OldDecls) { 2225 // If the new decl is known invalid already, don't bother doing any 2226 // merging checks. 2227 if (New->isInvalidDecl()) return; 2228 2229 // Allow multiple definitions for ObjC built-in typedefs. 2230 // FIXME: Verify the underlying types are equivalent! 2231 if (getLangOpts().ObjC) { 2232 const IdentifierInfo *TypeID = New->getIdentifier(); 2233 switch (TypeID->getLength()) { 2234 default: break; 2235 case 2: 2236 { 2237 if (!TypeID->isStr("id")) 2238 break; 2239 QualType T = New->getUnderlyingType(); 2240 if (!T->isPointerType()) 2241 break; 2242 if (!T->isVoidPointerType()) { 2243 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2244 if (!PT->isStructureType()) 2245 break; 2246 } 2247 Context.setObjCIdRedefinitionType(T); 2248 // Install the built-in type for 'id', ignoring the current definition. 2249 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2250 return; 2251 } 2252 case 5: 2253 if (!TypeID->isStr("Class")) 2254 break; 2255 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2256 // Install the built-in type for 'Class', ignoring the current definition. 2257 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2258 return; 2259 case 3: 2260 if (!TypeID->isStr("SEL")) 2261 break; 2262 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2263 // Install the built-in type for 'SEL', ignoring the current definition. 2264 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2265 return; 2266 } 2267 // Fall through - the typedef name was not a builtin type. 2268 } 2269 2270 // Verify the old decl was also a type. 2271 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2272 if (!Old) { 2273 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2274 << New->getDeclName(); 2275 2276 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2277 if (OldD->getLocation().isValid()) 2278 notePreviousDefinition(OldD, New->getLocation()); 2279 2280 return New->setInvalidDecl(); 2281 } 2282 2283 // If the old declaration is invalid, just give up here. 2284 if (Old->isInvalidDecl()) 2285 return New->setInvalidDecl(); 2286 2287 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2288 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2289 auto *NewTag = New->getAnonDeclWithTypedefName(); 2290 NamedDecl *Hidden = nullptr; 2291 if (OldTag && NewTag && 2292 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2293 !hasVisibleDefinition(OldTag, &Hidden)) { 2294 // There is a definition of this tag, but it is not visible. Use it 2295 // instead of our tag. 2296 New->setTypeForDecl(OldTD->getTypeForDecl()); 2297 if (OldTD->isModed()) 2298 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2299 OldTD->getUnderlyingType()); 2300 else 2301 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2302 2303 // Make the old tag definition visible. 2304 makeMergedDefinitionVisible(Hidden); 2305 2306 // If this was an unscoped enumeration, yank all of its enumerators 2307 // out of the scope. 2308 if (isa<EnumDecl>(NewTag)) { 2309 Scope *EnumScope = getNonFieldDeclScope(S); 2310 for (auto *D : NewTag->decls()) { 2311 auto *ED = cast<EnumConstantDecl>(D); 2312 assert(EnumScope->isDeclScope(ED)); 2313 EnumScope->RemoveDecl(ED); 2314 IdResolver.RemoveDecl(ED); 2315 ED->getLexicalDeclContext()->removeDecl(ED); 2316 } 2317 } 2318 } 2319 } 2320 2321 // If the typedef types are not identical, reject them in all languages and 2322 // with any extensions enabled. 2323 if (isIncompatibleTypedef(Old, New)) 2324 return; 2325 2326 // The types match. Link up the redeclaration chain and merge attributes if 2327 // the old declaration was a typedef. 2328 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2329 New->setPreviousDecl(Typedef); 2330 mergeDeclAttributes(New, Old); 2331 } 2332 2333 if (getLangOpts().MicrosoftExt) 2334 return; 2335 2336 if (getLangOpts().CPlusPlus) { 2337 // C++ [dcl.typedef]p2: 2338 // In a given non-class scope, a typedef specifier can be used to 2339 // redefine the name of any type declared in that scope to refer 2340 // to the type to which it already refers. 2341 if (!isa<CXXRecordDecl>(CurContext)) 2342 return; 2343 2344 // C++0x [dcl.typedef]p4: 2345 // In a given class scope, a typedef specifier can be used to redefine 2346 // any class-name declared in that scope that is not also a typedef-name 2347 // to refer to the type to which it already refers. 2348 // 2349 // This wording came in via DR424, which was a correction to the 2350 // wording in DR56, which accidentally banned code like: 2351 // 2352 // struct S { 2353 // typedef struct A { } A; 2354 // }; 2355 // 2356 // in the C++03 standard. We implement the C++0x semantics, which 2357 // allow the above but disallow 2358 // 2359 // struct S { 2360 // typedef int I; 2361 // typedef int I; 2362 // }; 2363 // 2364 // since that was the intent of DR56. 2365 if (!isa<TypedefNameDecl>(Old)) 2366 return; 2367 2368 Diag(New->getLocation(), diag::err_redefinition) 2369 << New->getDeclName(); 2370 notePreviousDefinition(Old, New->getLocation()); 2371 return New->setInvalidDecl(); 2372 } 2373 2374 // Modules always permit redefinition of typedefs, as does C11. 2375 if (getLangOpts().Modules || getLangOpts().C11) 2376 return; 2377 2378 // If we have a redefinition of a typedef in C, emit a warning. This warning 2379 // is normally mapped to an error, but can be controlled with 2380 // -Wtypedef-redefinition. If either the original or the redefinition is 2381 // in a system header, don't emit this for compatibility with GCC. 2382 if (getDiagnostics().getSuppressSystemWarnings() && 2383 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2384 (Old->isImplicit() || 2385 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2386 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2387 return; 2388 2389 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2390 << New->getDeclName(); 2391 notePreviousDefinition(Old, New->getLocation()); 2392 } 2393 2394 /// DeclhasAttr - returns true if decl Declaration already has the target 2395 /// attribute. 2396 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2397 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2398 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2399 for (const auto *i : D->attrs()) 2400 if (i->getKind() == A->getKind()) { 2401 if (Ann) { 2402 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2403 return true; 2404 continue; 2405 } 2406 // FIXME: Don't hardcode this check 2407 if (OA && isa<OwnershipAttr>(i)) 2408 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2409 return true; 2410 } 2411 2412 return false; 2413 } 2414 2415 static bool isAttributeTargetADefinition(Decl *D) { 2416 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2417 return VD->isThisDeclarationADefinition(); 2418 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2419 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2420 return true; 2421 } 2422 2423 /// Merge alignment attributes from \p Old to \p New, taking into account the 2424 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2425 /// 2426 /// \return \c true if any attributes were added to \p New. 2427 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2428 // Look for alignas attributes on Old, and pick out whichever attribute 2429 // specifies the strictest alignment requirement. 2430 AlignedAttr *OldAlignasAttr = nullptr; 2431 AlignedAttr *OldStrictestAlignAttr = nullptr; 2432 unsigned OldAlign = 0; 2433 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2434 // FIXME: We have no way of representing inherited dependent alignments 2435 // in a case like: 2436 // template<int A, int B> struct alignas(A) X; 2437 // template<int A, int B> struct alignas(B) X {}; 2438 // For now, we just ignore any alignas attributes which are not on the 2439 // definition in such a case. 2440 if (I->isAlignmentDependent()) 2441 return false; 2442 2443 if (I->isAlignas()) 2444 OldAlignasAttr = I; 2445 2446 unsigned Align = I->getAlignment(S.Context); 2447 if (Align > OldAlign) { 2448 OldAlign = Align; 2449 OldStrictestAlignAttr = I; 2450 } 2451 } 2452 2453 // Look for alignas attributes on New. 2454 AlignedAttr *NewAlignasAttr = nullptr; 2455 unsigned NewAlign = 0; 2456 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2457 if (I->isAlignmentDependent()) 2458 return false; 2459 2460 if (I->isAlignas()) 2461 NewAlignasAttr = I; 2462 2463 unsigned Align = I->getAlignment(S.Context); 2464 if (Align > NewAlign) 2465 NewAlign = Align; 2466 } 2467 2468 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2469 // Both declarations have 'alignas' attributes. We require them to match. 2470 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2471 // fall short. (If two declarations both have alignas, they must both match 2472 // every definition, and so must match each other if there is a definition.) 2473 2474 // If either declaration only contains 'alignas(0)' specifiers, then it 2475 // specifies the natural alignment for the type. 2476 if (OldAlign == 0 || NewAlign == 0) { 2477 QualType Ty; 2478 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2479 Ty = VD->getType(); 2480 else 2481 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2482 2483 if (OldAlign == 0) 2484 OldAlign = S.Context.getTypeAlign(Ty); 2485 if (NewAlign == 0) 2486 NewAlign = S.Context.getTypeAlign(Ty); 2487 } 2488 2489 if (OldAlign != NewAlign) { 2490 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2491 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2492 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2493 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2494 } 2495 } 2496 2497 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2498 // C++11 [dcl.align]p6: 2499 // if any declaration of an entity has an alignment-specifier, 2500 // every defining declaration of that entity shall specify an 2501 // equivalent alignment. 2502 // C11 6.7.5/7: 2503 // If the definition of an object does not have an alignment 2504 // specifier, any other declaration of that object shall also 2505 // have no alignment specifier. 2506 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2507 << OldAlignasAttr; 2508 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2509 << OldAlignasAttr; 2510 } 2511 2512 bool AnyAdded = false; 2513 2514 // Ensure we have an attribute representing the strictest alignment. 2515 if (OldAlign > NewAlign) { 2516 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2517 Clone->setInherited(true); 2518 New->addAttr(Clone); 2519 AnyAdded = true; 2520 } 2521 2522 // Ensure we have an alignas attribute if the old declaration had one. 2523 if (OldAlignasAttr && !NewAlignasAttr && 2524 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2525 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 return AnyAdded; 2532 } 2533 2534 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2535 const InheritableAttr *Attr, 2536 Sema::AvailabilityMergeKind AMK) { 2537 // This function copies an attribute Attr from a previous declaration to the 2538 // new declaration D if the new declaration doesn't itself have that attribute 2539 // yet or if that attribute allows duplicates. 2540 // If you're adding a new attribute that requires logic different from 2541 // "use explicit attribute on decl if present, else use attribute from 2542 // previous decl", for example if the attribute needs to be consistent 2543 // between redeclarations, you need to call a custom merge function here. 2544 InheritableAttr *NewAttr = nullptr; 2545 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2546 NewAttr = S.mergeAvailabilityAttr( 2547 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2548 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2549 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2550 AA->getPriority()); 2551 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2552 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2553 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2554 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2555 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2556 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2557 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2558 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2559 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2560 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2561 FA->getFirstArg()); 2562 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2563 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2564 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2565 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2566 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2567 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2568 IA->getInheritanceModel()); 2569 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2570 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2571 &S.Context.Idents.get(AA->getSpelling())); 2572 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2573 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2574 isa<CUDAGlobalAttr>(Attr))) { 2575 // CUDA target attributes are part of function signature for 2576 // overloading purposes and must not be merged. 2577 return false; 2578 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2579 NewAttr = S.mergeMinSizeAttr(D, *MA); 2580 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2581 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2582 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2583 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2584 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2585 NewAttr = S.mergeCommonAttr(D, *CommonA); 2586 else if (isa<AlignedAttr>(Attr)) 2587 // AlignedAttrs are handled separately, because we need to handle all 2588 // such attributes on a declaration at the same time. 2589 NewAttr = nullptr; 2590 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2591 (AMK == Sema::AMK_Override || 2592 AMK == Sema::AMK_ProtocolImplementation)) 2593 NewAttr = nullptr; 2594 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2595 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2596 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2597 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2598 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2599 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2600 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2601 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2602 2603 if (NewAttr) { 2604 NewAttr->setInherited(true); 2605 D->addAttr(NewAttr); 2606 if (isa<MSInheritanceAttr>(NewAttr)) 2607 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2608 return true; 2609 } 2610 2611 return false; 2612 } 2613 2614 static const NamedDecl *getDefinition(const Decl *D) { 2615 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2616 return TD->getDefinition(); 2617 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2618 const VarDecl *Def = VD->getDefinition(); 2619 if (Def) 2620 return Def; 2621 return VD->getActingDefinition(); 2622 } 2623 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2624 return FD->getDefinition(); 2625 return nullptr; 2626 } 2627 2628 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2629 for (const auto *Attribute : D->attrs()) 2630 if (Attribute->getKind() == Kind) 2631 return true; 2632 return false; 2633 } 2634 2635 /// checkNewAttributesAfterDef - If we already have a definition, check that 2636 /// there are no new attributes in this declaration. 2637 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2638 if (!New->hasAttrs()) 2639 return; 2640 2641 const NamedDecl *Def = getDefinition(Old); 2642 if (!Def || Def == New) 2643 return; 2644 2645 AttrVec &NewAttributes = New->getAttrs(); 2646 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2647 const Attr *NewAttribute = NewAttributes[I]; 2648 2649 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2651 Sema::SkipBodyInfo SkipBody; 2652 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2653 2654 // If we're skipping this definition, drop the "alias" attribute. 2655 if (SkipBody.ShouldSkip) { 2656 NewAttributes.erase(NewAttributes.begin() + I); 2657 --E; 2658 continue; 2659 } 2660 } else { 2661 VarDecl *VD = cast<VarDecl>(New); 2662 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2663 VarDecl::TentativeDefinition 2664 ? diag::err_alias_after_tentative 2665 : diag::err_redefinition; 2666 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2667 if (Diag == diag::err_redefinition) 2668 S.notePreviousDefinition(Def, VD->getLocation()); 2669 else 2670 S.Diag(Def->getLocation(), diag::note_previous_definition); 2671 VD->setInvalidDecl(); 2672 } 2673 ++I; 2674 continue; 2675 } 2676 2677 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2678 // Tentative definitions are only interesting for the alias check above. 2679 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2680 ++I; 2681 continue; 2682 } 2683 } 2684 2685 if (hasAttribute(Def, NewAttribute->getKind())) { 2686 ++I; 2687 continue; // regular attr merging will take care of validating this. 2688 } 2689 2690 if (isa<C11NoReturnAttr>(NewAttribute)) { 2691 // C's _Noreturn is allowed to be added to a function after it is defined. 2692 ++I; 2693 continue; 2694 } else if (isa<UuidAttr>(NewAttribute)) { 2695 // msvc will allow a subsequent definition to add an uuid to a class 2696 ++I; 2697 continue; 2698 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2699 if (AA->isAlignas()) { 2700 // C++11 [dcl.align]p6: 2701 // if any declaration of an entity has an alignment-specifier, 2702 // every defining declaration of that entity shall specify an 2703 // equivalent alignment. 2704 // C11 6.7.5/7: 2705 // If the definition of an object does not have an alignment 2706 // specifier, any other declaration of that object shall also 2707 // have no alignment specifier. 2708 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2709 << AA; 2710 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2711 << AA; 2712 NewAttributes.erase(NewAttributes.begin() + I); 2713 --E; 2714 continue; 2715 } 2716 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2717 // If there is a C definition followed by a redeclaration with this 2718 // attribute then there are two different definitions. In C++, prefer the 2719 // standard diagnostics. 2720 if (!S.getLangOpts().CPlusPlus) { 2721 S.Diag(NewAttribute->getLocation(), 2722 diag::err_loader_uninitialized_redeclaration); 2723 S.Diag(Def->getLocation(), diag::note_previous_definition); 2724 NewAttributes.erase(NewAttributes.begin() + I); 2725 --E; 2726 continue; 2727 } 2728 } else if (isa<SelectAnyAttr>(NewAttribute) && 2729 cast<VarDecl>(New)->isInline() && 2730 !cast<VarDecl>(New)->isInlineSpecified()) { 2731 // Don't warn about applying selectany to implicitly inline variables. 2732 // Older compilers and language modes would require the use of selectany 2733 // to make such variables inline, and it would have no effect if we 2734 // honored it. 2735 ++I; 2736 continue; 2737 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2738 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2739 // declarations after defintions. 2740 ++I; 2741 continue; 2742 } 2743 2744 S.Diag(NewAttribute->getLocation(), 2745 diag::warn_attribute_precede_definition); 2746 S.Diag(Def->getLocation(), diag::note_previous_definition); 2747 NewAttributes.erase(NewAttributes.begin() + I); 2748 --E; 2749 } 2750 } 2751 2752 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2753 const ConstInitAttr *CIAttr, 2754 bool AttrBeforeInit) { 2755 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2756 2757 // Figure out a good way to write this specifier on the old declaration. 2758 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2759 // enough of the attribute list spelling information to extract that without 2760 // heroics. 2761 std::string SuitableSpelling; 2762 if (S.getLangOpts().CPlusPlus20) 2763 SuitableSpelling = std::string( 2764 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2765 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2766 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2767 InsertLoc, {tok::l_square, tok::l_square, 2768 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2769 S.PP.getIdentifierInfo("require_constant_initialization"), 2770 tok::r_square, tok::r_square})); 2771 if (SuitableSpelling.empty()) 2772 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2773 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2774 S.PP.getIdentifierInfo("require_constant_initialization"), 2775 tok::r_paren, tok::r_paren})); 2776 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2777 SuitableSpelling = "constinit"; 2778 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2779 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2780 if (SuitableSpelling.empty()) 2781 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2782 SuitableSpelling += " "; 2783 2784 if (AttrBeforeInit) { 2785 // extern constinit int a; 2786 // int a = 0; // error (missing 'constinit'), accepted as extension 2787 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2788 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2789 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2790 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2791 } else { 2792 // int a = 0; 2793 // constinit extern int a; // error (missing 'constinit') 2794 S.Diag(CIAttr->getLocation(), 2795 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2796 : diag::warn_require_const_init_added_too_late) 2797 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2798 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2799 << CIAttr->isConstinit() 2800 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2801 } 2802 } 2803 2804 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2805 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2806 AvailabilityMergeKind AMK) { 2807 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2808 UsedAttr *NewAttr = OldAttr->clone(Context); 2809 NewAttr->setInherited(true); 2810 New->addAttr(NewAttr); 2811 } 2812 2813 if (!Old->hasAttrs() && !New->hasAttrs()) 2814 return; 2815 2816 // [dcl.constinit]p1: 2817 // If the [constinit] specifier is applied to any declaration of a 2818 // variable, it shall be applied to the initializing declaration. 2819 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2820 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2821 if (bool(OldConstInit) != bool(NewConstInit)) { 2822 const auto *OldVD = cast<VarDecl>(Old); 2823 auto *NewVD = cast<VarDecl>(New); 2824 2825 // Find the initializing declaration. Note that we might not have linked 2826 // the new declaration into the redeclaration chain yet. 2827 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2828 if (!InitDecl && 2829 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2830 InitDecl = NewVD; 2831 2832 if (InitDecl == NewVD) { 2833 // This is the initializing declaration. If it would inherit 'constinit', 2834 // that's ill-formed. (Note that we do not apply this to the attribute 2835 // form). 2836 if (OldConstInit && OldConstInit->isConstinit()) 2837 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2838 /*AttrBeforeInit=*/true); 2839 } else if (NewConstInit) { 2840 // This is the first time we've been told that this declaration should 2841 // have a constant initializer. If we already saw the initializing 2842 // declaration, this is too late. 2843 if (InitDecl && InitDecl != NewVD) { 2844 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2845 /*AttrBeforeInit=*/false); 2846 NewVD->dropAttr<ConstInitAttr>(); 2847 } 2848 } 2849 } 2850 2851 // Attributes declared post-definition are currently ignored. 2852 checkNewAttributesAfterDef(*this, New, Old); 2853 2854 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2855 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2856 if (!OldA->isEquivalent(NewA)) { 2857 // This redeclaration changes __asm__ label. 2858 Diag(New->getLocation(), diag::err_different_asm_label); 2859 Diag(OldA->getLocation(), diag::note_previous_declaration); 2860 } 2861 } else if (Old->isUsed()) { 2862 // This redeclaration adds an __asm__ label to a declaration that has 2863 // already been ODR-used. 2864 Diag(New->getLocation(), diag::err_late_asm_label_name) 2865 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2866 } 2867 } 2868 2869 // Re-declaration cannot add abi_tag's. 2870 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2871 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2872 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2873 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2874 NewTag) == OldAbiTagAttr->tags_end()) { 2875 Diag(NewAbiTagAttr->getLocation(), 2876 diag::err_new_abi_tag_on_redeclaration) 2877 << NewTag; 2878 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2879 } 2880 } 2881 } else { 2882 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2883 Diag(Old->getLocation(), diag::note_previous_declaration); 2884 } 2885 } 2886 2887 // This redeclaration adds a section attribute. 2888 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2889 if (auto *VD = dyn_cast<VarDecl>(New)) { 2890 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2891 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2892 Diag(Old->getLocation(), diag::note_previous_declaration); 2893 } 2894 } 2895 } 2896 2897 // Redeclaration adds code-seg attribute. 2898 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2899 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2900 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2901 Diag(New->getLocation(), diag::warn_mismatched_section) 2902 << 0 /*codeseg*/; 2903 Diag(Old->getLocation(), diag::note_previous_declaration); 2904 } 2905 2906 if (!Old->hasAttrs()) 2907 return; 2908 2909 bool foundAny = New->hasAttrs(); 2910 2911 // Ensure that any moving of objects within the allocated map is done before 2912 // we process them. 2913 if (!foundAny) New->setAttrs(AttrVec()); 2914 2915 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2916 // Ignore deprecated/unavailable/availability attributes if requested. 2917 AvailabilityMergeKind LocalAMK = AMK_None; 2918 if (isa<DeprecatedAttr>(I) || 2919 isa<UnavailableAttr>(I) || 2920 isa<AvailabilityAttr>(I)) { 2921 switch (AMK) { 2922 case AMK_None: 2923 continue; 2924 2925 case AMK_Redeclaration: 2926 case AMK_Override: 2927 case AMK_ProtocolImplementation: 2928 LocalAMK = AMK; 2929 break; 2930 } 2931 } 2932 2933 // Already handled. 2934 if (isa<UsedAttr>(I)) 2935 continue; 2936 2937 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2938 foundAny = true; 2939 } 2940 2941 if (mergeAlignedAttrs(*this, New, Old)) 2942 foundAny = true; 2943 2944 if (!foundAny) New->dropAttrs(); 2945 } 2946 2947 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2948 /// to the new one. 2949 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2950 const ParmVarDecl *oldDecl, 2951 Sema &S) { 2952 // C++11 [dcl.attr.depend]p2: 2953 // The first declaration of a function shall specify the 2954 // carries_dependency attribute for its declarator-id if any declaration 2955 // of the function specifies the carries_dependency attribute. 2956 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2957 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2958 S.Diag(CDA->getLocation(), 2959 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2960 // Find the first declaration of the parameter. 2961 // FIXME: Should we build redeclaration chains for function parameters? 2962 const FunctionDecl *FirstFD = 2963 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2964 const ParmVarDecl *FirstVD = 2965 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2966 S.Diag(FirstVD->getLocation(), 2967 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2968 } 2969 2970 if (!oldDecl->hasAttrs()) 2971 return; 2972 2973 bool foundAny = newDecl->hasAttrs(); 2974 2975 // Ensure that any moving of objects within the allocated map is 2976 // done before we process them. 2977 if (!foundAny) newDecl->setAttrs(AttrVec()); 2978 2979 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2980 if (!DeclHasAttr(newDecl, I)) { 2981 InheritableAttr *newAttr = 2982 cast<InheritableParamAttr>(I->clone(S.Context)); 2983 newAttr->setInherited(true); 2984 newDecl->addAttr(newAttr); 2985 foundAny = true; 2986 } 2987 } 2988 2989 if (!foundAny) newDecl->dropAttrs(); 2990 } 2991 2992 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2993 const ParmVarDecl *OldParam, 2994 Sema &S) { 2995 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2996 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2997 if (*Oldnullability != *Newnullability) { 2998 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2999 << DiagNullabilityKind( 3000 *Newnullability, 3001 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3002 != 0)) 3003 << DiagNullabilityKind( 3004 *Oldnullability, 3005 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3006 != 0)); 3007 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3008 } 3009 } else { 3010 QualType NewT = NewParam->getType(); 3011 NewT = S.Context.getAttributedType( 3012 AttributedType::getNullabilityAttrKind(*Oldnullability), 3013 NewT, NewT); 3014 NewParam->setType(NewT); 3015 } 3016 } 3017 } 3018 3019 namespace { 3020 3021 /// Used in MergeFunctionDecl to keep track of function parameters in 3022 /// C. 3023 struct GNUCompatibleParamWarning { 3024 ParmVarDecl *OldParm; 3025 ParmVarDecl *NewParm; 3026 QualType PromotedType; 3027 }; 3028 3029 } // end anonymous namespace 3030 3031 // Determine whether the previous declaration was a definition, implicit 3032 // declaration, or a declaration. 3033 template <typename T> 3034 static std::pair<diag::kind, SourceLocation> 3035 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3036 diag::kind PrevDiag; 3037 SourceLocation OldLocation = Old->getLocation(); 3038 if (Old->isThisDeclarationADefinition()) 3039 PrevDiag = diag::note_previous_definition; 3040 else if (Old->isImplicit()) { 3041 PrevDiag = diag::note_previous_implicit_declaration; 3042 if (OldLocation.isInvalid()) 3043 OldLocation = New->getLocation(); 3044 } else 3045 PrevDiag = diag::note_previous_declaration; 3046 return std::make_pair(PrevDiag, OldLocation); 3047 } 3048 3049 /// canRedefineFunction - checks if a function can be redefined. Currently, 3050 /// only extern inline functions can be redefined, and even then only in 3051 /// GNU89 mode. 3052 static bool canRedefineFunction(const FunctionDecl *FD, 3053 const LangOptions& LangOpts) { 3054 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3055 !LangOpts.CPlusPlus && 3056 FD->isInlineSpecified() && 3057 FD->getStorageClass() == SC_Extern); 3058 } 3059 3060 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3061 const AttributedType *AT = T->getAs<AttributedType>(); 3062 while (AT && !AT->isCallingConv()) 3063 AT = AT->getModifiedType()->getAs<AttributedType>(); 3064 return AT; 3065 } 3066 3067 template <typename T> 3068 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3069 const DeclContext *DC = Old->getDeclContext(); 3070 if (DC->isRecord()) 3071 return false; 3072 3073 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3074 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3075 return true; 3076 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3077 return true; 3078 return false; 3079 } 3080 3081 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3082 static bool isExternC(VarTemplateDecl *) { return false; } 3083 3084 /// Check whether a redeclaration of an entity introduced by a 3085 /// using-declaration is valid, given that we know it's not an overload 3086 /// (nor a hidden tag declaration). 3087 template<typename ExpectedDecl> 3088 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3089 ExpectedDecl *New) { 3090 // C++11 [basic.scope.declarative]p4: 3091 // Given a set of declarations in a single declarative region, each of 3092 // which specifies the same unqualified name, 3093 // -- they shall all refer to the same entity, or all refer to functions 3094 // and function templates; or 3095 // -- exactly one declaration shall declare a class name or enumeration 3096 // name that is not a typedef name and the other declarations shall all 3097 // refer to the same variable or enumerator, or all refer to functions 3098 // and function templates; in this case the class name or enumeration 3099 // name is hidden (3.3.10). 3100 3101 // C++11 [namespace.udecl]p14: 3102 // If a function declaration in namespace scope or block scope has the 3103 // same name and the same parameter-type-list as a function introduced 3104 // by a using-declaration, and the declarations do not declare the same 3105 // function, the program is ill-formed. 3106 3107 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3108 if (Old && 3109 !Old->getDeclContext()->getRedeclContext()->Equals( 3110 New->getDeclContext()->getRedeclContext()) && 3111 !(isExternC(Old) && isExternC(New))) 3112 Old = nullptr; 3113 3114 if (!Old) { 3115 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3116 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3117 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3118 return true; 3119 } 3120 return false; 3121 } 3122 3123 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3124 const FunctionDecl *B) { 3125 assert(A->getNumParams() == B->getNumParams()); 3126 3127 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3128 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3129 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3130 if (AttrA == AttrB) 3131 return true; 3132 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3133 AttrA->isDynamic() == AttrB->isDynamic(); 3134 }; 3135 3136 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3137 } 3138 3139 /// If necessary, adjust the semantic declaration context for a qualified 3140 /// declaration to name the correct inline namespace within the qualifier. 3141 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3142 DeclaratorDecl *OldD) { 3143 // The only case where we need to update the DeclContext is when 3144 // redeclaration lookup for a qualified name finds a declaration 3145 // in an inline namespace within the context named by the qualifier: 3146 // 3147 // inline namespace N { int f(); } 3148 // int ::f(); // Sema DC needs adjusting from :: to N::. 3149 // 3150 // For unqualified declarations, the semantic context *can* change 3151 // along the redeclaration chain (for local extern declarations, 3152 // extern "C" declarations, and friend declarations in particular). 3153 if (!NewD->getQualifier()) 3154 return; 3155 3156 // NewD is probably already in the right context. 3157 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3158 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3159 if (NamedDC->Equals(SemaDC)) 3160 return; 3161 3162 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3163 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3164 "unexpected context for redeclaration"); 3165 3166 auto *LexDC = NewD->getLexicalDeclContext(); 3167 auto FixSemaDC = [=](NamedDecl *D) { 3168 if (!D) 3169 return; 3170 D->setDeclContext(SemaDC); 3171 D->setLexicalDeclContext(LexDC); 3172 }; 3173 3174 FixSemaDC(NewD); 3175 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3176 FixSemaDC(FD->getDescribedFunctionTemplate()); 3177 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3178 FixSemaDC(VD->getDescribedVarTemplate()); 3179 } 3180 3181 /// MergeFunctionDecl - We just parsed a function 'New' from 3182 /// declarator D which has the same name and scope as a previous 3183 /// declaration 'Old'. Figure out how to resolve this situation, 3184 /// merging decls or emitting diagnostics as appropriate. 3185 /// 3186 /// In C++, New and Old must be declarations that are not 3187 /// overloaded. Use IsOverload to determine whether New and Old are 3188 /// overloaded, and to select the Old declaration that New should be 3189 /// merged with. 3190 /// 3191 /// Returns true if there was an error, false otherwise. 3192 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3193 Scope *S, bool MergeTypeWithOld) { 3194 // Verify the old decl was also a function. 3195 FunctionDecl *Old = OldD->getAsFunction(); 3196 if (!Old) { 3197 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3198 if (New->getFriendObjectKind()) { 3199 Diag(New->getLocation(), diag::err_using_decl_friend); 3200 Diag(Shadow->getTargetDecl()->getLocation(), 3201 diag::note_using_decl_target); 3202 Diag(Shadow->getUsingDecl()->getLocation(), 3203 diag::note_using_decl) << 0; 3204 return true; 3205 } 3206 3207 // Check whether the two declarations might declare the same function. 3208 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3209 return true; 3210 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3211 } else { 3212 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3213 << New->getDeclName(); 3214 notePreviousDefinition(OldD, New->getLocation()); 3215 return true; 3216 } 3217 } 3218 3219 // If the old declaration is invalid, just give up here. 3220 if (Old->isInvalidDecl()) 3221 return true; 3222 3223 // Disallow redeclaration of some builtins. 3224 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3225 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3226 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3227 << Old << Old->getType(); 3228 return true; 3229 } 3230 3231 diag::kind PrevDiag; 3232 SourceLocation OldLocation; 3233 std::tie(PrevDiag, OldLocation) = 3234 getNoteDiagForInvalidRedeclaration(Old, New); 3235 3236 // Don't complain about this if we're in GNU89 mode and the old function 3237 // is an extern inline function. 3238 // Don't complain about specializations. They are not supposed to have 3239 // storage classes. 3240 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3241 New->getStorageClass() == SC_Static && 3242 Old->hasExternalFormalLinkage() && 3243 !New->getTemplateSpecializationInfo() && 3244 !canRedefineFunction(Old, getLangOpts())) { 3245 if (getLangOpts().MicrosoftExt) { 3246 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3247 Diag(OldLocation, PrevDiag); 3248 } else { 3249 Diag(New->getLocation(), diag::err_static_non_static) << New; 3250 Diag(OldLocation, PrevDiag); 3251 return true; 3252 } 3253 } 3254 3255 if (New->hasAttr<InternalLinkageAttr>() && 3256 !Old->hasAttr<InternalLinkageAttr>()) { 3257 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3258 << New->getDeclName(); 3259 notePreviousDefinition(Old, New->getLocation()); 3260 New->dropAttr<InternalLinkageAttr>(); 3261 } 3262 3263 if (CheckRedeclarationModuleOwnership(New, Old)) 3264 return true; 3265 3266 if (!getLangOpts().CPlusPlus) { 3267 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3268 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3269 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3270 << New << OldOvl; 3271 3272 // Try our best to find a decl that actually has the overloadable 3273 // attribute for the note. In most cases (e.g. programs with only one 3274 // broken declaration/definition), this won't matter. 3275 // 3276 // FIXME: We could do this if we juggled some extra state in 3277 // OverloadableAttr, rather than just removing it. 3278 const Decl *DiagOld = Old; 3279 if (OldOvl) { 3280 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3281 const auto *A = D->getAttr<OverloadableAttr>(); 3282 return A && !A->isImplicit(); 3283 }); 3284 // If we've implicitly added *all* of the overloadable attrs to this 3285 // chain, emitting a "previous redecl" note is pointless. 3286 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3287 } 3288 3289 if (DiagOld) 3290 Diag(DiagOld->getLocation(), 3291 diag::note_attribute_overloadable_prev_overload) 3292 << OldOvl; 3293 3294 if (OldOvl) 3295 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3296 else 3297 New->dropAttr<OverloadableAttr>(); 3298 } 3299 } 3300 3301 // If a function is first declared with a calling convention, but is later 3302 // declared or defined without one, all following decls assume the calling 3303 // convention of the first. 3304 // 3305 // It's OK if a function is first declared without a calling convention, 3306 // but is later declared or defined with the default calling convention. 3307 // 3308 // To test if either decl has an explicit calling convention, we look for 3309 // AttributedType sugar nodes on the type as written. If they are missing or 3310 // were canonicalized away, we assume the calling convention was implicit. 3311 // 3312 // Note also that we DO NOT return at this point, because we still have 3313 // other tests to run. 3314 QualType OldQType = Context.getCanonicalType(Old->getType()); 3315 QualType NewQType = Context.getCanonicalType(New->getType()); 3316 const FunctionType *OldType = cast<FunctionType>(OldQType); 3317 const FunctionType *NewType = cast<FunctionType>(NewQType); 3318 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3319 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3320 bool RequiresAdjustment = false; 3321 3322 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3323 FunctionDecl *First = Old->getFirstDecl(); 3324 const FunctionType *FT = 3325 First->getType().getCanonicalType()->castAs<FunctionType>(); 3326 FunctionType::ExtInfo FI = FT->getExtInfo(); 3327 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3328 if (!NewCCExplicit) { 3329 // Inherit the CC from the previous declaration if it was specified 3330 // there but not here. 3331 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3332 RequiresAdjustment = true; 3333 } else if (New->getBuiltinID()) { 3334 // Calling Conventions on a Builtin aren't really useful and setting a 3335 // default calling convention and cdecl'ing some builtin redeclarations is 3336 // common, so warn and ignore the calling convention on the redeclaration. 3337 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3338 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3339 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3340 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3341 RequiresAdjustment = true; 3342 } else { 3343 // Calling conventions aren't compatible, so complain. 3344 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3345 Diag(New->getLocation(), diag::err_cconv_change) 3346 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3347 << !FirstCCExplicit 3348 << (!FirstCCExplicit ? "" : 3349 FunctionType::getNameForCallConv(FI.getCC())); 3350 3351 // Put the note on the first decl, since it is the one that matters. 3352 Diag(First->getLocation(), diag::note_previous_declaration); 3353 return true; 3354 } 3355 } 3356 3357 // FIXME: diagnose the other way around? 3358 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3359 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3360 RequiresAdjustment = true; 3361 } 3362 3363 // Merge regparm attribute. 3364 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3365 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3366 if (NewTypeInfo.getHasRegParm()) { 3367 Diag(New->getLocation(), diag::err_regparm_mismatch) 3368 << NewType->getRegParmType() 3369 << OldType->getRegParmType(); 3370 Diag(OldLocation, diag::note_previous_declaration); 3371 return true; 3372 } 3373 3374 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3375 RequiresAdjustment = true; 3376 } 3377 3378 // Merge ns_returns_retained attribute. 3379 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3380 if (NewTypeInfo.getProducesResult()) { 3381 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3382 << "'ns_returns_retained'"; 3383 Diag(OldLocation, diag::note_previous_declaration); 3384 return true; 3385 } 3386 3387 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3388 RequiresAdjustment = true; 3389 } 3390 3391 if (OldTypeInfo.getNoCallerSavedRegs() != 3392 NewTypeInfo.getNoCallerSavedRegs()) { 3393 if (NewTypeInfo.getNoCallerSavedRegs()) { 3394 AnyX86NoCallerSavedRegistersAttr *Attr = 3395 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3396 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3397 Diag(OldLocation, diag::note_previous_declaration); 3398 return true; 3399 } 3400 3401 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3402 RequiresAdjustment = true; 3403 } 3404 3405 if (RequiresAdjustment) { 3406 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3407 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3408 New->setType(QualType(AdjustedType, 0)); 3409 NewQType = Context.getCanonicalType(New->getType()); 3410 } 3411 3412 // If this redeclaration makes the function inline, we may need to add it to 3413 // UndefinedButUsed. 3414 if (!Old->isInlined() && New->isInlined() && 3415 !New->hasAttr<GNUInlineAttr>() && 3416 !getLangOpts().GNUInline && 3417 Old->isUsed(false) && 3418 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3419 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3420 SourceLocation())); 3421 3422 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3423 // about it. 3424 if (New->hasAttr<GNUInlineAttr>() && 3425 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3426 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3427 } 3428 3429 // If pass_object_size params don't match up perfectly, this isn't a valid 3430 // redeclaration. 3431 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3432 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3433 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3434 << New->getDeclName(); 3435 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3436 return true; 3437 } 3438 3439 if (getLangOpts().CPlusPlus) { 3440 // C++1z [over.load]p2 3441 // Certain function declarations cannot be overloaded: 3442 // -- Function declarations that differ only in the return type, 3443 // the exception specification, or both cannot be overloaded. 3444 3445 // Check the exception specifications match. This may recompute the type of 3446 // both Old and New if it resolved exception specifications, so grab the 3447 // types again after this. Because this updates the type, we do this before 3448 // any of the other checks below, which may update the "de facto" NewQType 3449 // but do not necessarily update the type of New. 3450 if (CheckEquivalentExceptionSpec(Old, New)) 3451 return true; 3452 OldQType = Context.getCanonicalType(Old->getType()); 3453 NewQType = Context.getCanonicalType(New->getType()); 3454 3455 // Go back to the type source info to compare the declared return types, 3456 // per C++1y [dcl.type.auto]p13: 3457 // Redeclarations or specializations of a function or function template 3458 // with a declared return type that uses a placeholder type shall also 3459 // use that placeholder, not a deduced type. 3460 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3461 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3462 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3463 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3464 OldDeclaredReturnType)) { 3465 QualType ResQT; 3466 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3467 OldDeclaredReturnType->isObjCObjectPointerType()) 3468 // FIXME: This does the wrong thing for a deduced return type. 3469 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3470 if (ResQT.isNull()) { 3471 if (New->isCXXClassMember() && New->isOutOfLine()) 3472 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3473 << New << New->getReturnTypeSourceRange(); 3474 else 3475 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3476 << New->getReturnTypeSourceRange(); 3477 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3478 << Old->getReturnTypeSourceRange(); 3479 return true; 3480 } 3481 else 3482 NewQType = ResQT; 3483 } 3484 3485 QualType OldReturnType = OldType->getReturnType(); 3486 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3487 if (OldReturnType != NewReturnType) { 3488 // If this function has a deduced return type and has already been 3489 // defined, copy the deduced value from the old declaration. 3490 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3491 if (OldAT && OldAT->isDeduced()) { 3492 New->setType( 3493 SubstAutoType(New->getType(), 3494 OldAT->isDependentType() ? Context.DependentTy 3495 : OldAT->getDeducedType())); 3496 NewQType = Context.getCanonicalType( 3497 SubstAutoType(NewQType, 3498 OldAT->isDependentType() ? Context.DependentTy 3499 : OldAT->getDeducedType())); 3500 } 3501 } 3502 3503 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3504 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3505 if (OldMethod && NewMethod) { 3506 // Preserve triviality. 3507 NewMethod->setTrivial(OldMethod->isTrivial()); 3508 3509 // MSVC allows explicit template specialization at class scope: 3510 // 2 CXXMethodDecls referring to the same function will be injected. 3511 // We don't want a redeclaration error. 3512 bool IsClassScopeExplicitSpecialization = 3513 OldMethod->isFunctionTemplateSpecialization() && 3514 NewMethod->isFunctionTemplateSpecialization(); 3515 bool isFriend = NewMethod->getFriendObjectKind(); 3516 3517 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3518 !IsClassScopeExplicitSpecialization) { 3519 // -- Member function declarations with the same name and the 3520 // same parameter types cannot be overloaded if any of them 3521 // is a static member function declaration. 3522 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3523 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3524 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3525 return true; 3526 } 3527 3528 // C++ [class.mem]p1: 3529 // [...] A member shall not be declared twice in the 3530 // member-specification, except that a nested class or member 3531 // class template can be declared and then later defined. 3532 if (!inTemplateInstantiation()) { 3533 unsigned NewDiag; 3534 if (isa<CXXConstructorDecl>(OldMethod)) 3535 NewDiag = diag::err_constructor_redeclared; 3536 else if (isa<CXXDestructorDecl>(NewMethod)) 3537 NewDiag = diag::err_destructor_redeclared; 3538 else if (isa<CXXConversionDecl>(NewMethod)) 3539 NewDiag = diag::err_conv_function_redeclared; 3540 else 3541 NewDiag = diag::err_member_redeclared; 3542 3543 Diag(New->getLocation(), NewDiag); 3544 } else { 3545 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3546 << New << New->getType(); 3547 } 3548 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3549 return true; 3550 3551 // Complain if this is an explicit declaration of a special 3552 // member that was initially declared implicitly. 3553 // 3554 // As an exception, it's okay to befriend such methods in order 3555 // to permit the implicit constructor/destructor/operator calls. 3556 } else if (OldMethod->isImplicit()) { 3557 if (isFriend) { 3558 NewMethod->setImplicit(); 3559 } else { 3560 Diag(NewMethod->getLocation(), 3561 diag::err_definition_of_implicitly_declared_member) 3562 << New << getSpecialMember(OldMethod); 3563 return true; 3564 } 3565 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3566 Diag(NewMethod->getLocation(), 3567 diag::err_definition_of_explicitly_defaulted_member) 3568 << getSpecialMember(OldMethod); 3569 return true; 3570 } 3571 } 3572 3573 // C++11 [dcl.attr.noreturn]p1: 3574 // The first declaration of a function shall specify the noreturn 3575 // attribute if any declaration of that function specifies the noreturn 3576 // attribute. 3577 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3578 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3579 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3580 Diag(Old->getFirstDecl()->getLocation(), 3581 diag::note_noreturn_missing_first_decl); 3582 } 3583 3584 // C++11 [dcl.attr.depend]p2: 3585 // The first declaration of a function shall specify the 3586 // carries_dependency attribute for its declarator-id if any declaration 3587 // of the function specifies the carries_dependency attribute. 3588 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3589 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3590 Diag(CDA->getLocation(), 3591 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3592 Diag(Old->getFirstDecl()->getLocation(), 3593 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3594 } 3595 3596 // (C++98 8.3.5p3): 3597 // All declarations for a function shall agree exactly in both the 3598 // return type and the parameter-type-list. 3599 // We also want to respect all the extended bits except noreturn. 3600 3601 // noreturn should now match unless the old type info didn't have it. 3602 QualType OldQTypeForComparison = OldQType; 3603 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3604 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3605 const FunctionType *OldTypeForComparison 3606 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3607 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3608 assert(OldQTypeForComparison.isCanonical()); 3609 } 3610 3611 if (haveIncompatibleLanguageLinkages(Old, New)) { 3612 // As a special case, retain the language linkage from previous 3613 // declarations of a friend function as an extension. 3614 // 3615 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3616 // and is useful because there's otherwise no way to specify language 3617 // linkage within class scope. 3618 // 3619 // Check cautiously as the friend object kind isn't yet complete. 3620 if (New->getFriendObjectKind() != Decl::FOK_None) { 3621 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3622 Diag(OldLocation, PrevDiag); 3623 } else { 3624 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3625 Diag(OldLocation, PrevDiag); 3626 return true; 3627 } 3628 } 3629 3630 // If the function types are compatible, merge the declarations. Ignore the 3631 // exception specifier because it was already checked above in 3632 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3633 // about incompatible types under -fms-compatibility. 3634 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3635 NewQType)) 3636 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3637 3638 // If the types are imprecise (due to dependent constructs in friends or 3639 // local extern declarations), it's OK if they differ. We'll check again 3640 // during instantiation. 3641 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3642 return false; 3643 3644 // Fall through for conflicting redeclarations and redefinitions. 3645 } 3646 3647 // C: Function types need to be compatible, not identical. This handles 3648 // duplicate function decls like "void f(int); void f(enum X);" properly. 3649 if (!getLangOpts().CPlusPlus && 3650 Context.typesAreCompatible(OldQType, NewQType)) { 3651 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3652 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3653 const FunctionProtoType *OldProto = nullptr; 3654 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3655 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3656 // The old declaration provided a function prototype, but the 3657 // new declaration does not. Merge in the prototype. 3658 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3659 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3660 NewQType = 3661 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3662 OldProto->getExtProtoInfo()); 3663 New->setType(NewQType); 3664 New->setHasInheritedPrototype(); 3665 3666 // Synthesize parameters with the same types. 3667 SmallVector<ParmVarDecl*, 16> Params; 3668 for (const auto &ParamType : OldProto->param_types()) { 3669 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3670 SourceLocation(), nullptr, 3671 ParamType, /*TInfo=*/nullptr, 3672 SC_None, nullptr); 3673 Param->setScopeInfo(0, Params.size()); 3674 Param->setImplicit(); 3675 Params.push_back(Param); 3676 } 3677 3678 New->setParams(Params); 3679 } 3680 3681 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3682 } 3683 3684 // Check if the function types are compatible when pointer size address 3685 // spaces are ignored. 3686 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3687 return false; 3688 3689 // GNU C permits a K&R definition to follow a prototype declaration 3690 // if the declared types of the parameters in the K&R definition 3691 // match the types in the prototype declaration, even when the 3692 // promoted types of the parameters from the K&R definition differ 3693 // from the types in the prototype. GCC then keeps the types from 3694 // the prototype. 3695 // 3696 // If a variadic prototype is followed by a non-variadic K&R definition, 3697 // the K&R definition becomes variadic. This is sort of an edge case, but 3698 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3699 // C99 6.9.1p8. 3700 if (!getLangOpts().CPlusPlus && 3701 Old->hasPrototype() && !New->hasPrototype() && 3702 New->getType()->getAs<FunctionProtoType>() && 3703 Old->getNumParams() == New->getNumParams()) { 3704 SmallVector<QualType, 16> ArgTypes; 3705 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3706 const FunctionProtoType *OldProto 3707 = Old->getType()->getAs<FunctionProtoType>(); 3708 const FunctionProtoType *NewProto 3709 = New->getType()->getAs<FunctionProtoType>(); 3710 3711 // Determine whether this is the GNU C extension. 3712 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3713 NewProto->getReturnType()); 3714 bool LooseCompatible = !MergedReturn.isNull(); 3715 for (unsigned Idx = 0, End = Old->getNumParams(); 3716 LooseCompatible && Idx != End; ++Idx) { 3717 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3718 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3719 if (Context.typesAreCompatible(OldParm->getType(), 3720 NewProto->getParamType(Idx))) { 3721 ArgTypes.push_back(NewParm->getType()); 3722 } else if (Context.typesAreCompatible(OldParm->getType(), 3723 NewParm->getType(), 3724 /*CompareUnqualified=*/true)) { 3725 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3726 NewProto->getParamType(Idx) }; 3727 Warnings.push_back(Warn); 3728 ArgTypes.push_back(NewParm->getType()); 3729 } else 3730 LooseCompatible = false; 3731 } 3732 3733 if (LooseCompatible) { 3734 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3735 Diag(Warnings[Warn].NewParm->getLocation(), 3736 diag::ext_param_promoted_not_compatible_with_prototype) 3737 << Warnings[Warn].PromotedType 3738 << Warnings[Warn].OldParm->getType(); 3739 if (Warnings[Warn].OldParm->getLocation().isValid()) 3740 Diag(Warnings[Warn].OldParm->getLocation(), 3741 diag::note_previous_declaration); 3742 } 3743 3744 if (MergeTypeWithOld) 3745 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3746 OldProto->getExtProtoInfo())); 3747 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3748 } 3749 3750 // Fall through to diagnose conflicting types. 3751 } 3752 3753 // A function that has already been declared has been redeclared or 3754 // defined with a different type; show an appropriate diagnostic. 3755 3756 // If the previous declaration was an implicitly-generated builtin 3757 // declaration, then at the very least we should use a specialized note. 3758 unsigned BuiltinID; 3759 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3760 // If it's actually a library-defined builtin function like 'malloc' 3761 // or 'printf', just warn about the incompatible redeclaration. 3762 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3763 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3764 Diag(OldLocation, diag::note_previous_builtin_declaration) 3765 << Old << Old->getType(); 3766 3767 // If this is a global redeclaration, just forget hereafter 3768 // about the "builtin-ness" of the function. 3769 // 3770 // Doing this for local extern declarations is problematic. If 3771 // the builtin declaration remains visible, a second invalid 3772 // local declaration will produce a hard error; if it doesn't 3773 // remain visible, a single bogus local redeclaration (which is 3774 // actually only a warning) could break all the downstream code. 3775 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3776 New->getIdentifier()->revertBuiltin(); 3777 3778 return false; 3779 } 3780 3781 PrevDiag = diag::note_previous_builtin_declaration; 3782 } 3783 3784 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3785 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3786 return true; 3787 } 3788 3789 /// Completes the merge of two function declarations that are 3790 /// known to be compatible. 3791 /// 3792 /// This routine handles the merging of attributes and other 3793 /// properties of function declarations from the old declaration to 3794 /// the new declaration, once we know that New is in fact a 3795 /// redeclaration of Old. 3796 /// 3797 /// \returns false 3798 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3799 Scope *S, bool MergeTypeWithOld) { 3800 // Merge the attributes 3801 mergeDeclAttributes(New, Old); 3802 3803 // Merge "pure" flag. 3804 if (Old->isPure()) 3805 New->setPure(); 3806 3807 // Merge "used" flag. 3808 if (Old->getMostRecentDecl()->isUsed(false)) 3809 New->setIsUsed(); 3810 3811 // Merge attributes from the parameters. These can mismatch with K&R 3812 // declarations. 3813 if (New->getNumParams() == Old->getNumParams()) 3814 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3815 ParmVarDecl *NewParam = New->getParamDecl(i); 3816 ParmVarDecl *OldParam = Old->getParamDecl(i); 3817 mergeParamDeclAttributes(NewParam, OldParam, *this); 3818 mergeParamDeclTypes(NewParam, OldParam, *this); 3819 } 3820 3821 if (getLangOpts().CPlusPlus) 3822 return MergeCXXFunctionDecl(New, Old, S); 3823 3824 // Merge the function types so the we get the composite types for the return 3825 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3826 // was visible. 3827 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3828 if (!Merged.isNull() && MergeTypeWithOld) 3829 New->setType(Merged); 3830 3831 return false; 3832 } 3833 3834 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3835 ObjCMethodDecl *oldMethod) { 3836 // Merge the attributes, including deprecated/unavailable 3837 AvailabilityMergeKind MergeKind = 3838 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3839 ? AMK_ProtocolImplementation 3840 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3841 : AMK_Override; 3842 3843 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3844 3845 // Merge attributes from the parameters. 3846 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3847 oe = oldMethod->param_end(); 3848 for (ObjCMethodDecl::param_iterator 3849 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3850 ni != ne && oi != oe; ++ni, ++oi) 3851 mergeParamDeclAttributes(*ni, *oi, *this); 3852 3853 CheckObjCMethodOverride(newMethod, oldMethod); 3854 } 3855 3856 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3857 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3858 3859 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3860 ? diag::err_redefinition_different_type 3861 : diag::err_redeclaration_different_type) 3862 << New->getDeclName() << New->getType() << Old->getType(); 3863 3864 diag::kind PrevDiag; 3865 SourceLocation OldLocation; 3866 std::tie(PrevDiag, OldLocation) 3867 = getNoteDiagForInvalidRedeclaration(Old, New); 3868 S.Diag(OldLocation, PrevDiag); 3869 New->setInvalidDecl(); 3870 } 3871 3872 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3873 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3874 /// emitting diagnostics as appropriate. 3875 /// 3876 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3877 /// to here in AddInitializerToDecl. We can't check them before the initializer 3878 /// is attached. 3879 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3880 bool MergeTypeWithOld) { 3881 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3882 return; 3883 3884 QualType MergedT; 3885 if (getLangOpts().CPlusPlus) { 3886 if (New->getType()->isUndeducedType()) { 3887 // We don't know what the new type is until the initializer is attached. 3888 return; 3889 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3890 // These could still be something that needs exception specs checked. 3891 return MergeVarDeclExceptionSpecs(New, Old); 3892 } 3893 // C++ [basic.link]p10: 3894 // [...] the types specified by all declarations referring to a given 3895 // object or function shall be identical, except that declarations for an 3896 // array object can specify array types that differ by the presence or 3897 // absence of a major array bound (8.3.4). 3898 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3899 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3900 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3901 3902 // We are merging a variable declaration New into Old. If it has an array 3903 // bound, and that bound differs from Old's bound, we should diagnose the 3904 // mismatch. 3905 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3906 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3907 PrevVD = PrevVD->getPreviousDecl()) { 3908 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3909 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3910 continue; 3911 3912 if (!Context.hasSameType(NewArray, PrevVDTy)) 3913 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3914 } 3915 } 3916 3917 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3918 if (Context.hasSameType(OldArray->getElementType(), 3919 NewArray->getElementType())) 3920 MergedT = New->getType(); 3921 } 3922 // FIXME: Check visibility. New is hidden but has a complete type. If New 3923 // has no array bound, it should not inherit one from Old, if Old is not 3924 // visible. 3925 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3926 if (Context.hasSameType(OldArray->getElementType(), 3927 NewArray->getElementType())) 3928 MergedT = Old->getType(); 3929 } 3930 } 3931 else if (New->getType()->isObjCObjectPointerType() && 3932 Old->getType()->isObjCObjectPointerType()) { 3933 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3934 Old->getType()); 3935 } 3936 } else { 3937 // C 6.2.7p2: 3938 // All declarations that refer to the same object or function shall have 3939 // compatible type. 3940 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3941 } 3942 if (MergedT.isNull()) { 3943 // It's OK if we couldn't merge types if either type is dependent, for a 3944 // block-scope variable. In other cases (static data members of class 3945 // templates, variable templates, ...), we require the types to be 3946 // equivalent. 3947 // FIXME: The C++ standard doesn't say anything about this. 3948 if ((New->getType()->isDependentType() || 3949 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3950 // If the old type was dependent, we can't merge with it, so the new type 3951 // becomes dependent for now. We'll reproduce the original type when we 3952 // instantiate the TypeSourceInfo for the variable. 3953 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3954 New->setType(Context.DependentTy); 3955 return; 3956 } 3957 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3958 } 3959 3960 // Don't actually update the type on the new declaration if the old 3961 // declaration was an extern declaration in a different scope. 3962 if (MergeTypeWithOld) 3963 New->setType(MergedT); 3964 } 3965 3966 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3967 LookupResult &Previous) { 3968 // C11 6.2.7p4: 3969 // For an identifier with internal or external linkage declared 3970 // in a scope in which a prior declaration of that identifier is 3971 // visible, if the prior declaration specifies internal or 3972 // external linkage, the type of the identifier at the later 3973 // declaration becomes the composite type. 3974 // 3975 // If the variable isn't visible, we do not merge with its type. 3976 if (Previous.isShadowed()) 3977 return false; 3978 3979 if (S.getLangOpts().CPlusPlus) { 3980 // C++11 [dcl.array]p3: 3981 // If there is a preceding declaration of the entity in the same 3982 // scope in which the bound was specified, an omitted array bound 3983 // is taken to be the same as in that earlier declaration. 3984 return NewVD->isPreviousDeclInSameBlockScope() || 3985 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3986 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3987 } else { 3988 // If the old declaration was function-local, don't merge with its 3989 // type unless we're in the same function. 3990 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3991 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3992 } 3993 } 3994 3995 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3996 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3997 /// situation, merging decls or emitting diagnostics as appropriate. 3998 /// 3999 /// Tentative definition rules (C99 6.9.2p2) are checked by 4000 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4001 /// definitions here, since the initializer hasn't been attached. 4002 /// 4003 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4004 // If the new decl is already invalid, don't do any other checking. 4005 if (New->isInvalidDecl()) 4006 return; 4007 4008 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4009 return; 4010 4011 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4012 4013 // Verify the old decl was also a variable or variable template. 4014 VarDecl *Old = nullptr; 4015 VarTemplateDecl *OldTemplate = nullptr; 4016 if (Previous.isSingleResult()) { 4017 if (NewTemplate) { 4018 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4019 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4020 4021 if (auto *Shadow = 4022 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4023 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4024 return New->setInvalidDecl(); 4025 } else { 4026 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4027 4028 if (auto *Shadow = 4029 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4030 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4031 return New->setInvalidDecl(); 4032 } 4033 } 4034 if (!Old) { 4035 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4036 << New->getDeclName(); 4037 notePreviousDefinition(Previous.getRepresentativeDecl(), 4038 New->getLocation()); 4039 return New->setInvalidDecl(); 4040 } 4041 4042 // Ensure the template parameters are compatible. 4043 if (NewTemplate && 4044 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4045 OldTemplate->getTemplateParameters(), 4046 /*Complain=*/true, TPL_TemplateMatch)) 4047 return New->setInvalidDecl(); 4048 4049 // C++ [class.mem]p1: 4050 // A member shall not be declared twice in the member-specification [...] 4051 // 4052 // Here, we need only consider static data members. 4053 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4054 Diag(New->getLocation(), diag::err_duplicate_member) 4055 << New->getIdentifier(); 4056 Diag(Old->getLocation(), diag::note_previous_declaration); 4057 New->setInvalidDecl(); 4058 } 4059 4060 mergeDeclAttributes(New, Old); 4061 // Warn if an already-declared variable is made a weak_import in a subsequent 4062 // declaration 4063 if (New->hasAttr<WeakImportAttr>() && 4064 Old->getStorageClass() == SC_None && 4065 !Old->hasAttr<WeakImportAttr>()) { 4066 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4067 notePreviousDefinition(Old, New->getLocation()); 4068 // Remove weak_import attribute on new declaration. 4069 New->dropAttr<WeakImportAttr>(); 4070 } 4071 4072 if (New->hasAttr<InternalLinkageAttr>() && 4073 !Old->hasAttr<InternalLinkageAttr>()) { 4074 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4075 << New->getDeclName(); 4076 notePreviousDefinition(Old, New->getLocation()); 4077 New->dropAttr<InternalLinkageAttr>(); 4078 } 4079 4080 // Merge the types. 4081 VarDecl *MostRecent = Old->getMostRecentDecl(); 4082 if (MostRecent != Old) { 4083 MergeVarDeclTypes(New, MostRecent, 4084 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4085 if (New->isInvalidDecl()) 4086 return; 4087 } 4088 4089 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4090 if (New->isInvalidDecl()) 4091 return; 4092 4093 diag::kind PrevDiag; 4094 SourceLocation OldLocation; 4095 std::tie(PrevDiag, OldLocation) = 4096 getNoteDiagForInvalidRedeclaration(Old, New); 4097 4098 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4099 if (New->getStorageClass() == SC_Static && 4100 !New->isStaticDataMember() && 4101 Old->hasExternalFormalLinkage()) { 4102 if (getLangOpts().MicrosoftExt) { 4103 Diag(New->getLocation(), diag::ext_static_non_static) 4104 << New->getDeclName(); 4105 Diag(OldLocation, PrevDiag); 4106 } else { 4107 Diag(New->getLocation(), diag::err_static_non_static) 4108 << New->getDeclName(); 4109 Diag(OldLocation, PrevDiag); 4110 return New->setInvalidDecl(); 4111 } 4112 } 4113 // C99 6.2.2p4: 4114 // For an identifier declared with the storage-class specifier 4115 // extern in a scope in which a prior declaration of that 4116 // identifier is visible,23) if the prior declaration specifies 4117 // internal or external linkage, the linkage of the identifier at 4118 // the later declaration is the same as the linkage specified at 4119 // the prior declaration. If no prior declaration is visible, or 4120 // if the prior declaration specifies no linkage, then the 4121 // identifier has external linkage. 4122 if (New->hasExternalStorage() && Old->hasLinkage()) 4123 /* Okay */; 4124 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4125 !New->isStaticDataMember() && 4126 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4127 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4128 Diag(OldLocation, PrevDiag); 4129 return New->setInvalidDecl(); 4130 } 4131 4132 // Check if extern is followed by non-extern and vice-versa. 4133 if (New->hasExternalStorage() && 4134 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4135 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4136 Diag(OldLocation, PrevDiag); 4137 return New->setInvalidDecl(); 4138 } 4139 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4140 !New->hasExternalStorage()) { 4141 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4142 Diag(OldLocation, PrevDiag); 4143 return New->setInvalidDecl(); 4144 } 4145 4146 if (CheckRedeclarationModuleOwnership(New, Old)) 4147 return; 4148 4149 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4150 4151 // FIXME: The test for external storage here seems wrong? We still 4152 // need to check for mismatches. 4153 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4154 // Don't complain about out-of-line definitions of static members. 4155 !(Old->getLexicalDeclContext()->isRecord() && 4156 !New->getLexicalDeclContext()->isRecord())) { 4157 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4158 Diag(OldLocation, PrevDiag); 4159 return New->setInvalidDecl(); 4160 } 4161 4162 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4163 if (VarDecl *Def = Old->getDefinition()) { 4164 // C++1z [dcl.fcn.spec]p4: 4165 // If the definition of a variable appears in a translation unit before 4166 // its first declaration as inline, the program is ill-formed. 4167 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4168 Diag(Def->getLocation(), diag::note_previous_definition); 4169 } 4170 } 4171 4172 // If this redeclaration makes the variable inline, we may need to add it to 4173 // UndefinedButUsed. 4174 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4175 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4176 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4177 SourceLocation())); 4178 4179 if (New->getTLSKind() != Old->getTLSKind()) { 4180 if (!Old->getTLSKind()) { 4181 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4182 Diag(OldLocation, PrevDiag); 4183 } else if (!New->getTLSKind()) { 4184 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4185 Diag(OldLocation, PrevDiag); 4186 } else { 4187 // Do not allow redeclaration to change the variable between requiring 4188 // static and dynamic initialization. 4189 // FIXME: GCC allows this, but uses the TLS keyword on the first 4190 // declaration to determine the kind. Do we need to be compatible here? 4191 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4192 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4193 Diag(OldLocation, PrevDiag); 4194 } 4195 } 4196 4197 // C++ doesn't have tentative definitions, so go right ahead and check here. 4198 if (getLangOpts().CPlusPlus && 4199 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4200 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4201 Old->getCanonicalDecl()->isConstexpr()) { 4202 // This definition won't be a definition any more once it's been merged. 4203 Diag(New->getLocation(), 4204 diag::warn_deprecated_redundant_constexpr_static_def); 4205 } else if (VarDecl *Def = Old->getDefinition()) { 4206 if (checkVarDeclRedefinition(Def, New)) 4207 return; 4208 } 4209 } 4210 4211 if (haveIncompatibleLanguageLinkages(Old, New)) { 4212 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4213 Diag(OldLocation, PrevDiag); 4214 New->setInvalidDecl(); 4215 return; 4216 } 4217 4218 // Merge "used" flag. 4219 if (Old->getMostRecentDecl()->isUsed(false)) 4220 New->setIsUsed(); 4221 4222 // Keep a chain of previous declarations. 4223 New->setPreviousDecl(Old); 4224 if (NewTemplate) 4225 NewTemplate->setPreviousDecl(OldTemplate); 4226 adjustDeclContextForDeclaratorDecl(New, Old); 4227 4228 // Inherit access appropriately. 4229 New->setAccess(Old->getAccess()); 4230 if (NewTemplate) 4231 NewTemplate->setAccess(New->getAccess()); 4232 4233 if (Old->isInline()) 4234 New->setImplicitlyInline(); 4235 } 4236 4237 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4238 SourceManager &SrcMgr = getSourceManager(); 4239 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4240 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4241 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4242 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4243 auto &HSI = PP.getHeaderSearchInfo(); 4244 StringRef HdrFilename = 4245 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4246 4247 auto noteFromModuleOrInclude = [&](Module *Mod, 4248 SourceLocation IncLoc) -> bool { 4249 // Redefinition errors with modules are common with non modular mapped 4250 // headers, example: a non-modular header H in module A that also gets 4251 // included directly in a TU. Pointing twice to the same header/definition 4252 // is confusing, try to get better diagnostics when modules is on. 4253 if (IncLoc.isValid()) { 4254 if (Mod) { 4255 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4256 << HdrFilename.str() << Mod->getFullModuleName(); 4257 if (!Mod->DefinitionLoc.isInvalid()) 4258 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4259 << Mod->getFullModuleName(); 4260 } else { 4261 Diag(IncLoc, diag::note_redefinition_include_same_file) 4262 << HdrFilename.str(); 4263 } 4264 return true; 4265 } 4266 4267 return false; 4268 }; 4269 4270 // Is it the same file and same offset? Provide more information on why 4271 // this leads to a redefinition error. 4272 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4273 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4274 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4275 bool EmittedDiag = 4276 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4277 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4278 4279 // If the header has no guards, emit a note suggesting one. 4280 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4281 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4282 4283 if (EmittedDiag) 4284 return; 4285 } 4286 4287 // Redefinition coming from different files or couldn't do better above. 4288 if (Old->getLocation().isValid()) 4289 Diag(Old->getLocation(), diag::note_previous_definition); 4290 } 4291 4292 /// We've just determined that \p Old and \p New both appear to be definitions 4293 /// of the same variable. Either diagnose or fix the problem. 4294 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4295 if (!hasVisibleDefinition(Old) && 4296 (New->getFormalLinkage() == InternalLinkage || 4297 New->isInline() || 4298 New->getDescribedVarTemplate() || 4299 New->getNumTemplateParameterLists() || 4300 New->getDeclContext()->isDependentContext())) { 4301 // The previous definition is hidden, and multiple definitions are 4302 // permitted (in separate TUs). Demote this to a declaration. 4303 New->demoteThisDefinitionToDeclaration(); 4304 4305 // Make the canonical definition visible. 4306 if (auto *OldTD = Old->getDescribedVarTemplate()) 4307 makeMergedDefinitionVisible(OldTD); 4308 makeMergedDefinitionVisible(Old); 4309 return false; 4310 } else { 4311 Diag(New->getLocation(), diag::err_redefinition) << New; 4312 notePreviousDefinition(Old, New->getLocation()); 4313 New->setInvalidDecl(); 4314 return true; 4315 } 4316 } 4317 4318 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4319 /// no declarator (e.g. "struct foo;") is parsed. 4320 Decl * 4321 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4322 RecordDecl *&AnonRecord) { 4323 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4324 AnonRecord); 4325 } 4326 4327 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4328 // disambiguate entities defined in different scopes. 4329 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4330 // compatibility. 4331 // We will pick our mangling number depending on which version of MSVC is being 4332 // targeted. 4333 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4334 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4335 ? S->getMSCurManglingNumber() 4336 : S->getMSLastManglingNumber(); 4337 } 4338 4339 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4340 if (!Context.getLangOpts().CPlusPlus) 4341 return; 4342 4343 if (isa<CXXRecordDecl>(Tag->getParent())) { 4344 // If this tag is the direct child of a class, number it if 4345 // it is anonymous. 4346 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4347 return; 4348 MangleNumberingContext &MCtx = 4349 Context.getManglingNumberContext(Tag->getParent()); 4350 Context.setManglingNumber( 4351 Tag, MCtx.getManglingNumber( 4352 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4353 return; 4354 } 4355 4356 // If this tag isn't a direct child of a class, number it if it is local. 4357 MangleNumberingContext *MCtx; 4358 Decl *ManglingContextDecl; 4359 std::tie(MCtx, ManglingContextDecl) = 4360 getCurrentMangleNumberContext(Tag->getDeclContext()); 4361 if (MCtx) { 4362 Context.setManglingNumber( 4363 Tag, MCtx->getManglingNumber( 4364 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4365 } 4366 } 4367 4368 namespace { 4369 struct NonCLikeKind { 4370 enum { 4371 None, 4372 BaseClass, 4373 DefaultMemberInit, 4374 Lambda, 4375 Friend, 4376 OtherMember, 4377 Invalid, 4378 } Kind = None; 4379 SourceRange Range; 4380 4381 explicit operator bool() { return Kind != None; } 4382 }; 4383 } 4384 4385 /// Determine whether a class is C-like, according to the rules of C++ 4386 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4387 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4388 if (RD->isInvalidDecl()) 4389 return {NonCLikeKind::Invalid, {}}; 4390 4391 // C++ [dcl.typedef]p9: [P1766R1] 4392 // An unnamed class with a typedef name for linkage purposes shall not 4393 // 4394 // -- have any base classes 4395 if (RD->getNumBases()) 4396 return {NonCLikeKind::BaseClass, 4397 SourceRange(RD->bases_begin()->getBeginLoc(), 4398 RD->bases_end()[-1].getEndLoc())}; 4399 bool Invalid = false; 4400 for (Decl *D : RD->decls()) { 4401 // Don't complain about things we already diagnosed. 4402 if (D->isInvalidDecl()) { 4403 Invalid = true; 4404 continue; 4405 } 4406 4407 // -- have any [...] default member initializers 4408 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4409 if (FD->hasInClassInitializer()) { 4410 auto *Init = FD->getInClassInitializer(); 4411 return {NonCLikeKind::DefaultMemberInit, 4412 Init ? Init->getSourceRange() : D->getSourceRange()}; 4413 } 4414 continue; 4415 } 4416 4417 // FIXME: We don't allow friend declarations. This violates the wording of 4418 // P1766, but not the intent. 4419 if (isa<FriendDecl>(D)) 4420 return {NonCLikeKind::Friend, D->getSourceRange()}; 4421 4422 // -- declare any members other than non-static data members, member 4423 // enumerations, or member classes, 4424 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4425 isa<EnumDecl>(D)) 4426 continue; 4427 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4428 if (!MemberRD) { 4429 if (D->isImplicit()) 4430 continue; 4431 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4432 } 4433 4434 // -- contain a lambda-expression, 4435 if (MemberRD->isLambda()) 4436 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4437 4438 // and all member classes shall also satisfy these requirements 4439 // (recursively). 4440 if (MemberRD->isThisDeclarationADefinition()) { 4441 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4442 return Kind; 4443 } 4444 } 4445 4446 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4447 } 4448 4449 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4450 TypedefNameDecl *NewTD) { 4451 if (TagFromDeclSpec->isInvalidDecl()) 4452 return; 4453 4454 // Do nothing if the tag already has a name for linkage purposes. 4455 if (TagFromDeclSpec->hasNameForLinkage()) 4456 return; 4457 4458 // A well-formed anonymous tag must always be a TUK_Definition. 4459 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4460 4461 // The type must match the tag exactly; no qualifiers allowed. 4462 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4463 Context.getTagDeclType(TagFromDeclSpec))) { 4464 if (getLangOpts().CPlusPlus) 4465 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4466 return; 4467 } 4468 4469 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4470 // An unnamed class with a typedef name for linkage purposes shall [be 4471 // C-like]. 4472 // 4473 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4474 // shouldn't happen, but there are constructs that the language rule doesn't 4475 // disallow for which we can't reasonably avoid computing linkage early. 4476 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4477 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4478 : NonCLikeKind(); 4479 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4480 if (NonCLike || ChangesLinkage) { 4481 if (NonCLike.Kind == NonCLikeKind::Invalid) 4482 return; 4483 4484 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4485 if (ChangesLinkage) { 4486 // If the linkage changes, we can't accept this as an extension. 4487 if (NonCLike.Kind == NonCLikeKind::None) 4488 DiagID = diag::err_typedef_changes_linkage; 4489 else 4490 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4491 } 4492 4493 SourceLocation FixitLoc = 4494 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4495 llvm::SmallString<40> TextToInsert; 4496 TextToInsert += ' '; 4497 TextToInsert += NewTD->getIdentifier()->getName(); 4498 4499 Diag(FixitLoc, DiagID) 4500 << isa<TypeAliasDecl>(NewTD) 4501 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4502 if (NonCLike.Kind != NonCLikeKind::None) { 4503 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4504 << NonCLike.Kind - 1 << NonCLike.Range; 4505 } 4506 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4507 << NewTD << isa<TypeAliasDecl>(NewTD); 4508 4509 if (ChangesLinkage) 4510 return; 4511 } 4512 4513 // Otherwise, set this as the anon-decl typedef for the tag. 4514 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4515 } 4516 4517 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4518 switch (T) { 4519 case DeclSpec::TST_class: 4520 return 0; 4521 case DeclSpec::TST_struct: 4522 return 1; 4523 case DeclSpec::TST_interface: 4524 return 2; 4525 case DeclSpec::TST_union: 4526 return 3; 4527 case DeclSpec::TST_enum: 4528 return 4; 4529 default: 4530 llvm_unreachable("unexpected type specifier"); 4531 } 4532 } 4533 4534 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4535 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4536 /// parameters to cope with template friend declarations. 4537 Decl * 4538 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4539 MultiTemplateParamsArg TemplateParams, 4540 bool IsExplicitInstantiation, 4541 RecordDecl *&AnonRecord) { 4542 Decl *TagD = nullptr; 4543 TagDecl *Tag = nullptr; 4544 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4545 DS.getTypeSpecType() == DeclSpec::TST_struct || 4546 DS.getTypeSpecType() == DeclSpec::TST_interface || 4547 DS.getTypeSpecType() == DeclSpec::TST_union || 4548 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4549 TagD = DS.getRepAsDecl(); 4550 4551 if (!TagD) // We probably had an error 4552 return nullptr; 4553 4554 // Note that the above type specs guarantee that the 4555 // type rep is a Decl, whereas in many of the others 4556 // it's a Type. 4557 if (isa<TagDecl>(TagD)) 4558 Tag = cast<TagDecl>(TagD); 4559 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4560 Tag = CTD->getTemplatedDecl(); 4561 } 4562 4563 if (Tag) { 4564 handleTagNumbering(Tag, S); 4565 Tag->setFreeStanding(); 4566 if (Tag->isInvalidDecl()) 4567 return Tag; 4568 } 4569 4570 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4571 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4572 // or incomplete types shall not be restrict-qualified." 4573 if (TypeQuals & DeclSpec::TQ_restrict) 4574 Diag(DS.getRestrictSpecLoc(), 4575 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4576 << DS.getSourceRange(); 4577 } 4578 4579 if (DS.isInlineSpecified()) 4580 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4581 << getLangOpts().CPlusPlus17; 4582 4583 if (DS.hasConstexprSpecifier()) { 4584 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4585 // and definitions of functions and variables. 4586 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4587 // the declaration of a function or function template 4588 if (Tag) 4589 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4590 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4591 << DS.getConstexprSpecifier(); 4592 else 4593 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4594 << DS.getConstexprSpecifier(); 4595 // Don't emit warnings after this error. 4596 return TagD; 4597 } 4598 4599 DiagnoseFunctionSpecifiers(DS); 4600 4601 if (DS.isFriendSpecified()) { 4602 // If we're dealing with a decl but not a TagDecl, assume that 4603 // whatever routines created it handled the friendship aspect. 4604 if (TagD && !Tag) 4605 return nullptr; 4606 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4607 } 4608 4609 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4610 bool IsExplicitSpecialization = 4611 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4612 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4613 !IsExplicitInstantiation && !IsExplicitSpecialization && 4614 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4615 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4616 // nested-name-specifier unless it is an explicit instantiation 4617 // or an explicit specialization. 4618 // 4619 // FIXME: We allow class template partial specializations here too, per the 4620 // obvious intent of DR1819. 4621 // 4622 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4623 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4624 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4625 return nullptr; 4626 } 4627 4628 // Track whether this decl-specifier declares anything. 4629 bool DeclaresAnything = true; 4630 4631 // Handle anonymous struct definitions. 4632 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4633 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4634 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4635 if (getLangOpts().CPlusPlus || 4636 Record->getDeclContext()->isRecord()) { 4637 // If CurContext is a DeclContext that can contain statements, 4638 // RecursiveASTVisitor won't visit the decls that 4639 // BuildAnonymousStructOrUnion() will put into CurContext. 4640 // Also store them here so that they can be part of the 4641 // DeclStmt that gets created in this case. 4642 // FIXME: Also return the IndirectFieldDecls created by 4643 // BuildAnonymousStructOr union, for the same reason? 4644 if (CurContext->isFunctionOrMethod()) 4645 AnonRecord = Record; 4646 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4647 Context.getPrintingPolicy()); 4648 } 4649 4650 DeclaresAnything = false; 4651 } 4652 } 4653 4654 // C11 6.7.2.1p2: 4655 // A struct-declaration that does not declare an anonymous structure or 4656 // anonymous union shall contain a struct-declarator-list. 4657 // 4658 // This rule also existed in C89 and C99; the grammar for struct-declaration 4659 // did not permit a struct-declaration without a struct-declarator-list. 4660 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4661 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4662 // Check for Microsoft C extension: anonymous struct/union member. 4663 // Handle 2 kinds of anonymous struct/union: 4664 // struct STRUCT; 4665 // union UNION; 4666 // and 4667 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4668 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4669 if ((Tag && Tag->getDeclName()) || 4670 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4671 RecordDecl *Record = nullptr; 4672 if (Tag) 4673 Record = dyn_cast<RecordDecl>(Tag); 4674 else if (const RecordType *RT = 4675 DS.getRepAsType().get()->getAsStructureType()) 4676 Record = RT->getDecl(); 4677 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4678 Record = UT->getDecl(); 4679 4680 if (Record && getLangOpts().MicrosoftExt) { 4681 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4682 << Record->isUnion() << DS.getSourceRange(); 4683 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4684 } 4685 4686 DeclaresAnything = false; 4687 } 4688 } 4689 4690 // Skip all the checks below if we have a type error. 4691 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4692 (TagD && TagD->isInvalidDecl())) 4693 return TagD; 4694 4695 if (getLangOpts().CPlusPlus && 4696 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4697 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4698 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4699 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4700 DeclaresAnything = false; 4701 4702 if (!DS.isMissingDeclaratorOk()) { 4703 // Customize diagnostic for a typedef missing a name. 4704 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4705 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4706 << DS.getSourceRange(); 4707 else 4708 DeclaresAnything = false; 4709 } 4710 4711 if (DS.isModulePrivateSpecified() && 4712 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4713 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4714 << Tag->getTagKind() 4715 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4716 4717 ActOnDocumentableDecl(TagD); 4718 4719 // C 6.7/2: 4720 // A declaration [...] shall declare at least a declarator [...], a tag, 4721 // or the members of an enumeration. 4722 // C++ [dcl.dcl]p3: 4723 // [If there are no declarators], and except for the declaration of an 4724 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4725 // names into the program, or shall redeclare a name introduced by a 4726 // previous declaration. 4727 if (!DeclaresAnything) { 4728 // In C, we allow this as a (popular) extension / bug. Don't bother 4729 // producing further diagnostics for redundant qualifiers after this. 4730 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4731 return TagD; 4732 } 4733 4734 // C++ [dcl.stc]p1: 4735 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4736 // init-declarator-list of the declaration shall not be empty. 4737 // C++ [dcl.fct.spec]p1: 4738 // If a cv-qualifier appears in a decl-specifier-seq, the 4739 // init-declarator-list of the declaration shall not be empty. 4740 // 4741 // Spurious qualifiers here appear to be valid in C. 4742 unsigned DiagID = diag::warn_standalone_specifier; 4743 if (getLangOpts().CPlusPlus) 4744 DiagID = diag::ext_standalone_specifier; 4745 4746 // Note that a linkage-specification sets a storage class, but 4747 // 'extern "C" struct foo;' is actually valid and not theoretically 4748 // useless. 4749 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4750 if (SCS == DeclSpec::SCS_mutable) 4751 // Since mutable is not a viable storage class specifier in C, there is 4752 // no reason to treat it as an extension. Instead, diagnose as an error. 4753 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4754 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4755 Diag(DS.getStorageClassSpecLoc(), DiagID) 4756 << DeclSpec::getSpecifierName(SCS); 4757 } 4758 4759 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4760 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4761 << DeclSpec::getSpecifierName(TSCS); 4762 if (DS.getTypeQualifiers()) { 4763 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4764 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4765 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4766 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4767 // Restrict is covered above. 4768 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4769 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4770 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4771 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4772 } 4773 4774 // Warn about ignored type attributes, for example: 4775 // __attribute__((aligned)) struct A; 4776 // Attributes should be placed after tag to apply to type declaration. 4777 if (!DS.getAttributes().empty()) { 4778 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4779 if (TypeSpecType == DeclSpec::TST_class || 4780 TypeSpecType == DeclSpec::TST_struct || 4781 TypeSpecType == DeclSpec::TST_interface || 4782 TypeSpecType == DeclSpec::TST_union || 4783 TypeSpecType == DeclSpec::TST_enum) { 4784 for (const ParsedAttr &AL : DS.getAttributes()) 4785 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4786 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4787 } 4788 } 4789 4790 return TagD; 4791 } 4792 4793 /// We are trying to inject an anonymous member into the given scope; 4794 /// check if there's an existing declaration that can't be overloaded. 4795 /// 4796 /// \return true if this is a forbidden redeclaration 4797 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4798 Scope *S, 4799 DeclContext *Owner, 4800 DeclarationName Name, 4801 SourceLocation NameLoc, 4802 bool IsUnion) { 4803 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4804 Sema::ForVisibleRedeclaration); 4805 if (!SemaRef.LookupName(R, S)) return false; 4806 4807 // Pick a representative declaration. 4808 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4809 assert(PrevDecl && "Expected a non-null Decl"); 4810 4811 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4812 return false; 4813 4814 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4815 << IsUnion << Name; 4816 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4817 4818 return true; 4819 } 4820 4821 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4822 /// anonymous struct or union AnonRecord into the owning context Owner 4823 /// and scope S. This routine will be invoked just after we realize 4824 /// that an unnamed union or struct is actually an anonymous union or 4825 /// struct, e.g., 4826 /// 4827 /// @code 4828 /// union { 4829 /// int i; 4830 /// float f; 4831 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4832 /// // f into the surrounding scope.x 4833 /// @endcode 4834 /// 4835 /// This routine is recursive, injecting the names of nested anonymous 4836 /// structs/unions into the owning context and scope as well. 4837 static bool 4838 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4839 RecordDecl *AnonRecord, AccessSpecifier AS, 4840 SmallVectorImpl<NamedDecl *> &Chaining) { 4841 bool Invalid = false; 4842 4843 // Look every FieldDecl and IndirectFieldDecl with a name. 4844 for (auto *D : AnonRecord->decls()) { 4845 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4846 cast<NamedDecl>(D)->getDeclName()) { 4847 ValueDecl *VD = cast<ValueDecl>(D); 4848 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4849 VD->getLocation(), 4850 AnonRecord->isUnion())) { 4851 // C++ [class.union]p2: 4852 // The names of the members of an anonymous union shall be 4853 // distinct from the names of any other entity in the 4854 // scope in which the anonymous union is declared. 4855 Invalid = true; 4856 } else { 4857 // C++ [class.union]p2: 4858 // For the purpose of name lookup, after the anonymous union 4859 // definition, the members of the anonymous union are 4860 // considered to have been defined in the scope in which the 4861 // anonymous union is declared. 4862 unsigned OldChainingSize = Chaining.size(); 4863 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4864 Chaining.append(IF->chain_begin(), IF->chain_end()); 4865 else 4866 Chaining.push_back(VD); 4867 4868 assert(Chaining.size() >= 2); 4869 NamedDecl **NamedChain = 4870 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4871 for (unsigned i = 0; i < Chaining.size(); i++) 4872 NamedChain[i] = Chaining[i]; 4873 4874 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4875 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4876 VD->getType(), {NamedChain, Chaining.size()}); 4877 4878 for (const auto *Attr : VD->attrs()) 4879 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4880 4881 IndirectField->setAccess(AS); 4882 IndirectField->setImplicit(); 4883 SemaRef.PushOnScopeChains(IndirectField, S); 4884 4885 // That includes picking up the appropriate access specifier. 4886 if (AS != AS_none) IndirectField->setAccess(AS); 4887 4888 Chaining.resize(OldChainingSize); 4889 } 4890 } 4891 } 4892 4893 return Invalid; 4894 } 4895 4896 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4897 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4898 /// illegal input values are mapped to SC_None. 4899 static StorageClass 4900 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4901 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4902 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4903 "Parser allowed 'typedef' as storage class VarDecl."); 4904 switch (StorageClassSpec) { 4905 case DeclSpec::SCS_unspecified: return SC_None; 4906 case DeclSpec::SCS_extern: 4907 if (DS.isExternInLinkageSpec()) 4908 return SC_None; 4909 return SC_Extern; 4910 case DeclSpec::SCS_static: return SC_Static; 4911 case DeclSpec::SCS_auto: return SC_Auto; 4912 case DeclSpec::SCS_register: return SC_Register; 4913 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4914 // Illegal SCSs map to None: error reporting is up to the caller. 4915 case DeclSpec::SCS_mutable: // Fall through. 4916 case DeclSpec::SCS_typedef: return SC_None; 4917 } 4918 llvm_unreachable("unknown storage class specifier"); 4919 } 4920 4921 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4922 assert(Record->hasInClassInitializer()); 4923 4924 for (const auto *I : Record->decls()) { 4925 const auto *FD = dyn_cast<FieldDecl>(I); 4926 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4927 FD = IFD->getAnonField(); 4928 if (FD && FD->hasInClassInitializer()) 4929 return FD->getLocation(); 4930 } 4931 4932 llvm_unreachable("couldn't find in-class initializer"); 4933 } 4934 4935 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4936 SourceLocation DefaultInitLoc) { 4937 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4938 return; 4939 4940 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4941 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4942 } 4943 4944 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4945 CXXRecordDecl *AnonUnion) { 4946 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4947 return; 4948 4949 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4950 } 4951 4952 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4953 /// anonymous structure or union. Anonymous unions are a C++ feature 4954 /// (C++ [class.union]) and a C11 feature; anonymous structures 4955 /// are a C11 feature and GNU C++ extension. 4956 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4957 AccessSpecifier AS, 4958 RecordDecl *Record, 4959 const PrintingPolicy &Policy) { 4960 DeclContext *Owner = Record->getDeclContext(); 4961 4962 // Diagnose whether this anonymous struct/union is an extension. 4963 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4964 Diag(Record->getLocation(), diag::ext_anonymous_union); 4965 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4966 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4967 else if (!Record->isUnion() && !getLangOpts().C11) 4968 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4969 4970 // C and C++ require different kinds of checks for anonymous 4971 // structs/unions. 4972 bool Invalid = false; 4973 if (getLangOpts().CPlusPlus) { 4974 const char *PrevSpec = nullptr; 4975 if (Record->isUnion()) { 4976 // C++ [class.union]p6: 4977 // C++17 [class.union.anon]p2: 4978 // Anonymous unions declared in a named namespace or in the 4979 // global namespace shall be declared static. 4980 unsigned DiagID; 4981 DeclContext *OwnerScope = Owner->getRedeclContext(); 4982 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4983 (OwnerScope->isTranslationUnit() || 4984 (OwnerScope->isNamespace() && 4985 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4986 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4987 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4988 4989 // Recover by adding 'static'. 4990 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4991 PrevSpec, DiagID, Policy); 4992 } 4993 // C++ [class.union]p6: 4994 // A storage class is not allowed in a declaration of an 4995 // anonymous union in a class scope. 4996 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4997 isa<RecordDecl>(Owner)) { 4998 Diag(DS.getStorageClassSpecLoc(), 4999 diag::err_anonymous_union_with_storage_spec) 5000 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5001 5002 // Recover by removing the storage specifier. 5003 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5004 SourceLocation(), 5005 PrevSpec, DiagID, Context.getPrintingPolicy()); 5006 } 5007 } 5008 5009 // Ignore const/volatile/restrict qualifiers. 5010 if (DS.getTypeQualifiers()) { 5011 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5012 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5013 << Record->isUnion() << "const" 5014 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5015 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5016 Diag(DS.getVolatileSpecLoc(), 5017 diag::ext_anonymous_struct_union_qualified) 5018 << Record->isUnion() << "volatile" 5019 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5020 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5021 Diag(DS.getRestrictSpecLoc(), 5022 diag::ext_anonymous_struct_union_qualified) 5023 << Record->isUnion() << "restrict" 5024 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5026 Diag(DS.getAtomicSpecLoc(), 5027 diag::ext_anonymous_struct_union_qualified) 5028 << Record->isUnion() << "_Atomic" 5029 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5030 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5031 Diag(DS.getUnalignedSpecLoc(), 5032 diag::ext_anonymous_struct_union_qualified) 5033 << Record->isUnion() << "__unaligned" 5034 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5035 5036 DS.ClearTypeQualifiers(); 5037 } 5038 5039 // C++ [class.union]p2: 5040 // The member-specification of an anonymous union shall only 5041 // define non-static data members. [Note: nested types and 5042 // functions cannot be declared within an anonymous union. ] 5043 for (auto *Mem : Record->decls()) { 5044 // Ignore invalid declarations; we already diagnosed them. 5045 if (Mem->isInvalidDecl()) 5046 continue; 5047 5048 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5049 // C++ [class.union]p3: 5050 // An anonymous union shall not have private or protected 5051 // members (clause 11). 5052 assert(FD->getAccess() != AS_none); 5053 if (FD->getAccess() != AS_public) { 5054 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5055 << Record->isUnion() << (FD->getAccess() == AS_protected); 5056 Invalid = true; 5057 } 5058 5059 // C++ [class.union]p1 5060 // An object of a class with a non-trivial constructor, a non-trivial 5061 // copy constructor, a non-trivial destructor, or a non-trivial copy 5062 // assignment operator cannot be a member of a union, nor can an 5063 // array of such objects. 5064 if (CheckNontrivialField(FD)) 5065 Invalid = true; 5066 } else if (Mem->isImplicit()) { 5067 // Any implicit members are fine. 5068 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5069 // This is a type that showed up in an 5070 // elaborated-type-specifier inside the anonymous struct or 5071 // union, but which actually declares a type outside of the 5072 // anonymous struct or union. It's okay. 5073 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5074 if (!MemRecord->isAnonymousStructOrUnion() && 5075 MemRecord->getDeclName()) { 5076 // Visual C++ allows type definition in anonymous struct or union. 5077 if (getLangOpts().MicrosoftExt) 5078 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5079 << Record->isUnion(); 5080 else { 5081 // This is a nested type declaration. 5082 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5083 << Record->isUnion(); 5084 Invalid = true; 5085 } 5086 } else { 5087 // This is an anonymous type definition within another anonymous type. 5088 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5089 // not part of standard C++. 5090 Diag(MemRecord->getLocation(), 5091 diag::ext_anonymous_record_with_anonymous_type) 5092 << Record->isUnion(); 5093 } 5094 } else if (isa<AccessSpecDecl>(Mem)) { 5095 // Any access specifier is fine. 5096 } else if (isa<StaticAssertDecl>(Mem)) { 5097 // In C++1z, static_assert declarations are also fine. 5098 } else { 5099 // We have something that isn't a non-static data 5100 // member. Complain about it. 5101 unsigned DK = diag::err_anonymous_record_bad_member; 5102 if (isa<TypeDecl>(Mem)) 5103 DK = diag::err_anonymous_record_with_type; 5104 else if (isa<FunctionDecl>(Mem)) 5105 DK = diag::err_anonymous_record_with_function; 5106 else if (isa<VarDecl>(Mem)) 5107 DK = diag::err_anonymous_record_with_static; 5108 5109 // Visual C++ allows type definition in anonymous struct or union. 5110 if (getLangOpts().MicrosoftExt && 5111 DK == diag::err_anonymous_record_with_type) 5112 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5113 << Record->isUnion(); 5114 else { 5115 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5116 Invalid = true; 5117 } 5118 } 5119 } 5120 5121 // C++11 [class.union]p8 (DR1460): 5122 // At most one variant member of a union may have a 5123 // brace-or-equal-initializer. 5124 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5125 Owner->isRecord()) 5126 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5127 cast<CXXRecordDecl>(Record)); 5128 } 5129 5130 if (!Record->isUnion() && !Owner->isRecord()) { 5131 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5132 << getLangOpts().CPlusPlus; 5133 Invalid = true; 5134 } 5135 5136 // C++ [dcl.dcl]p3: 5137 // [If there are no declarators], and except for the declaration of an 5138 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5139 // names into the program 5140 // C++ [class.mem]p2: 5141 // each such member-declaration shall either declare at least one member 5142 // name of the class or declare at least one unnamed bit-field 5143 // 5144 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5145 if (getLangOpts().CPlusPlus && Record->field_empty()) 5146 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5147 5148 // Mock up a declarator. 5149 Declarator Dc(DS, DeclaratorContext::MemberContext); 5150 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5151 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5152 5153 // Create a declaration for this anonymous struct/union. 5154 NamedDecl *Anon = nullptr; 5155 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5156 Anon = FieldDecl::Create( 5157 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5158 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5159 /*BitWidth=*/nullptr, /*Mutable=*/false, 5160 /*InitStyle=*/ICIS_NoInit); 5161 Anon->setAccess(AS); 5162 ProcessDeclAttributes(S, Anon, Dc); 5163 5164 if (getLangOpts().CPlusPlus) 5165 FieldCollector->Add(cast<FieldDecl>(Anon)); 5166 } else { 5167 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5168 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5169 if (SCSpec == DeclSpec::SCS_mutable) { 5170 // mutable can only appear on non-static class members, so it's always 5171 // an error here 5172 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5173 Invalid = true; 5174 SC = SC_None; 5175 } 5176 5177 assert(DS.getAttributes().empty() && "No attribute expected"); 5178 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5179 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5180 Context.getTypeDeclType(Record), TInfo, SC); 5181 5182 // Default-initialize the implicit variable. This initialization will be 5183 // trivial in almost all cases, except if a union member has an in-class 5184 // initializer: 5185 // union { int n = 0; }; 5186 ActOnUninitializedDecl(Anon); 5187 } 5188 Anon->setImplicit(); 5189 5190 // Mark this as an anonymous struct/union type. 5191 Record->setAnonymousStructOrUnion(true); 5192 5193 // Add the anonymous struct/union object to the current 5194 // context. We'll be referencing this object when we refer to one of 5195 // its members. 5196 Owner->addDecl(Anon); 5197 5198 // Inject the members of the anonymous struct/union into the owning 5199 // context and into the identifier resolver chain for name lookup 5200 // purposes. 5201 SmallVector<NamedDecl*, 2> Chain; 5202 Chain.push_back(Anon); 5203 5204 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5205 Invalid = true; 5206 5207 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5208 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5209 MangleNumberingContext *MCtx; 5210 Decl *ManglingContextDecl; 5211 std::tie(MCtx, ManglingContextDecl) = 5212 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5213 if (MCtx) { 5214 Context.setManglingNumber( 5215 NewVD, MCtx->getManglingNumber( 5216 NewVD, getMSManglingNumber(getLangOpts(), S))); 5217 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5218 } 5219 } 5220 } 5221 5222 if (Invalid) 5223 Anon->setInvalidDecl(); 5224 5225 return Anon; 5226 } 5227 5228 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5229 /// Microsoft C anonymous structure. 5230 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5231 /// Example: 5232 /// 5233 /// struct A { int a; }; 5234 /// struct B { struct A; int b; }; 5235 /// 5236 /// void foo() { 5237 /// B var; 5238 /// var.a = 3; 5239 /// } 5240 /// 5241 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5242 RecordDecl *Record) { 5243 assert(Record && "expected a record!"); 5244 5245 // Mock up a declarator. 5246 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5247 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5248 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5249 5250 auto *ParentDecl = cast<RecordDecl>(CurContext); 5251 QualType RecTy = Context.getTypeDeclType(Record); 5252 5253 // Create a declaration for this anonymous struct. 5254 NamedDecl *Anon = 5255 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5256 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5257 /*BitWidth=*/nullptr, /*Mutable=*/false, 5258 /*InitStyle=*/ICIS_NoInit); 5259 Anon->setImplicit(); 5260 5261 // Add the anonymous struct object to the current context. 5262 CurContext->addDecl(Anon); 5263 5264 // Inject the members of the anonymous struct into the current 5265 // context and into the identifier resolver chain for name lookup 5266 // purposes. 5267 SmallVector<NamedDecl*, 2> Chain; 5268 Chain.push_back(Anon); 5269 5270 RecordDecl *RecordDef = Record->getDefinition(); 5271 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5272 diag::err_field_incomplete_or_sizeless) || 5273 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5274 AS_none, Chain)) { 5275 Anon->setInvalidDecl(); 5276 ParentDecl->setInvalidDecl(); 5277 } 5278 5279 return Anon; 5280 } 5281 5282 /// GetNameForDeclarator - Determine the full declaration name for the 5283 /// given Declarator. 5284 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5285 return GetNameFromUnqualifiedId(D.getName()); 5286 } 5287 5288 /// Retrieves the declaration name from a parsed unqualified-id. 5289 DeclarationNameInfo 5290 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5291 DeclarationNameInfo NameInfo; 5292 NameInfo.setLoc(Name.StartLocation); 5293 5294 switch (Name.getKind()) { 5295 5296 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5297 case UnqualifiedIdKind::IK_Identifier: 5298 NameInfo.setName(Name.Identifier); 5299 return NameInfo; 5300 5301 case UnqualifiedIdKind::IK_DeductionGuideName: { 5302 // C++ [temp.deduct.guide]p3: 5303 // The simple-template-id shall name a class template specialization. 5304 // The template-name shall be the same identifier as the template-name 5305 // of the simple-template-id. 5306 // These together intend to imply that the template-name shall name a 5307 // class template. 5308 // FIXME: template<typename T> struct X {}; 5309 // template<typename T> using Y = X<T>; 5310 // Y(int) -> Y<int>; 5311 // satisfies these rules but does not name a class template. 5312 TemplateName TN = Name.TemplateName.get().get(); 5313 auto *Template = TN.getAsTemplateDecl(); 5314 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5315 Diag(Name.StartLocation, 5316 diag::err_deduction_guide_name_not_class_template) 5317 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5318 if (Template) 5319 Diag(Template->getLocation(), diag::note_template_decl_here); 5320 return DeclarationNameInfo(); 5321 } 5322 5323 NameInfo.setName( 5324 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5325 return NameInfo; 5326 } 5327 5328 case UnqualifiedIdKind::IK_OperatorFunctionId: 5329 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5330 Name.OperatorFunctionId.Operator)); 5331 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5332 = Name.OperatorFunctionId.SymbolLocations[0]; 5333 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5334 = Name.EndLocation.getRawEncoding(); 5335 return NameInfo; 5336 5337 case UnqualifiedIdKind::IK_LiteralOperatorId: 5338 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5339 Name.Identifier)); 5340 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5341 return NameInfo; 5342 5343 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5344 TypeSourceInfo *TInfo; 5345 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5346 if (Ty.isNull()) 5347 return DeclarationNameInfo(); 5348 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5349 Context.getCanonicalType(Ty))); 5350 NameInfo.setNamedTypeInfo(TInfo); 5351 return NameInfo; 5352 } 5353 5354 case UnqualifiedIdKind::IK_ConstructorName: { 5355 TypeSourceInfo *TInfo; 5356 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5357 if (Ty.isNull()) 5358 return DeclarationNameInfo(); 5359 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5360 Context.getCanonicalType(Ty))); 5361 NameInfo.setNamedTypeInfo(TInfo); 5362 return NameInfo; 5363 } 5364 5365 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5366 // In well-formed code, we can only have a constructor 5367 // template-id that refers to the current context, so go there 5368 // to find the actual type being constructed. 5369 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5370 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5371 return DeclarationNameInfo(); 5372 5373 // Determine the type of the class being constructed. 5374 QualType CurClassType = Context.getTypeDeclType(CurClass); 5375 5376 // FIXME: Check two things: that the template-id names the same type as 5377 // CurClassType, and that the template-id does not occur when the name 5378 // was qualified. 5379 5380 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5381 Context.getCanonicalType(CurClassType))); 5382 // FIXME: should we retrieve TypeSourceInfo? 5383 NameInfo.setNamedTypeInfo(nullptr); 5384 return NameInfo; 5385 } 5386 5387 case UnqualifiedIdKind::IK_DestructorName: { 5388 TypeSourceInfo *TInfo; 5389 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5390 if (Ty.isNull()) 5391 return DeclarationNameInfo(); 5392 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5393 Context.getCanonicalType(Ty))); 5394 NameInfo.setNamedTypeInfo(TInfo); 5395 return NameInfo; 5396 } 5397 5398 case UnqualifiedIdKind::IK_TemplateId: { 5399 TemplateName TName = Name.TemplateId->Template.get(); 5400 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5401 return Context.getNameForTemplate(TName, TNameLoc); 5402 } 5403 5404 } // switch (Name.getKind()) 5405 5406 llvm_unreachable("Unknown name kind"); 5407 } 5408 5409 static QualType getCoreType(QualType Ty) { 5410 do { 5411 if (Ty->isPointerType() || Ty->isReferenceType()) 5412 Ty = Ty->getPointeeType(); 5413 else if (Ty->isArrayType()) 5414 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5415 else 5416 return Ty.withoutLocalFastQualifiers(); 5417 } while (true); 5418 } 5419 5420 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5421 /// and Definition have "nearly" matching parameters. This heuristic is 5422 /// used to improve diagnostics in the case where an out-of-line function 5423 /// definition doesn't match any declaration within the class or namespace. 5424 /// Also sets Params to the list of indices to the parameters that differ 5425 /// between the declaration and the definition. If hasSimilarParameters 5426 /// returns true and Params is empty, then all of the parameters match. 5427 static bool hasSimilarParameters(ASTContext &Context, 5428 FunctionDecl *Declaration, 5429 FunctionDecl *Definition, 5430 SmallVectorImpl<unsigned> &Params) { 5431 Params.clear(); 5432 if (Declaration->param_size() != Definition->param_size()) 5433 return false; 5434 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5435 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5436 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5437 5438 // The parameter types are identical 5439 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5440 continue; 5441 5442 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5443 QualType DefParamBaseTy = getCoreType(DefParamTy); 5444 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5445 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5446 5447 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5448 (DeclTyName && DeclTyName == DefTyName)) 5449 Params.push_back(Idx); 5450 else // The two parameters aren't even close 5451 return false; 5452 } 5453 5454 return true; 5455 } 5456 5457 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5458 /// declarator needs to be rebuilt in the current instantiation. 5459 /// Any bits of declarator which appear before the name are valid for 5460 /// consideration here. That's specifically the type in the decl spec 5461 /// and the base type in any member-pointer chunks. 5462 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5463 DeclarationName Name) { 5464 // The types we specifically need to rebuild are: 5465 // - typenames, typeofs, and decltypes 5466 // - types which will become injected class names 5467 // Of course, we also need to rebuild any type referencing such a 5468 // type. It's safest to just say "dependent", but we call out a 5469 // few cases here. 5470 5471 DeclSpec &DS = D.getMutableDeclSpec(); 5472 switch (DS.getTypeSpecType()) { 5473 case DeclSpec::TST_typename: 5474 case DeclSpec::TST_typeofType: 5475 case DeclSpec::TST_underlyingType: 5476 case DeclSpec::TST_atomic: { 5477 // Grab the type from the parser. 5478 TypeSourceInfo *TSI = nullptr; 5479 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5480 if (T.isNull() || !T->isDependentType()) break; 5481 5482 // Make sure there's a type source info. This isn't really much 5483 // of a waste; most dependent types should have type source info 5484 // attached already. 5485 if (!TSI) 5486 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5487 5488 // Rebuild the type in the current instantiation. 5489 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5490 if (!TSI) return true; 5491 5492 // Store the new type back in the decl spec. 5493 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5494 DS.UpdateTypeRep(LocType); 5495 break; 5496 } 5497 5498 case DeclSpec::TST_decltype: 5499 case DeclSpec::TST_typeofExpr: { 5500 Expr *E = DS.getRepAsExpr(); 5501 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5502 if (Result.isInvalid()) return true; 5503 DS.UpdateExprRep(Result.get()); 5504 break; 5505 } 5506 5507 default: 5508 // Nothing to do for these decl specs. 5509 break; 5510 } 5511 5512 // It doesn't matter what order we do this in. 5513 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5514 DeclaratorChunk &Chunk = D.getTypeObject(I); 5515 5516 // The only type information in the declarator which can come 5517 // before the declaration name is the base type of a member 5518 // pointer. 5519 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5520 continue; 5521 5522 // Rebuild the scope specifier in-place. 5523 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5524 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5525 return true; 5526 } 5527 5528 return false; 5529 } 5530 5531 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5532 D.setFunctionDefinitionKind(FDK_Declaration); 5533 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5534 5535 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5536 Dcl && Dcl->getDeclContext()->isFileContext()) 5537 Dcl->setTopLevelDeclInObjCContainer(); 5538 5539 if (getLangOpts().OpenCL) 5540 setCurrentOpenCLExtensionForDecl(Dcl); 5541 5542 return Dcl; 5543 } 5544 5545 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5546 /// If T is the name of a class, then each of the following shall have a 5547 /// name different from T: 5548 /// - every static data member of class T; 5549 /// - every member function of class T 5550 /// - every member of class T that is itself a type; 5551 /// \returns true if the declaration name violates these rules. 5552 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5553 DeclarationNameInfo NameInfo) { 5554 DeclarationName Name = NameInfo.getName(); 5555 5556 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5557 while (Record && Record->isAnonymousStructOrUnion()) 5558 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5559 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5560 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5561 return true; 5562 } 5563 5564 return false; 5565 } 5566 5567 /// Diagnose a declaration whose declarator-id has the given 5568 /// nested-name-specifier. 5569 /// 5570 /// \param SS The nested-name-specifier of the declarator-id. 5571 /// 5572 /// \param DC The declaration context to which the nested-name-specifier 5573 /// resolves. 5574 /// 5575 /// \param Name The name of the entity being declared. 5576 /// 5577 /// \param Loc The location of the name of the entity being declared. 5578 /// 5579 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5580 /// we're declaring an explicit / partial specialization / instantiation. 5581 /// 5582 /// \returns true if we cannot safely recover from this error, false otherwise. 5583 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5584 DeclarationName Name, 5585 SourceLocation Loc, bool IsTemplateId) { 5586 DeclContext *Cur = CurContext; 5587 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5588 Cur = Cur->getParent(); 5589 5590 // If the user provided a superfluous scope specifier that refers back to the 5591 // class in which the entity is already declared, diagnose and ignore it. 5592 // 5593 // class X { 5594 // void X::f(); 5595 // }; 5596 // 5597 // Note, it was once ill-formed to give redundant qualification in all 5598 // contexts, but that rule was removed by DR482. 5599 if (Cur->Equals(DC)) { 5600 if (Cur->isRecord()) { 5601 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5602 : diag::err_member_extra_qualification) 5603 << Name << FixItHint::CreateRemoval(SS.getRange()); 5604 SS.clear(); 5605 } else { 5606 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5607 } 5608 return false; 5609 } 5610 5611 // Check whether the qualifying scope encloses the scope of the original 5612 // declaration. For a template-id, we perform the checks in 5613 // CheckTemplateSpecializationScope. 5614 if (!Cur->Encloses(DC) && !IsTemplateId) { 5615 if (Cur->isRecord()) 5616 Diag(Loc, diag::err_member_qualification) 5617 << Name << SS.getRange(); 5618 else if (isa<TranslationUnitDecl>(DC)) 5619 Diag(Loc, diag::err_invalid_declarator_global_scope) 5620 << Name << SS.getRange(); 5621 else if (isa<FunctionDecl>(Cur)) 5622 Diag(Loc, diag::err_invalid_declarator_in_function) 5623 << Name << SS.getRange(); 5624 else if (isa<BlockDecl>(Cur)) 5625 Diag(Loc, diag::err_invalid_declarator_in_block) 5626 << Name << SS.getRange(); 5627 else 5628 Diag(Loc, diag::err_invalid_declarator_scope) 5629 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5630 5631 return true; 5632 } 5633 5634 if (Cur->isRecord()) { 5635 // Cannot qualify members within a class. 5636 Diag(Loc, diag::err_member_qualification) 5637 << Name << SS.getRange(); 5638 SS.clear(); 5639 5640 // C++ constructors and destructors with incorrect scopes can break 5641 // our AST invariants by having the wrong underlying types. If 5642 // that's the case, then drop this declaration entirely. 5643 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5644 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5645 !Context.hasSameType(Name.getCXXNameType(), 5646 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5647 return true; 5648 5649 return false; 5650 } 5651 5652 // C++11 [dcl.meaning]p1: 5653 // [...] "The nested-name-specifier of the qualified declarator-id shall 5654 // not begin with a decltype-specifer" 5655 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5656 while (SpecLoc.getPrefix()) 5657 SpecLoc = SpecLoc.getPrefix(); 5658 if (dyn_cast_or_null<DecltypeType>( 5659 SpecLoc.getNestedNameSpecifier()->getAsType())) 5660 Diag(Loc, diag::err_decltype_in_declarator) 5661 << SpecLoc.getTypeLoc().getSourceRange(); 5662 5663 return false; 5664 } 5665 5666 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5667 MultiTemplateParamsArg TemplateParamLists) { 5668 // TODO: consider using NameInfo for diagnostic. 5669 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5670 DeclarationName Name = NameInfo.getName(); 5671 5672 // All of these full declarators require an identifier. If it doesn't have 5673 // one, the ParsedFreeStandingDeclSpec action should be used. 5674 if (D.isDecompositionDeclarator()) { 5675 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5676 } else if (!Name) { 5677 if (!D.isInvalidType()) // Reject this if we think it is valid. 5678 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5679 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5680 return nullptr; 5681 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5682 return nullptr; 5683 5684 // The scope passed in may not be a decl scope. Zip up the scope tree until 5685 // we find one that is. 5686 while ((S->getFlags() & Scope::DeclScope) == 0 || 5687 (S->getFlags() & Scope::TemplateParamScope) != 0) 5688 S = S->getParent(); 5689 5690 DeclContext *DC = CurContext; 5691 if (D.getCXXScopeSpec().isInvalid()) 5692 D.setInvalidType(); 5693 else if (D.getCXXScopeSpec().isSet()) { 5694 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5695 UPPC_DeclarationQualifier)) 5696 return nullptr; 5697 5698 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5699 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5700 if (!DC || isa<EnumDecl>(DC)) { 5701 // If we could not compute the declaration context, it's because the 5702 // declaration context is dependent but does not refer to a class, 5703 // class template, or class template partial specialization. Complain 5704 // and return early, to avoid the coming semantic disaster. 5705 Diag(D.getIdentifierLoc(), 5706 diag::err_template_qualified_declarator_no_match) 5707 << D.getCXXScopeSpec().getScopeRep() 5708 << D.getCXXScopeSpec().getRange(); 5709 return nullptr; 5710 } 5711 bool IsDependentContext = DC->isDependentContext(); 5712 5713 if (!IsDependentContext && 5714 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5715 return nullptr; 5716 5717 // If a class is incomplete, do not parse entities inside it. 5718 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5719 Diag(D.getIdentifierLoc(), 5720 diag::err_member_def_undefined_record) 5721 << Name << DC << D.getCXXScopeSpec().getRange(); 5722 return nullptr; 5723 } 5724 if (!D.getDeclSpec().isFriendSpecified()) { 5725 if (diagnoseQualifiedDeclaration( 5726 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5727 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5728 if (DC->isRecord()) 5729 return nullptr; 5730 5731 D.setInvalidType(); 5732 } 5733 } 5734 5735 // Check whether we need to rebuild the type of the given 5736 // declaration in the current instantiation. 5737 if (EnteringContext && IsDependentContext && 5738 TemplateParamLists.size() != 0) { 5739 ContextRAII SavedContext(*this, DC); 5740 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5741 D.setInvalidType(); 5742 } 5743 } 5744 5745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5746 QualType R = TInfo->getType(); 5747 5748 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5749 UPPC_DeclarationType)) 5750 D.setInvalidType(); 5751 5752 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5753 forRedeclarationInCurContext()); 5754 5755 // See if this is a redefinition of a variable in the same scope. 5756 if (!D.getCXXScopeSpec().isSet()) { 5757 bool IsLinkageLookup = false; 5758 bool CreateBuiltins = false; 5759 5760 // If the declaration we're planning to build will be a function 5761 // or object with linkage, then look for another declaration with 5762 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5763 // 5764 // If the declaration we're planning to build will be declared with 5765 // external linkage in the translation unit, create any builtin with 5766 // the same name. 5767 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5768 /* Do nothing*/; 5769 else if (CurContext->isFunctionOrMethod() && 5770 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5771 R->isFunctionType())) { 5772 IsLinkageLookup = true; 5773 CreateBuiltins = 5774 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5775 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5776 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5777 CreateBuiltins = true; 5778 5779 if (IsLinkageLookup) { 5780 Previous.clear(LookupRedeclarationWithLinkage); 5781 Previous.setRedeclarationKind(ForExternalRedeclaration); 5782 } 5783 5784 LookupName(Previous, S, CreateBuiltins); 5785 } else { // Something like "int foo::x;" 5786 LookupQualifiedName(Previous, DC); 5787 5788 // C++ [dcl.meaning]p1: 5789 // When the declarator-id is qualified, the declaration shall refer to a 5790 // previously declared member of the class or namespace to which the 5791 // qualifier refers (or, in the case of a namespace, of an element of the 5792 // inline namespace set of that namespace (7.3.1)) or to a specialization 5793 // thereof; [...] 5794 // 5795 // Note that we already checked the context above, and that we do not have 5796 // enough information to make sure that Previous contains the declaration 5797 // we want to match. For example, given: 5798 // 5799 // class X { 5800 // void f(); 5801 // void f(float); 5802 // }; 5803 // 5804 // void X::f(int) { } // ill-formed 5805 // 5806 // In this case, Previous will point to the overload set 5807 // containing the two f's declared in X, but neither of them 5808 // matches. 5809 5810 // C++ [dcl.meaning]p1: 5811 // [...] the member shall not merely have been introduced by a 5812 // using-declaration in the scope of the class or namespace nominated by 5813 // the nested-name-specifier of the declarator-id. 5814 RemoveUsingDecls(Previous); 5815 } 5816 5817 if (Previous.isSingleResult() && 5818 Previous.getFoundDecl()->isTemplateParameter()) { 5819 // Maybe we will complain about the shadowed template parameter. 5820 if (!D.isInvalidType()) 5821 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5822 Previous.getFoundDecl()); 5823 5824 // Just pretend that we didn't see the previous declaration. 5825 Previous.clear(); 5826 } 5827 5828 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5829 // Forget that the previous declaration is the injected-class-name. 5830 Previous.clear(); 5831 5832 // In C++, the previous declaration we find might be a tag type 5833 // (class or enum). In this case, the new declaration will hide the 5834 // tag type. Note that this applies to functions, function templates, and 5835 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5836 if (Previous.isSingleTagDecl() && 5837 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5838 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5839 Previous.clear(); 5840 5841 // Check that there are no default arguments other than in the parameters 5842 // of a function declaration (C++ only). 5843 if (getLangOpts().CPlusPlus) 5844 CheckExtraCXXDefaultArguments(D); 5845 5846 NamedDecl *New; 5847 5848 bool AddToScope = true; 5849 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5850 if (TemplateParamLists.size()) { 5851 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5852 return nullptr; 5853 } 5854 5855 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5856 } else if (R->isFunctionType()) { 5857 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5858 TemplateParamLists, 5859 AddToScope); 5860 } else { 5861 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5862 AddToScope); 5863 } 5864 5865 if (!New) 5866 return nullptr; 5867 5868 // If this has an identifier and is not a function template specialization, 5869 // add it to the scope stack. 5870 if (New->getDeclName() && AddToScope) 5871 PushOnScopeChains(New, S); 5872 5873 if (isInOpenMPDeclareTargetContext()) 5874 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5875 5876 return New; 5877 } 5878 5879 /// Helper method to turn variable array types into constant array 5880 /// types in certain situations which would otherwise be errors (for 5881 /// GCC compatibility). 5882 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5883 ASTContext &Context, 5884 bool &SizeIsNegative, 5885 llvm::APSInt &Oversized) { 5886 // This method tries to turn a variable array into a constant 5887 // array even when the size isn't an ICE. This is necessary 5888 // for compatibility with code that depends on gcc's buggy 5889 // constant expression folding, like struct {char x[(int)(char*)2];} 5890 SizeIsNegative = false; 5891 Oversized = 0; 5892 5893 if (T->isDependentType()) 5894 return QualType(); 5895 5896 QualifierCollector Qs; 5897 const Type *Ty = Qs.strip(T); 5898 5899 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5900 QualType Pointee = PTy->getPointeeType(); 5901 QualType FixedType = 5902 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5903 Oversized); 5904 if (FixedType.isNull()) return FixedType; 5905 FixedType = Context.getPointerType(FixedType); 5906 return Qs.apply(Context, FixedType); 5907 } 5908 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5909 QualType Inner = PTy->getInnerType(); 5910 QualType FixedType = 5911 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5912 Oversized); 5913 if (FixedType.isNull()) return FixedType; 5914 FixedType = Context.getParenType(FixedType); 5915 return Qs.apply(Context, FixedType); 5916 } 5917 5918 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5919 if (!VLATy) 5920 return QualType(); 5921 // FIXME: We should probably handle this case 5922 if (VLATy->getElementType()->isVariablyModifiedType()) 5923 return QualType(); 5924 5925 Expr::EvalResult Result; 5926 if (!VLATy->getSizeExpr() || 5927 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5928 return QualType(); 5929 5930 llvm::APSInt Res = Result.Val.getInt(); 5931 5932 // Check whether the array size is negative. 5933 if (Res.isSigned() && Res.isNegative()) { 5934 SizeIsNegative = true; 5935 return QualType(); 5936 } 5937 5938 // Check whether the array is too large to be addressed. 5939 unsigned ActiveSizeBits 5940 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5941 Res); 5942 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5943 Oversized = Res; 5944 return QualType(); 5945 } 5946 5947 return Context.getConstantArrayType( 5948 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5949 } 5950 5951 static void 5952 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5953 SrcTL = SrcTL.getUnqualifiedLoc(); 5954 DstTL = DstTL.getUnqualifiedLoc(); 5955 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5956 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5957 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5958 DstPTL.getPointeeLoc()); 5959 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5960 return; 5961 } 5962 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5963 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5964 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5965 DstPTL.getInnerLoc()); 5966 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5967 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5968 return; 5969 } 5970 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5971 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5972 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5973 TypeLoc DstElemTL = DstATL.getElementLoc(); 5974 DstElemTL.initializeFullCopy(SrcElemTL); 5975 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5976 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5977 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5978 } 5979 5980 /// Helper method to turn variable array types into constant array 5981 /// types in certain situations which would otherwise be errors (for 5982 /// GCC compatibility). 5983 static TypeSourceInfo* 5984 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5985 ASTContext &Context, 5986 bool &SizeIsNegative, 5987 llvm::APSInt &Oversized) { 5988 QualType FixedTy 5989 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5990 SizeIsNegative, Oversized); 5991 if (FixedTy.isNull()) 5992 return nullptr; 5993 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5994 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5995 FixedTInfo->getTypeLoc()); 5996 return FixedTInfo; 5997 } 5998 5999 /// Register the given locally-scoped extern "C" declaration so 6000 /// that it can be found later for redeclarations. We include any extern "C" 6001 /// declaration that is not visible in the translation unit here, not just 6002 /// function-scope declarations. 6003 void 6004 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6005 if (!getLangOpts().CPlusPlus && 6006 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6007 // Don't need to track declarations in the TU in C. 6008 return; 6009 6010 // Note that we have a locally-scoped external with this name. 6011 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6012 } 6013 6014 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6015 // FIXME: We can have multiple results via __attribute__((overloadable)). 6016 auto Result = Context.getExternCContextDecl()->lookup(Name); 6017 return Result.empty() ? nullptr : *Result.begin(); 6018 } 6019 6020 /// Diagnose function specifiers on a declaration of an identifier that 6021 /// does not identify a function. 6022 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6023 // FIXME: We should probably indicate the identifier in question to avoid 6024 // confusion for constructs like "virtual int a(), b;" 6025 if (DS.isVirtualSpecified()) 6026 Diag(DS.getVirtualSpecLoc(), 6027 diag::err_virtual_non_function); 6028 6029 if (DS.hasExplicitSpecifier()) 6030 Diag(DS.getExplicitSpecLoc(), 6031 diag::err_explicit_non_function); 6032 6033 if (DS.isNoreturnSpecified()) 6034 Diag(DS.getNoreturnSpecLoc(), 6035 diag::err_noreturn_non_function); 6036 } 6037 6038 NamedDecl* 6039 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6040 TypeSourceInfo *TInfo, LookupResult &Previous) { 6041 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6042 if (D.getCXXScopeSpec().isSet()) { 6043 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6044 << D.getCXXScopeSpec().getRange(); 6045 D.setInvalidType(); 6046 // Pretend we didn't see the scope specifier. 6047 DC = CurContext; 6048 Previous.clear(); 6049 } 6050 6051 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6052 6053 if (D.getDeclSpec().isInlineSpecified()) 6054 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6055 << getLangOpts().CPlusPlus17; 6056 if (D.getDeclSpec().hasConstexprSpecifier()) 6057 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6058 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6059 6060 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6061 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6062 Diag(D.getName().StartLocation, 6063 diag::err_deduction_guide_invalid_specifier) 6064 << "typedef"; 6065 else 6066 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6067 << D.getName().getSourceRange(); 6068 return nullptr; 6069 } 6070 6071 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6072 if (!NewTD) return nullptr; 6073 6074 // Handle attributes prior to checking for duplicates in MergeVarDecl 6075 ProcessDeclAttributes(S, NewTD, D); 6076 6077 CheckTypedefForVariablyModifiedType(S, NewTD); 6078 6079 bool Redeclaration = D.isRedeclaration(); 6080 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6081 D.setRedeclaration(Redeclaration); 6082 return ND; 6083 } 6084 6085 void 6086 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6087 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6088 // then it shall have block scope. 6089 // Note that variably modified types must be fixed before merging the decl so 6090 // that redeclarations will match. 6091 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6092 QualType T = TInfo->getType(); 6093 if (T->isVariablyModifiedType()) { 6094 setFunctionHasBranchProtectedScope(); 6095 6096 if (S->getFnParent() == nullptr) { 6097 bool SizeIsNegative; 6098 llvm::APSInt Oversized; 6099 TypeSourceInfo *FixedTInfo = 6100 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6101 SizeIsNegative, 6102 Oversized); 6103 if (FixedTInfo) { 6104 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6105 NewTD->setTypeSourceInfo(FixedTInfo); 6106 } else { 6107 if (SizeIsNegative) 6108 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6109 else if (T->isVariableArrayType()) 6110 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6111 else if (Oversized.getBoolValue()) 6112 Diag(NewTD->getLocation(), diag::err_array_too_large) 6113 << Oversized.toString(10); 6114 else 6115 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6116 NewTD->setInvalidDecl(); 6117 } 6118 } 6119 } 6120 } 6121 6122 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6123 /// declares a typedef-name, either using the 'typedef' type specifier or via 6124 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6125 NamedDecl* 6126 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6127 LookupResult &Previous, bool &Redeclaration) { 6128 6129 // Find the shadowed declaration before filtering for scope. 6130 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6131 6132 // Merge the decl with the existing one if appropriate. If the decl is 6133 // in an outer scope, it isn't the same thing. 6134 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6135 /*AllowInlineNamespace*/false); 6136 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6137 if (!Previous.empty()) { 6138 Redeclaration = true; 6139 MergeTypedefNameDecl(S, NewTD, Previous); 6140 } else { 6141 inferGslPointerAttribute(NewTD); 6142 } 6143 6144 if (ShadowedDecl && !Redeclaration) 6145 CheckShadow(NewTD, ShadowedDecl, Previous); 6146 6147 // If this is the C FILE type, notify the AST context. 6148 if (IdentifierInfo *II = NewTD->getIdentifier()) 6149 if (!NewTD->isInvalidDecl() && 6150 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6151 if (II->isStr("FILE")) 6152 Context.setFILEDecl(NewTD); 6153 else if (II->isStr("jmp_buf")) 6154 Context.setjmp_bufDecl(NewTD); 6155 else if (II->isStr("sigjmp_buf")) 6156 Context.setsigjmp_bufDecl(NewTD); 6157 else if (II->isStr("ucontext_t")) 6158 Context.setucontext_tDecl(NewTD); 6159 } 6160 6161 return NewTD; 6162 } 6163 6164 /// Determines whether the given declaration is an out-of-scope 6165 /// previous declaration. 6166 /// 6167 /// This routine should be invoked when name lookup has found a 6168 /// previous declaration (PrevDecl) that is not in the scope where a 6169 /// new declaration by the same name is being introduced. If the new 6170 /// declaration occurs in a local scope, previous declarations with 6171 /// linkage may still be considered previous declarations (C99 6172 /// 6.2.2p4-5, C++ [basic.link]p6). 6173 /// 6174 /// \param PrevDecl the previous declaration found by name 6175 /// lookup 6176 /// 6177 /// \param DC the context in which the new declaration is being 6178 /// declared. 6179 /// 6180 /// \returns true if PrevDecl is an out-of-scope previous declaration 6181 /// for a new delcaration with the same name. 6182 static bool 6183 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6184 ASTContext &Context) { 6185 if (!PrevDecl) 6186 return false; 6187 6188 if (!PrevDecl->hasLinkage()) 6189 return false; 6190 6191 if (Context.getLangOpts().CPlusPlus) { 6192 // C++ [basic.link]p6: 6193 // If there is a visible declaration of an entity with linkage 6194 // having the same name and type, ignoring entities declared 6195 // outside the innermost enclosing namespace scope, the block 6196 // scope declaration declares that same entity and receives the 6197 // linkage of the previous declaration. 6198 DeclContext *OuterContext = DC->getRedeclContext(); 6199 if (!OuterContext->isFunctionOrMethod()) 6200 // This rule only applies to block-scope declarations. 6201 return false; 6202 6203 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6204 if (PrevOuterContext->isRecord()) 6205 // We found a member function: ignore it. 6206 return false; 6207 6208 // Find the innermost enclosing namespace for the new and 6209 // previous declarations. 6210 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6211 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6212 6213 // The previous declaration is in a different namespace, so it 6214 // isn't the same function. 6215 if (!OuterContext->Equals(PrevOuterContext)) 6216 return false; 6217 } 6218 6219 return true; 6220 } 6221 6222 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6223 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6224 if (!SS.isSet()) return; 6225 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6226 } 6227 6228 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6229 QualType type = decl->getType(); 6230 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6231 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6232 // Various kinds of declaration aren't allowed to be __autoreleasing. 6233 unsigned kind = -1U; 6234 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6235 if (var->hasAttr<BlocksAttr>()) 6236 kind = 0; // __block 6237 else if (!var->hasLocalStorage()) 6238 kind = 1; // global 6239 } else if (isa<ObjCIvarDecl>(decl)) { 6240 kind = 3; // ivar 6241 } else if (isa<FieldDecl>(decl)) { 6242 kind = 2; // field 6243 } 6244 6245 if (kind != -1U) { 6246 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6247 << kind; 6248 } 6249 } else if (lifetime == Qualifiers::OCL_None) { 6250 // Try to infer lifetime. 6251 if (!type->isObjCLifetimeType()) 6252 return false; 6253 6254 lifetime = type->getObjCARCImplicitLifetime(); 6255 type = Context.getLifetimeQualifiedType(type, lifetime); 6256 decl->setType(type); 6257 } 6258 6259 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6260 // Thread-local variables cannot have lifetime. 6261 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6262 var->getTLSKind()) { 6263 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6264 << var->getType(); 6265 return true; 6266 } 6267 } 6268 6269 return false; 6270 } 6271 6272 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6273 if (Decl->getType().hasAddressSpace()) 6274 return; 6275 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6276 QualType Type = Var->getType(); 6277 if (Type->isSamplerT() || Type->isVoidType()) 6278 return; 6279 LangAS ImplAS = LangAS::opencl_private; 6280 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6281 Var->hasGlobalStorage()) 6282 ImplAS = LangAS::opencl_global; 6283 // If the original type from a decayed type is an array type and that array 6284 // type has no address space yet, deduce it now. 6285 if (auto DT = dyn_cast<DecayedType>(Type)) { 6286 auto OrigTy = DT->getOriginalType(); 6287 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6288 // Add the address space to the original array type and then propagate 6289 // that to the element type through `getAsArrayType`. 6290 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6291 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6292 // Re-generate the decayed type. 6293 Type = Context.getDecayedType(OrigTy); 6294 } 6295 } 6296 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6297 // Apply any qualifiers (including address space) from the array type to 6298 // the element type. This implements C99 6.7.3p8: "If the specification of 6299 // an array type includes any type qualifiers, the element type is so 6300 // qualified, not the array type." 6301 if (Type->isArrayType()) 6302 Type = QualType(Context.getAsArrayType(Type), 0); 6303 Decl->setType(Type); 6304 } 6305 } 6306 6307 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6308 // Ensure that an auto decl is deduced otherwise the checks below might cache 6309 // the wrong linkage. 6310 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6311 6312 // 'weak' only applies to declarations with external linkage. 6313 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6314 if (!ND.isExternallyVisible()) { 6315 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6316 ND.dropAttr<WeakAttr>(); 6317 } 6318 } 6319 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6320 if (ND.isExternallyVisible()) { 6321 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6322 ND.dropAttr<WeakRefAttr>(); 6323 ND.dropAttr<AliasAttr>(); 6324 } 6325 } 6326 6327 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6328 if (VD->hasInit()) { 6329 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6330 assert(VD->isThisDeclarationADefinition() && 6331 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6332 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6333 VD->dropAttr<AliasAttr>(); 6334 } 6335 } 6336 } 6337 6338 // 'selectany' only applies to externally visible variable declarations. 6339 // It does not apply to functions. 6340 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6341 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6342 S.Diag(Attr->getLocation(), 6343 diag::err_attribute_selectany_non_extern_data); 6344 ND.dropAttr<SelectAnyAttr>(); 6345 } 6346 } 6347 6348 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6349 auto *VD = dyn_cast<VarDecl>(&ND); 6350 bool IsAnonymousNS = false; 6351 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6352 if (VD) { 6353 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6354 while (NS && !IsAnonymousNS) { 6355 IsAnonymousNS = NS->isAnonymousNamespace(); 6356 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6357 } 6358 } 6359 // dll attributes require external linkage. Static locals may have external 6360 // linkage but still cannot be explicitly imported or exported. 6361 // In Microsoft mode, a variable defined in anonymous namespace must have 6362 // external linkage in order to be exported. 6363 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6364 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6365 (!AnonNSInMicrosoftMode && 6366 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6367 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6368 << &ND << Attr; 6369 ND.setInvalidDecl(); 6370 } 6371 } 6372 6373 // Virtual functions cannot be marked as 'notail'. 6374 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6375 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6376 if (MD->isVirtual()) { 6377 S.Diag(ND.getLocation(), 6378 diag::err_invalid_attribute_on_virtual_function) 6379 << Attr; 6380 ND.dropAttr<NotTailCalledAttr>(); 6381 } 6382 6383 // Check the attributes on the function type, if any. 6384 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6385 // Don't declare this variable in the second operand of the for-statement; 6386 // GCC miscompiles that by ending its lifetime before evaluating the 6387 // third operand. See gcc.gnu.org/PR86769. 6388 AttributedTypeLoc ATL; 6389 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6390 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6391 TL = ATL.getModifiedLoc()) { 6392 // The [[lifetimebound]] attribute can be applied to the implicit object 6393 // parameter of a non-static member function (other than a ctor or dtor) 6394 // by applying it to the function type. 6395 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6396 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6397 if (!MD || MD->isStatic()) { 6398 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6399 << !MD << A->getRange(); 6400 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6401 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6402 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6403 } 6404 } 6405 } 6406 } 6407 } 6408 6409 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6410 NamedDecl *NewDecl, 6411 bool IsSpecialization, 6412 bool IsDefinition) { 6413 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6414 return; 6415 6416 bool IsTemplate = false; 6417 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6418 OldDecl = OldTD->getTemplatedDecl(); 6419 IsTemplate = true; 6420 if (!IsSpecialization) 6421 IsDefinition = false; 6422 } 6423 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6424 NewDecl = NewTD->getTemplatedDecl(); 6425 IsTemplate = true; 6426 } 6427 6428 if (!OldDecl || !NewDecl) 6429 return; 6430 6431 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6432 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6433 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6434 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6435 6436 // dllimport and dllexport are inheritable attributes so we have to exclude 6437 // inherited attribute instances. 6438 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6439 (NewExportAttr && !NewExportAttr->isInherited()); 6440 6441 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6442 // the only exception being explicit specializations. 6443 // Implicitly generated declarations are also excluded for now because there 6444 // is no other way to switch these to use dllimport or dllexport. 6445 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6446 6447 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6448 // Allow with a warning for free functions and global variables. 6449 bool JustWarn = false; 6450 if (!OldDecl->isCXXClassMember()) { 6451 auto *VD = dyn_cast<VarDecl>(OldDecl); 6452 if (VD && !VD->getDescribedVarTemplate()) 6453 JustWarn = true; 6454 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6455 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6456 JustWarn = true; 6457 } 6458 6459 // We cannot change a declaration that's been used because IR has already 6460 // been emitted. Dllimported functions will still work though (modulo 6461 // address equality) as they can use the thunk. 6462 if (OldDecl->isUsed()) 6463 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6464 JustWarn = false; 6465 6466 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6467 : diag::err_attribute_dll_redeclaration; 6468 S.Diag(NewDecl->getLocation(), DiagID) 6469 << NewDecl 6470 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6471 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6472 if (!JustWarn) { 6473 NewDecl->setInvalidDecl(); 6474 return; 6475 } 6476 } 6477 6478 // A redeclaration is not allowed to drop a dllimport attribute, the only 6479 // exceptions being inline function definitions (except for function 6480 // templates), local extern declarations, qualified friend declarations or 6481 // special MSVC extension: in the last case, the declaration is treated as if 6482 // it were marked dllexport. 6483 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6484 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6485 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6486 // Ignore static data because out-of-line definitions are diagnosed 6487 // separately. 6488 IsStaticDataMember = VD->isStaticDataMember(); 6489 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6490 VarDecl::DeclarationOnly; 6491 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6492 IsInline = FD->isInlined(); 6493 IsQualifiedFriend = FD->getQualifier() && 6494 FD->getFriendObjectKind() == Decl::FOK_Declared; 6495 } 6496 6497 if (OldImportAttr && !HasNewAttr && 6498 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6499 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6500 if (IsMicrosoft && IsDefinition) { 6501 S.Diag(NewDecl->getLocation(), 6502 diag::warn_redeclaration_without_import_attribute) 6503 << NewDecl; 6504 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6505 NewDecl->dropAttr<DLLImportAttr>(); 6506 NewDecl->addAttr( 6507 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6508 } else { 6509 S.Diag(NewDecl->getLocation(), 6510 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6511 << NewDecl << OldImportAttr; 6512 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6513 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6514 OldDecl->dropAttr<DLLImportAttr>(); 6515 NewDecl->dropAttr<DLLImportAttr>(); 6516 } 6517 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6518 // In MinGW, seeing a function declared inline drops the dllimport 6519 // attribute. 6520 OldDecl->dropAttr<DLLImportAttr>(); 6521 NewDecl->dropAttr<DLLImportAttr>(); 6522 S.Diag(NewDecl->getLocation(), 6523 diag::warn_dllimport_dropped_from_inline_function) 6524 << NewDecl << OldImportAttr; 6525 } 6526 6527 // A specialization of a class template member function is processed here 6528 // since it's a redeclaration. If the parent class is dllexport, the 6529 // specialization inherits that attribute. This doesn't happen automatically 6530 // since the parent class isn't instantiated until later. 6531 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6532 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6533 !NewImportAttr && !NewExportAttr) { 6534 if (const DLLExportAttr *ParentExportAttr = 6535 MD->getParent()->getAttr<DLLExportAttr>()) { 6536 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6537 NewAttr->setInherited(true); 6538 NewDecl->addAttr(NewAttr); 6539 } 6540 } 6541 } 6542 } 6543 6544 /// Given that we are within the definition of the given function, 6545 /// will that definition behave like C99's 'inline', where the 6546 /// definition is discarded except for optimization purposes? 6547 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6548 // Try to avoid calling GetGVALinkageForFunction. 6549 6550 // All cases of this require the 'inline' keyword. 6551 if (!FD->isInlined()) return false; 6552 6553 // This is only possible in C++ with the gnu_inline attribute. 6554 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6555 return false; 6556 6557 // Okay, go ahead and call the relatively-more-expensive function. 6558 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6559 } 6560 6561 /// Determine whether a variable is extern "C" prior to attaching 6562 /// an initializer. We can't just call isExternC() here, because that 6563 /// will also compute and cache whether the declaration is externally 6564 /// visible, which might change when we attach the initializer. 6565 /// 6566 /// This can only be used if the declaration is known to not be a 6567 /// redeclaration of an internal linkage declaration. 6568 /// 6569 /// For instance: 6570 /// 6571 /// auto x = []{}; 6572 /// 6573 /// Attaching the initializer here makes this declaration not externally 6574 /// visible, because its type has internal linkage. 6575 /// 6576 /// FIXME: This is a hack. 6577 template<typename T> 6578 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6579 if (S.getLangOpts().CPlusPlus) { 6580 // In C++, the overloadable attribute negates the effects of extern "C". 6581 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6582 return false; 6583 6584 // So do CUDA's host/device attributes. 6585 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6586 D->template hasAttr<CUDAHostAttr>())) 6587 return false; 6588 } 6589 return D->isExternC(); 6590 } 6591 6592 static bool shouldConsiderLinkage(const VarDecl *VD) { 6593 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6594 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6595 isa<OMPDeclareMapperDecl>(DC)) 6596 return VD->hasExternalStorage(); 6597 if (DC->isFileContext()) 6598 return true; 6599 if (DC->isRecord()) 6600 return false; 6601 if (isa<RequiresExprBodyDecl>(DC)) 6602 return false; 6603 llvm_unreachable("Unexpected context"); 6604 } 6605 6606 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6607 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6608 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6609 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6610 return true; 6611 if (DC->isRecord()) 6612 return false; 6613 llvm_unreachable("Unexpected context"); 6614 } 6615 6616 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6617 ParsedAttr::Kind Kind) { 6618 // Check decl attributes on the DeclSpec. 6619 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6620 return true; 6621 6622 // Walk the declarator structure, checking decl attributes that were in a type 6623 // position to the decl itself. 6624 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6625 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6626 return true; 6627 } 6628 6629 // Finally, check attributes on the decl itself. 6630 return PD.getAttributes().hasAttribute(Kind); 6631 } 6632 6633 /// Adjust the \c DeclContext for a function or variable that might be a 6634 /// function-local external declaration. 6635 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6636 if (!DC->isFunctionOrMethod()) 6637 return false; 6638 6639 // If this is a local extern function or variable declared within a function 6640 // template, don't add it into the enclosing namespace scope until it is 6641 // instantiated; it might have a dependent type right now. 6642 if (DC->isDependentContext()) 6643 return true; 6644 6645 // C++11 [basic.link]p7: 6646 // When a block scope declaration of an entity with linkage is not found to 6647 // refer to some other declaration, then that entity is a member of the 6648 // innermost enclosing namespace. 6649 // 6650 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6651 // semantically-enclosing namespace, not a lexically-enclosing one. 6652 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6653 DC = DC->getParent(); 6654 return true; 6655 } 6656 6657 /// Returns true if given declaration has external C language linkage. 6658 static bool isDeclExternC(const Decl *D) { 6659 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6660 return FD->isExternC(); 6661 if (const auto *VD = dyn_cast<VarDecl>(D)) 6662 return VD->isExternC(); 6663 6664 llvm_unreachable("Unknown type of decl!"); 6665 } 6666 /// Returns true if there hasn't been any invalid type diagnosed. 6667 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6668 DeclContext *DC, QualType R) { 6669 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6670 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6671 // argument. 6672 if (R->isImageType() || R->isPipeType()) { 6673 Se.Diag(D.getIdentifierLoc(), 6674 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6675 << R; 6676 D.setInvalidType(); 6677 return false; 6678 } 6679 6680 // OpenCL v1.2 s6.9.r: 6681 // The event type cannot be used to declare a program scope variable. 6682 // OpenCL v2.0 s6.9.q: 6683 // The clk_event_t and reserve_id_t types cannot be declared in program 6684 // scope. 6685 if (NULL == S->getParent()) { 6686 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6687 Se.Diag(D.getIdentifierLoc(), 6688 diag::err_invalid_type_for_program_scope_var) 6689 << R; 6690 D.setInvalidType(); 6691 return false; 6692 } 6693 } 6694 6695 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6696 QualType NR = R; 6697 while (NR->isPointerType()) { 6698 if (NR->isFunctionPointerType()) { 6699 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6700 D.setInvalidType(); 6701 return false; 6702 } 6703 NR = NR->getPointeeType(); 6704 } 6705 6706 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6707 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6708 // half array type (unless the cl_khr_fp16 extension is enabled). 6709 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6710 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6711 D.setInvalidType(); 6712 return false; 6713 } 6714 } 6715 6716 // OpenCL v1.2 s6.9.r: 6717 // The event type cannot be used with the __local, __constant and __global 6718 // address space qualifiers. 6719 if (R->isEventT()) { 6720 if (R.getAddressSpace() != LangAS::opencl_private) { 6721 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6722 D.setInvalidType(); 6723 return false; 6724 } 6725 } 6726 6727 // C++ for OpenCL does not allow the thread_local storage qualifier. 6728 // OpenCL C does not support thread_local either, and 6729 // also reject all other thread storage class specifiers. 6730 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6731 if (TSC != TSCS_unspecified) { 6732 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6733 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6734 diag::err_opencl_unknown_type_specifier) 6735 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6736 << DeclSpec::getSpecifierName(TSC) << 1; 6737 D.setInvalidType(); 6738 return false; 6739 } 6740 6741 if (R->isSamplerT()) { 6742 // OpenCL v1.2 s6.9.b p4: 6743 // The sampler type cannot be used with the __local and __global address 6744 // space qualifiers. 6745 if (R.getAddressSpace() == LangAS::opencl_local || 6746 R.getAddressSpace() == LangAS::opencl_global) { 6747 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6748 D.setInvalidType(); 6749 } 6750 6751 // OpenCL v1.2 s6.12.14.1: 6752 // A global sampler must be declared with either the constant address 6753 // space qualifier or with the const qualifier. 6754 if (DC->isTranslationUnit() && 6755 !(R.getAddressSpace() == LangAS::opencl_constant || 6756 R.isConstQualified())) { 6757 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6758 D.setInvalidType(); 6759 } 6760 if (D.isInvalidType()) 6761 return false; 6762 } 6763 return true; 6764 } 6765 6766 NamedDecl *Sema::ActOnVariableDeclarator( 6767 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6768 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6769 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6770 QualType R = TInfo->getType(); 6771 DeclarationName Name = GetNameForDeclarator(D).getName(); 6772 6773 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6774 6775 if (D.isDecompositionDeclarator()) { 6776 // Take the name of the first declarator as our name for diagnostic 6777 // purposes. 6778 auto &Decomp = D.getDecompositionDeclarator(); 6779 if (!Decomp.bindings().empty()) { 6780 II = Decomp.bindings()[0].Name; 6781 Name = II; 6782 } 6783 } else if (!II) { 6784 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6785 return nullptr; 6786 } 6787 6788 6789 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6790 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6791 6792 // dllimport globals without explicit storage class are treated as extern. We 6793 // have to change the storage class this early to get the right DeclContext. 6794 if (SC == SC_None && !DC->isRecord() && 6795 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6796 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6797 SC = SC_Extern; 6798 6799 DeclContext *OriginalDC = DC; 6800 bool IsLocalExternDecl = SC == SC_Extern && 6801 adjustContextForLocalExternDecl(DC); 6802 6803 if (SCSpec == DeclSpec::SCS_mutable) { 6804 // mutable can only appear on non-static class members, so it's always 6805 // an error here 6806 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6807 D.setInvalidType(); 6808 SC = SC_None; 6809 } 6810 6811 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6812 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6813 D.getDeclSpec().getStorageClassSpecLoc())) { 6814 // In C++11, the 'register' storage class specifier is deprecated. 6815 // Suppress the warning in system macros, it's used in macros in some 6816 // popular C system headers, such as in glibc's htonl() macro. 6817 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6818 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6819 : diag::warn_deprecated_register) 6820 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6821 } 6822 6823 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6824 6825 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6826 // C99 6.9p2: The storage-class specifiers auto and register shall not 6827 // appear in the declaration specifiers in an external declaration. 6828 // Global Register+Asm is a GNU extension we support. 6829 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6830 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6831 D.setInvalidType(); 6832 } 6833 } 6834 6835 bool IsMemberSpecialization = false; 6836 bool IsVariableTemplateSpecialization = false; 6837 bool IsPartialSpecialization = false; 6838 bool IsVariableTemplate = false; 6839 VarDecl *NewVD = nullptr; 6840 VarTemplateDecl *NewTemplate = nullptr; 6841 TemplateParameterList *TemplateParams = nullptr; 6842 if (!getLangOpts().CPlusPlus) { 6843 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6844 II, R, TInfo, SC); 6845 6846 if (R->getContainedDeducedType()) 6847 ParsingInitForAutoVars.insert(NewVD); 6848 6849 if (D.isInvalidType()) 6850 NewVD->setInvalidDecl(); 6851 6852 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6853 NewVD->hasLocalStorage()) 6854 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6855 NTCUC_AutoVar, NTCUK_Destruct); 6856 } else { 6857 bool Invalid = false; 6858 6859 if (DC->isRecord() && !CurContext->isRecord()) { 6860 // This is an out-of-line definition of a static data member. 6861 switch (SC) { 6862 case SC_None: 6863 break; 6864 case SC_Static: 6865 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6866 diag::err_static_out_of_line) 6867 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6868 break; 6869 case SC_Auto: 6870 case SC_Register: 6871 case SC_Extern: 6872 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6873 // to names of variables declared in a block or to function parameters. 6874 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6875 // of class members 6876 6877 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6878 diag::err_storage_class_for_static_member) 6879 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6880 break; 6881 case SC_PrivateExtern: 6882 llvm_unreachable("C storage class in c++!"); 6883 } 6884 } 6885 6886 if (SC == SC_Static && CurContext->isRecord()) { 6887 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6888 // Walk up the enclosing DeclContexts to check for any that are 6889 // incompatible with static data members. 6890 const DeclContext *FunctionOrMethod = nullptr; 6891 const CXXRecordDecl *AnonStruct = nullptr; 6892 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6893 if (Ctxt->isFunctionOrMethod()) { 6894 FunctionOrMethod = Ctxt; 6895 break; 6896 } 6897 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6898 if (ParentDecl && !ParentDecl->getDeclName()) { 6899 AnonStruct = ParentDecl; 6900 break; 6901 } 6902 } 6903 if (FunctionOrMethod) { 6904 // C++ [class.static.data]p5: A local class shall not have static data 6905 // members. 6906 Diag(D.getIdentifierLoc(), 6907 diag::err_static_data_member_not_allowed_in_local_class) 6908 << Name << RD->getDeclName() << RD->getTagKind(); 6909 } else if (AnonStruct) { 6910 // C++ [class.static.data]p4: Unnamed classes and classes contained 6911 // directly or indirectly within unnamed classes shall not contain 6912 // static data members. 6913 Diag(D.getIdentifierLoc(), 6914 diag::err_static_data_member_not_allowed_in_anon_struct) 6915 << Name << AnonStruct->getTagKind(); 6916 Invalid = true; 6917 } else if (RD->isUnion()) { 6918 // C++98 [class.union]p1: If a union contains a static data member, 6919 // the program is ill-formed. C++11 drops this restriction. 6920 Diag(D.getIdentifierLoc(), 6921 getLangOpts().CPlusPlus11 6922 ? diag::warn_cxx98_compat_static_data_member_in_union 6923 : diag::ext_static_data_member_in_union) << Name; 6924 } 6925 } 6926 } 6927 6928 // Match up the template parameter lists with the scope specifier, then 6929 // determine whether we have a template or a template specialization. 6930 bool InvalidScope = false; 6931 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6932 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6933 D.getCXXScopeSpec(), 6934 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6935 ? D.getName().TemplateId 6936 : nullptr, 6937 TemplateParamLists, 6938 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6939 Invalid |= InvalidScope; 6940 6941 if (TemplateParams) { 6942 if (!TemplateParams->size() && 6943 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6944 // There is an extraneous 'template<>' for this variable. Complain 6945 // about it, but allow the declaration of the variable. 6946 Diag(TemplateParams->getTemplateLoc(), 6947 diag::err_template_variable_noparams) 6948 << II 6949 << SourceRange(TemplateParams->getTemplateLoc(), 6950 TemplateParams->getRAngleLoc()); 6951 TemplateParams = nullptr; 6952 } else { 6953 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6954 // This is an explicit specialization or a partial specialization. 6955 // FIXME: Check that we can declare a specialization here. 6956 IsVariableTemplateSpecialization = true; 6957 IsPartialSpecialization = TemplateParams->size() > 0; 6958 } else { // if (TemplateParams->size() > 0) 6959 // This is a template declaration. 6960 IsVariableTemplate = true; 6961 6962 // Check that we can declare a template here. 6963 if (CheckTemplateDeclScope(S, TemplateParams)) 6964 return nullptr; 6965 6966 // Only C++1y supports variable templates (N3651). 6967 Diag(D.getIdentifierLoc(), 6968 getLangOpts().CPlusPlus14 6969 ? diag::warn_cxx11_compat_variable_template 6970 : diag::ext_variable_template); 6971 } 6972 } 6973 } else { 6974 assert((Invalid || 6975 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6976 "should have a 'template<>' for this decl"); 6977 } 6978 6979 if (IsVariableTemplateSpecialization) { 6980 SourceLocation TemplateKWLoc = 6981 TemplateParamLists.size() > 0 6982 ? TemplateParamLists[0]->getTemplateLoc() 6983 : SourceLocation(); 6984 DeclResult Res = ActOnVarTemplateSpecialization( 6985 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6986 IsPartialSpecialization); 6987 if (Res.isInvalid()) 6988 return nullptr; 6989 NewVD = cast<VarDecl>(Res.get()); 6990 AddToScope = false; 6991 } else if (D.isDecompositionDeclarator()) { 6992 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6993 D.getIdentifierLoc(), R, TInfo, SC, 6994 Bindings); 6995 } else 6996 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6997 D.getIdentifierLoc(), II, R, TInfo, SC); 6998 6999 // If this is supposed to be a variable template, create it as such. 7000 if (IsVariableTemplate) { 7001 NewTemplate = 7002 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7003 TemplateParams, NewVD); 7004 NewVD->setDescribedVarTemplate(NewTemplate); 7005 } 7006 7007 // If this decl has an auto type in need of deduction, make a note of the 7008 // Decl so we can diagnose uses of it in its own initializer. 7009 if (R->getContainedDeducedType()) 7010 ParsingInitForAutoVars.insert(NewVD); 7011 7012 if (D.isInvalidType() || Invalid) { 7013 NewVD->setInvalidDecl(); 7014 if (NewTemplate) 7015 NewTemplate->setInvalidDecl(); 7016 } 7017 7018 SetNestedNameSpecifier(*this, NewVD, D); 7019 7020 // If we have any template parameter lists that don't directly belong to 7021 // the variable (matching the scope specifier), store them. 7022 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7023 if (TemplateParamLists.size() > VDTemplateParamLists) 7024 NewVD->setTemplateParameterListsInfo( 7025 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7026 } 7027 7028 if (D.getDeclSpec().isInlineSpecified()) { 7029 if (!getLangOpts().CPlusPlus) { 7030 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7031 << 0; 7032 } else if (CurContext->isFunctionOrMethod()) { 7033 // 'inline' is not allowed on block scope variable declaration. 7034 Diag(D.getDeclSpec().getInlineSpecLoc(), 7035 diag::err_inline_declaration_block_scope) << Name 7036 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7037 } else { 7038 Diag(D.getDeclSpec().getInlineSpecLoc(), 7039 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7040 : diag::ext_inline_variable); 7041 NewVD->setInlineSpecified(); 7042 } 7043 } 7044 7045 // Set the lexical context. If the declarator has a C++ scope specifier, the 7046 // lexical context will be different from the semantic context. 7047 NewVD->setLexicalDeclContext(CurContext); 7048 if (NewTemplate) 7049 NewTemplate->setLexicalDeclContext(CurContext); 7050 7051 if (IsLocalExternDecl) { 7052 if (D.isDecompositionDeclarator()) 7053 for (auto *B : Bindings) 7054 B->setLocalExternDecl(); 7055 else 7056 NewVD->setLocalExternDecl(); 7057 } 7058 7059 bool EmitTLSUnsupportedError = false; 7060 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7061 // C++11 [dcl.stc]p4: 7062 // When thread_local is applied to a variable of block scope the 7063 // storage-class-specifier static is implied if it does not appear 7064 // explicitly. 7065 // Core issue: 'static' is not implied if the variable is declared 7066 // 'extern'. 7067 if (NewVD->hasLocalStorage() && 7068 (SCSpec != DeclSpec::SCS_unspecified || 7069 TSCS != DeclSpec::TSCS_thread_local || 7070 !DC->isFunctionOrMethod())) 7071 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7072 diag::err_thread_non_global) 7073 << DeclSpec::getSpecifierName(TSCS); 7074 else if (!Context.getTargetInfo().isTLSSupported()) { 7075 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7076 // Postpone error emission until we've collected attributes required to 7077 // figure out whether it's a host or device variable and whether the 7078 // error should be ignored. 7079 EmitTLSUnsupportedError = true; 7080 // We still need to mark the variable as TLS so it shows up in AST with 7081 // proper storage class for other tools to use even if we're not going 7082 // to emit any code for it. 7083 NewVD->setTSCSpec(TSCS); 7084 } else 7085 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7086 diag::err_thread_unsupported); 7087 } else 7088 NewVD->setTSCSpec(TSCS); 7089 } 7090 7091 switch (D.getDeclSpec().getConstexprSpecifier()) { 7092 case CSK_unspecified: 7093 break; 7094 7095 case CSK_consteval: 7096 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7097 diag::err_constexpr_wrong_decl_kind) 7098 << D.getDeclSpec().getConstexprSpecifier(); 7099 LLVM_FALLTHROUGH; 7100 7101 case CSK_constexpr: 7102 NewVD->setConstexpr(true); 7103 // C++1z [dcl.spec.constexpr]p1: 7104 // A static data member declared with the constexpr specifier is 7105 // implicitly an inline variable. 7106 if (NewVD->isStaticDataMember() && 7107 (getLangOpts().CPlusPlus17 || 7108 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7109 NewVD->setImplicitlyInline(); 7110 break; 7111 7112 case CSK_constinit: 7113 if (!NewVD->hasGlobalStorage()) 7114 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7115 diag::err_constinit_local_variable); 7116 else 7117 NewVD->addAttr(ConstInitAttr::Create( 7118 Context, D.getDeclSpec().getConstexprSpecLoc(), 7119 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7120 break; 7121 } 7122 7123 // C99 6.7.4p3 7124 // An inline definition of a function with external linkage shall 7125 // not contain a definition of a modifiable object with static or 7126 // thread storage duration... 7127 // We only apply this when the function is required to be defined 7128 // elsewhere, i.e. when the function is not 'extern inline'. Note 7129 // that a local variable with thread storage duration still has to 7130 // be marked 'static'. Also note that it's possible to get these 7131 // semantics in C++ using __attribute__((gnu_inline)). 7132 if (SC == SC_Static && S->getFnParent() != nullptr && 7133 !NewVD->getType().isConstQualified()) { 7134 FunctionDecl *CurFD = getCurFunctionDecl(); 7135 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7136 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7137 diag::warn_static_local_in_extern_inline); 7138 MaybeSuggestAddingStaticToDecl(CurFD); 7139 } 7140 } 7141 7142 if (D.getDeclSpec().isModulePrivateSpecified()) { 7143 if (IsVariableTemplateSpecialization) 7144 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7145 << (IsPartialSpecialization ? 1 : 0) 7146 << FixItHint::CreateRemoval( 7147 D.getDeclSpec().getModulePrivateSpecLoc()); 7148 else if (IsMemberSpecialization) 7149 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7150 << 2 7151 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7152 else if (NewVD->hasLocalStorage()) 7153 Diag(NewVD->getLocation(), diag::err_module_private_local) 7154 << 0 << NewVD->getDeclName() 7155 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7156 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7157 else { 7158 NewVD->setModulePrivate(); 7159 if (NewTemplate) 7160 NewTemplate->setModulePrivate(); 7161 for (auto *B : Bindings) 7162 B->setModulePrivate(); 7163 } 7164 } 7165 7166 if (getLangOpts().OpenCL) { 7167 7168 deduceOpenCLAddressSpace(NewVD); 7169 7170 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7171 } 7172 7173 // Handle attributes prior to checking for duplicates in MergeVarDecl 7174 ProcessDeclAttributes(S, NewVD, D); 7175 7176 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7177 if (EmitTLSUnsupportedError && 7178 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7179 (getLangOpts().OpenMPIsDevice && 7180 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7181 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7182 diag::err_thread_unsupported); 7183 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7184 // storage [duration]." 7185 if (SC == SC_None && S->getFnParent() != nullptr && 7186 (NewVD->hasAttr<CUDASharedAttr>() || 7187 NewVD->hasAttr<CUDAConstantAttr>())) { 7188 NewVD->setStorageClass(SC_Static); 7189 } 7190 } 7191 7192 // Ensure that dllimport globals without explicit storage class are treated as 7193 // extern. The storage class is set above using parsed attributes. Now we can 7194 // check the VarDecl itself. 7195 assert(!NewVD->hasAttr<DLLImportAttr>() || 7196 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7197 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7198 7199 // In auto-retain/release, infer strong retension for variables of 7200 // retainable type. 7201 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7202 NewVD->setInvalidDecl(); 7203 7204 // Handle GNU asm-label extension (encoded as an attribute). 7205 if (Expr *E = (Expr*)D.getAsmLabel()) { 7206 // The parser guarantees this is a string. 7207 StringLiteral *SE = cast<StringLiteral>(E); 7208 StringRef Label = SE->getString(); 7209 if (S->getFnParent() != nullptr) { 7210 switch (SC) { 7211 case SC_None: 7212 case SC_Auto: 7213 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7214 break; 7215 case SC_Register: 7216 // Local Named register 7217 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7218 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7219 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7220 break; 7221 case SC_Static: 7222 case SC_Extern: 7223 case SC_PrivateExtern: 7224 break; 7225 } 7226 } else if (SC == SC_Register) { 7227 // Global Named register 7228 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7229 const auto &TI = Context.getTargetInfo(); 7230 bool HasSizeMismatch; 7231 7232 if (!TI.isValidGCCRegisterName(Label)) 7233 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7234 else if (!TI.validateGlobalRegisterVariable(Label, 7235 Context.getTypeSize(R), 7236 HasSizeMismatch)) 7237 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7238 else if (HasSizeMismatch) 7239 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7240 } 7241 7242 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7243 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7244 NewVD->setInvalidDecl(true); 7245 } 7246 } 7247 7248 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7249 /*IsLiteralLabel=*/true, 7250 SE->getStrTokenLoc(0))); 7251 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7252 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7253 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7254 if (I != ExtnameUndeclaredIdentifiers.end()) { 7255 if (isDeclExternC(NewVD)) { 7256 NewVD->addAttr(I->second); 7257 ExtnameUndeclaredIdentifiers.erase(I); 7258 } else 7259 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7260 << /*Variable*/1 << NewVD; 7261 } 7262 } 7263 7264 // Find the shadowed declaration before filtering for scope. 7265 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7266 ? getShadowedDeclaration(NewVD, Previous) 7267 : nullptr; 7268 7269 // Don't consider existing declarations that are in a different 7270 // scope and are out-of-semantic-context declarations (if the new 7271 // declaration has linkage). 7272 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7273 D.getCXXScopeSpec().isNotEmpty() || 7274 IsMemberSpecialization || 7275 IsVariableTemplateSpecialization); 7276 7277 // Check whether the previous declaration is in the same block scope. This 7278 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7279 if (getLangOpts().CPlusPlus && 7280 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7281 NewVD->setPreviousDeclInSameBlockScope( 7282 Previous.isSingleResult() && !Previous.isShadowed() && 7283 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7284 7285 if (!getLangOpts().CPlusPlus) { 7286 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7287 } else { 7288 // If this is an explicit specialization of a static data member, check it. 7289 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7290 CheckMemberSpecialization(NewVD, Previous)) 7291 NewVD->setInvalidDecl(); 7292 7293 // Merge the decl with the existing one if appropriate. 7294 if (!Previous.empty()) { 7295 if (Previous.isSingleResult() && 7296 isa<FieldDecl>(Previous.getFoundDecl()) && 7297 D.getCXXScopeSpec().isSet()) { 7298 // The user tried to define a non-static data member 7299 // out-of-line (C++ [dcl.meaning]p1). 7300 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7301 << D.getCXXScopeSpec().getRange(); 7302 Previous.clear(); 7303 NewVD->setInvalidDecl(); 7304 } 7305 } else if (D.getCXXScopeSpec().isSet()) { 7306 // No previous declaration in the qualifying scope. 7307 Diag(D.getIdentifierLoc(), diag::err_no_member) 7308 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7309 << D.getCXXScopeSpec().getRange(); 7310 NewVD->setInvalidDecl(); 7311 } 7312 7313 if (!IsVariableTemplateSpecialization) 7314 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7315 7316 if (NewTemplate) { 7317 VarTemplateDecl *PrevVarTemplate = 7318 NewVD->getPreviousDecl() 7319 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7320 : nullptr; 7321 7322 // Check the template parameter list of this declaration, possibly 7323 // merging in the template parameter list from the previous variable 7324 // template declaration. 7325 if (CheckTemplateParameterList( 7326 TemplateParams, 7327 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7328 : nullptr, 7329 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7330 DC->isDependentContext()) 7331 ? TPC_ClassTemplateMember 7332 : TPC_VarTemplate)) 7333 NewVD->setInvalidDecl(); 7334 7335 // If we are providing an explicit specialization of a static variable 7336 // template, make a note of that. 7337 if (PrevVarTemplate && 7338 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7339 PrevVarTemplate->setMemberSpecialization(); 7340 } 7341 } 7342 7343 // Diagnose shadowed variables iff this isn't a redeclaration. 7344 if (ShadowedDecl && !D.isRedeclaration()) 7345 CheckShadow(NewVD, ShadowedDecl, Previous); 7346 7347 ProcessPragmaWeak(S, NewVD); 7348 7349 // If this is the first declaration of an extern C variable, update 7350 // the map of such variables. 7351 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7352 isIncompleteDeclExternC(*this, NewVD)) 7353 RegisterLocallyScopedExternCDecl(NewVD, S); 7354 7355 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7356 MangleNumberingContext *MCtx; 7357 Decl *ManglingContextDecl; 7358 std::tie(MCtx, ManglingContextDecl) = 7359 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7360 if (MCtx) { 7361 Context.setManglingNumber( 7362 NewVD, MCtx->getManglingNumber( 7363 NewVD, getMSManglingNumber(getLangOpts(), S))); 7364 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7365 } 7366 } 7367 7368 // Special handling of variable named 'main'. 7369 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7370 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7371 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7372 7373 // C++ [basic.start.main]p3 7374 // A program that declares a variable main at global scope is ill-formed. 7375 if (getLangOpts().CPlusPlus) 7376 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7377 7378 // In C, and external-linkage variable named main results in undefined 7379 // behavior. 7380 else if (NewVD->hasExternalFormalLinkage()) 7381 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7382 } 7383 7384 if (D.isRedeclaration() && !Previous.empty()) { 7385 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7386 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7387 D.isFunctionDefinition()); 7388 } 7389 7390 if (NewTemplate) { 7391 if (NewVD->isInvalidDecl()) 7392 NewTemplate->setInvalidDecl(); 7393 ActOnDocumentableDecl(NewTemplate); 7394 return NewTemplate; 7395 } 7396 7397 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7398 CompleteMemberSpecialization(NewVD, Previous); 7399 7400 return NewVD; 7401 } 7402 7403 /// Enum describing the %select options in diag::warn_decl_shadow. 7404 enum ShadowedDeclKind { 7405 SDK_Local, 7406 SDK_Global, 7407 SDK_StaticMember, 7408 SDK_Field, 7409 SDK_Typedef, 7410 SDK_Using 7411 }; 7412 7413 /// Determine what kind of declaration we're shadowing. 7414 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7415 const DeclContext *OldDC) { 7416 if (isa<TypeAliasDecl>(ShadowedDecl)) 7417 return SDK_Using; 7418 else if (isa<TypedefDecl>(ShadowedDecl)) 7419 return SDK_Typedef; 7420 else if (isa<RecordDecl>(OldDC)) 7421 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7422 7423 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7424 } 7425 7426 /// Return the location of the capture if the given lambda captures the given 7427 /// variable \p VD, or an invalid source location otherwise. 7428 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7429 const VarDecl *VD) { 7430 for (const Capture &Capture : LSI->Captures) { 7431 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7432 return Capture.getLocation(); 7433 } 7434 return SourceLocation(); 7435 } 7436 7437 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7438 const LookupResult &R) { 7439 // Only diagnose if we're shadowing an unambiguous field or variable. 7440 if (R.getResultKind() != LookupResult::Found) 7441 return false; 7442 7443 // Return false if warning is ignored. 7444 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7445 } 7446 7447 /// Return the declaration shadowed by the given variable \p D, or null 7448 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7449 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7450 const LookupResult &R) { 7451 if (!shouldWarnIfShadowedDecl(Diags, R)) 7452 return nullptr; 7453 7454 // Don't diagnose declarations at file scope. 7455 if (D->hasGlobalStorage()) 7456 return nullptr; 7457 7458 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7459 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7460 ? ShadowedDecl 7461 : nullptr; 7462 } 7463 7464 /// Return the declaration shadowed by the given typedef \p D, or null 7465 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7466 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7467 const LookupResult &R) { 7468 // Don't warn if typedef declaration is part of a class 7469 if (D->getDeclContext()->isRecord()) 7470 return nullptr; 7471 7472 if (!shouldWarnIfShadowedDecl(Diags, R)) 7473 return nullptr; 7474 7475 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7476 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7477 } 7478 7479 /// Diagnose variable or built-in function shadowing. Implements 7480 /// -Wshadow. 7481 /// 7482 /// This method is called whenever a VarDecl is added to a "useful" 7483 /// scope. 7484 /// 7485 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7486 /// \param R the lookup of the name 7487 /// 7488 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7489 const LookupResult &R) { 7490 DeclContext *NewDC = D->getDeclContext(); 7491 7492 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7493 // Fields are not shadowed by variables in C++ static methods. 7494 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7495 if (MD->isStatic()) 7496 return; 7497 7498 // Fields shadowed by constructor parameters are a special case. Usually 7499 // the constructor initializes the field with the parameter. 7500 if (isa<CXXConstructorDecl>(NewDC)) 7501 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7502 // Remember that this was shadowed so we can either warn about its 7503 // modification or its existence depending on warning settings. 7504 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7505 return; 7506 } 7507 } 7508 7509 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7510 if (shadowedVar->isExternC()) { 7511 // For shadowing external vars, make sure that we point to the global 7512 // declaration, not a locally scoped extern declaration. 7513 for (auto I : shadowedVar->redecls()) 7514 if (I->isFileVarDecl()) { 7515 ShadowedDecl = I; 7516 break; 7517 } 7518 } 7519 7520 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7521 7522 unsigned WarningDiag = diag::warn_decl_shadow; 7523 SourceLocation CaptureLoc; 7524 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7525 isa<CXXMethodDecl>(NewDC)) { 7526 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7527 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7528 if (RD->getLambdaCaptureDefault() == LCD_None) { 7529 // Try to avoid warnings for lambdas with an explicit capture list. 7530 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7531 // Warn only when the lambda captures the shadowed decl explicitly. 7532 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7533 if (CaptureLoc.isInvalid()) 7534 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7535 } else { 7536 // Remember that this was shadowed so we can avoid the warning if the 7537 // shadowed decl isn't captured and the warning settings allow it. 7538 cast<LambdaScopeInfo>(getCurFunction()) 7539 ->ShadowingDecls.push_back( 7540 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7541 return; 7542 } 7543 } 7544 7545 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7546 // A variable can't shadow a local variable in an enclosing scope, if 7547 // they are separated by a non-capturing declaration context. 7548 for (DeclContext *ParentDC = NewDC; 7549 ParentDC && !ParentDC->Equals(OldDC); 7550 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7551 // Only block literals, captured statements, and lambda expressions 7552 // can capture; other scopes don't. 7553 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7554 !isLambdaCallOperator(ParentDC)) { 7555 return; 7556 } 7557 } 7558 } 7559 } 7560 } 7561 7562 // Only warn about certain kinds of shadowing for class members. 7563 if (NewDC && NewDC->isRecord()) { 7564 // In particular, don't warn about shadowing non-class members. 7565 if (!OldDC->isRecord()) 7566 return; 7567 7568 // TODO: should we warn about static data members shadowing 7569 // static data members from base classes? 7570 7571 // TODO: don't diagnose for inaccessible shadowed members. 7572 // This is hard to do perfectly because we might friend the 7573 // shadowing context, but that's just a false negative. 7574 } 7575 7576 7577 DeclarationName Name = R.getLookupName(); 7578 7579 // Emit warning and note. 7580 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7581 return; 7582 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7583 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7584 if (!CaptureLoc.isInvalid()) 7585 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7586 << Name << /*explicitly*/ 1; 7587 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7588 } 7589 7590 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7591 /// when these variables are captured by the lambda. 7592 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7593 for (const auto &Shadow : LSI->ShadowingDecls) { 7594 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7595 // Try to avoid the warning when the shadowed decl isn't captured. 7596 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7597 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7598 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7599 ? diag::warn_decl_shadow_uncaptured_local 7600 : diag::warn_decl_shadow) 7601 << Shadow.VD->getDeclName() 7602 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7603 if (!CaptureLoc.isInvalid()) 7604 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7605 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7606 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7607 } 7608 } 7609 7610 /// Check -Wshadow without the advantage of a previous lookup. 7611 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7612 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7613 return; 7614 7615 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7616 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7617 LookupName(R, S); 7618 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7619 CheckShadow(D, ShadowedDecl, R); 7620 } 7621 7622 /// Check if 'E', which is an expression that is about to be modified, refers 7623 /// to a constructor parameter that shadows a field. 7624 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7625 // Quickly ignore expressions that can't be shadowing ctor parameters. 7626 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7627 return; 7628 E = E->IgnoreParenImpCasts(); 7629 auto *DRE = dyn_cast<DeclRefExpr>(E); 7630 if (!DRE) 7631 return; 7632 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7633 auto I = ShadowingDecls.find(D); 7634 if (I == ShadowingDecls.end()) 7635 return; 7636 const NamedDecl *ShadowedDecl = I->second; 7637 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7638 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7639 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7640 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7641 7642 // Avoid issuing multiple warnings about the same decl. 7643 ShadowingDecls.erase(I); 7644 } 7645 7646 /// Check for conflict between this global or extern "C" declaration and 7647 /// previous global or extern "C" declarations. This is only used in C++. 7648 template<typename T> 7649 static bool checkGlobalOrExternCConflict( 7650 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7651 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7652 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7653 7654 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7655 // The common case: this global doesn't conflict with any extern "C" 7656 // declaration. 7657 return false; 7658 } 7659 7660 if (Prev) { 7661 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7662 // Both the old and new declarations have C language linkage. This is a 7663 // redeclaration. 7664 Previous.clear(); 7665 Previous.addDecl(Prev); 7666 return true; 7667 } 7668 7669 // This is a global, non-extern "C" declaration, and there is a previous 7670 // non-global extern "C" declaration. Diagnose if this is a variable 7671 // declaration. 7672 if (!isa<VarDecl>(ND)) 7673 return false; 7674 } else { 7675 // The declaration is extern "C". Check for any declaration in the 7676 // translation unit which might conflict. 7677 if (IsGlobal) { 7678 // We have already performed the lookup into the translation unit. 7679 IsGlobal = false; 7680 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7681 I != E; ++I) { 7682 if (isa<VarDecl>(*I)) { 7683 Prev = *I; 7684 break; 7685 } 7686 } 7687 } else { 7688 DeclContext::lookup_result R = 7689 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7690 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7691 I != E; ++I) { 7692 if (isa<VarDecl>(*I)) { 7693 Prev = *I; 7694 break; 7695 } 7696 // FIXME: If we have any other entity with this name in global scope, 7697 // the declaration is ill-formed, but that is a defect: it breaks the 7698 // 'stat' hack, for instance. Only variables can have mangled name 7699 // clashes with extern "C" declarations, so only they deserve a 7700 // diagnostic. 7701 } 7702 } 7703 7704 if (!Prev) 7705 return false; 7706 } 7707 7708 // Use the first declaration's location to ensure we point at something which 7709 // is lexically inside an extern "C" linkage-spec. 7710 assert(Prev && "should have found a previous declaration to diagnose"); 7711 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7712 Prev = FD->getFirstDecl(); 7713 else 7714 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7715 7716 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7717 << IsGlobal << ND; 7718 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7719 << IsGlobal; 7720 return false; 7721 } 7722 7723 /// Apply special rules for handling extern "C" declarations. Returns \c true 7724 /// if we have found that this is a redeclaration of some prior entity. 7725 /// 7726 /// Per C++ [dcl.link]p6: 7727 /// Two declarations [for a function or variable] with C language linkage 7728 /// with the same name that appear in different scopes refer to the same 7729 /// [entity]. An entity with C language linkage shall not be declared with 7730 /// the same name as an entity in global scope. 7731 template<typename T> 7732 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7733 LookupResult &Previous) { 7734 if (!S.getLangOpts().CPlusPlus) { 7735 // In C, when declaring a global variable, look for a corresponding 'extern' 7736 // variable declared in function scope. We don't need this in C++, because 7737 // we find local extern decls in the surrounding file-scope DeclContext. 7738 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7739 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7740 Previous.clear(); 7741 Previous.addDecl(Prev); 7742 return true; 7743 } 7744 } 7745 return false; 7746 } 7747 7748 // A declaration in the translation unit can conflict with an extern "C" 7749 // declaration. 7750 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7751 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7752 7753 // An extern "C" declaration can conflict with a declaration in the 7754 // translation unit or can be a redeclaration of an extern "C" declaration 7755 // in another scope. 7756 if (isIncompleteDeclExternC(S,ND)) 7757 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7758 7759 // Neither global nor extern "C": nothing to do. 7760 return false; 7761 } 7762 7763 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7764 // If the decl is already known invalid, don't check it. 7765 if (NewVD->isInvalidDecl()) 7766 return; 7767 7768 QualType T = NewVD->getType(); 7769 7770 // Defer checking an 'auto' type until its initializer is attached. 7771 if (T->isUndeducedType()) 7772 return; 7773 7774 if (NewVD->hasAttrs()) 7775 CheckAlignasUnderalignment(NewVD); 7776 7777 if (T->isObjCObjectType()) { 7778 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7779 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7780 T = Context.getObjCObjectPointerType(T); 7781 NewVD->setType(T); 7782 } 7783 7784 // Emit an error if an address space was applied to decl with local storage. 7785 // This includes arrays of objects with address space qualifiers, but not 7786 // automatic variables that point to other address spaces. 7787 // ISO/IEC TR 18037 S5.1.2 7788 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7789 T.getAddressSpace() != LangAS::Default) { 7790 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7791 NewVD->setInvalidDecl(); 7792 return; 7793 } 7794 7795 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7796 // scope. 7797 if (getLangOpts().OpenCLVersion == 120 && 7798 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7799 NewVD->isStaticLocal()) { 7800 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7801 NewVD->setInvalidDecl(); 7802 return; 7803 } 7804 7805 if (getLangOpts().OpenCL) { 7806 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7807 if (NewVD->hasAttr<BlocksAttr>()) { 7808 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7809 return; 7810 } 7811 7812 if (T->isBlockPointerType()) { 7813 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7814 // can't use 'extern' storage class. 7815 if (!T.isConstQualified()) { 7816 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7817 << 0 /*const*/; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 if (NewVD->hasExternalStorage()) { 7822 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7823 NewVD->setInvalidDecl(); 7824 return; 7825 } 7826 } 7827 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7828 // __constant address space. 7829 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7830 // variables inside a function can also be declared in the global 7831 // address space. 7832 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7833 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7834 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7835 NewVD->hasExternalStorage()) { 7836 if (!T->isSamplerT() && 7837 !(T.getAddressSpace() == LangAS::opencl_constant || 7838 (T.getAddressSpace() == LangAS::opencl_global && 7839 (getLangOpts().OpenCLVersion == 200 || 7840 getLangOpts().OpenCLCPlusPlus)))) { 7841 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7842 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7843 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7844 << Scope << "global or constant"; 7845 else 7846 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7847 << Scope << "constant"; 7848 NewVD->setInvalidDecl(); 7849 return; 7850 } 7851 } else { 7852 if (T.getAddressSpace() == LangAS::opencl_global) { 7853 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7854 << 1 /*is any function*/ << "global"; 7855 NewVD->setInvalidDecl(); 7856 return; 7857 } 7858 if (T.getAddressSpace() == LangAS::opencl_constant || 7859 T.getAddressSpace() == LangAS::opencl_local) { 7860 FunctionDecl *FD = getCurFunctionDecl(); 7861 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7862 // in functions. 7863 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7864 if (T.getAddressSpace() == LangAS::opencl_constant) 7865 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7866 << 0 /*non-kernel only*/ << "constant"; 7867 else 7868 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7869 << 0 /*non-kernel only*/ << "local"; 7870 NewVD->setInvalidDecl(); 7871 return; 7872 } 7873 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7874 // in the outermost scope of a kernel function. 7875 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7876 if (!getCurScope()->isFunctionScope()) { 7877 if (T.getAddressSpace() == LangAS::opencl_constant) 7878 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7879 << "constant"; 7880 else 7881 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7882 << "local"; 7883 NewVD->setInvalidDecl(); 7884 return; 7885 } 7886 } 7887 } else if (T.getAddressSpace() != LangAS::opencl_private && 7888 // If we are parsing a template we didn't deduce an addr 7889 // space yet. 7890 T.getAddressSpace() != LangAS::Default) { 7891 // Do not allow other address spaces on automatic variable. 7892 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7893 NewVD->setInvalidDecl(); 7894 return; 7895 } 7896 } 7897 } 7898 7899 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7900 && !NewVD->hasAttr<BlocksAttr>()) { 7901 if (getLangOpts().getGC() != LangOptions::NonGC) 7902 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7903 else { 7904 assert(!getLangOpts().ObjCAutoRefCount); 7905 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7906 } 7907 } 7908 7909 bool isVM = T->isVariablyModifiedType(); 7910 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7911 NewVD->hasAttr<BlocksAttr>()) 7912 setFunctionHasBranchProtectedScope(); 7913 7914 if ((isVM && NewVD->hasLinkage()) || 7915 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7916 bool SizeIsNegative; 7917 llvm::APSInt Oversized; 7918 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7919 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7920 QualType FixedT; 7921 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7922 FixedT = FixedTInfo->getType(); 7923 else if (FixedTInfo) { 7924 // Type and type-as-written are canonically different. We need to fix up 7925 // both types separately. 7926 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7927 Oversized); 7928 } 7929 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7930 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7931 // FIXME: This won't give the correct result for 7932 // int a[10][n]; 7933 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7934 7935 if (NewVD->isFileVarDecl()) 7936 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7937 << SizeRange; 7938 else if (NewVD->isStaticLocal()) 7939 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7940 << SizeRange; 7941 else 7942 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7943 << SizeRange; 7944 NewVD->setInvalidDecl(); 7945 return; 7946 } 7947 7948 if (!FixedTInfo) { 7949 if (NewVD->isFileVarDecl()) 7950 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7951 else 7952 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7953 NewVD->setInvalidDecl(); 7954 return; 7955 } 7956 7957 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7958 NewVD->setType(FixedT); 7959 NewVD->setTypeSourceInfo(FixedTInfo); 7960 } 7961 7962 if (T->isVoidType()) { 7963 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7964 // of objects and functions. 7965 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7966 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7967 << T; 7968 NewVD->setInvalidDecl(); 7969 return; 7970 } 7971 } 7972 7973 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7974 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7975 NewVD->setInvalidDecl(); 7976 return; 7977 } 7978 7979 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 7980 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 7985 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7986 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7987 NewVD->setInvalidDecl(); 7988 return; 7989 } 7990 7991 if (NewVD->isConstexpr() && !T->isDependentType() && 7992 RequireLiteralType(NewVD->getLocation(), T, 7993 diag::err_constexpr_var_non_literal)) { 7994 NewVD->setInvalidDecl(); 7995 return; 7996 } 7997 } 7998 7999 /// Perform semantic checking on a newly-created variable 8000 /// declaration. 8001 /// 8002 /// This routine performs all of the type-checking required for a 8003 /// variable declaration once it has been built. It is used both to 8004 /// check variables after they have been parsed and their declarators 8005 /// have been translated into a declaration, and to check variables 8006 /// that have been instantiated from a template. 8007 /// 8008 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8009 /// 8010 /// Returns true if the variable declaration is a redeclaration. 8011 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8012 CheckVariableDeclarationType(NewVD); 8013 8014 // If the decl is already known invalid, don't check it. 8015 if (NewVD->isInvalidDecl()) 8016 return false; 8017 8018 // If we did not find anything by this name, look for a non-visible 8019 // extern "C" declaration with the same name. 8020 if (Previous.empty() && 8021 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8022 Previous.setShadowed(); 8023 8024 if (!Previous.empty()) { 8025 MergeVarDecl(NewVD, Previous); 8026 return true; 8027 } 8028 return false; 8029 } 8030 8031 namespace { 8032 struct FindOverriddenMethod { 8033 Sema *S; 8034 CXXMethodDecl *Method; 8035 8036 /// Member lookup function that determines whether a given C++ 8037 /// method overrides a method in a base class, to be used with 8038 /// CXXRecordDecl::lookupInBases(). 8039 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8040 RecordDecl *BaseRecord = 8041 Specifier->getType()->castAs<RecordType>()->getDecl(); 8042 8043 DeclarationName Name = Method->getDeclName(); 8044 8045 // FIXME: Do we care about other names here too? 8046 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8047 // We really want to find the base class destructor here. 8048 QualType T = S->Context.getTypeDeclType(BaseRecord); 8049 CanQualType CT = S->Context.getCanonicalType(T); 8050 8051 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8052 } 8053 8054 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8055 Path.Decls = Path.Decls.slice(1)) { 8056 NamedDecl *D = Path.Decls.front(); 8057 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8058 if (MD->isVirtual() && 8059 !S->IsOverload( 8060 Method, MD, /*UseMemberUsingDeclRules=*/false, 8061 /*ConsiderCudaAttrs=*/true, 8062 // C++2a [class.virtual]p2 does not consider requires clauses 8063 // when overriding. 8064 /*ConsiderRequiresClauses=*/false)) 8065 return true; 8066 } 8067 } 8068 8069 return false; 8070 } 8071 }; 8072 } // end anonymous namespace 8073 8074 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8075 /// and if so, check that it's a valid override and remember it. 8076 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8077 // Look for methods in base classes that this method might override. 8078 CXXBasePaths Paths; 8079 FindOverriddenMethod FOM; 8080 FOM.Method = MD; 8081 FOM.S = this; 8082 bool AddedAny = false; 8083 if (DC->lookupInBases(FOM, Paths)) { 8084 for (auto *I : Paths.found_decls()) { 8085 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8086 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8087 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8088 !CheckOverridingFunctionAttributes(MD, OldMD) && 8089 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8090 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8091 AddedAny = true; 8092 } 8093 } 8094 } 8095 } 8096 8097 return AddedAny; 8098 } 8099 8100 namespace { 8101 // Struct for holding all of the extra arguments needed by 8102 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8103 struct ActOnFDArgs { 8104 Scope *S; 8105 Declarator &D; 8106 MultiTemplateParamsArg TemplateParamLists; 8107 bool AddToScope; 8108 }; 8109 } // end anonymous namespace 8110 8111 namespace { 8112 8113 // Callback to only accept typo corrections that have a non-zero edit distance. 8114 // Also only accept corrections that have the same parent decl. 8115 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8116 public: 8117 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8118 CXXRecordDecl *Parent) 8119 : Context(Context), OriginalFD(TypoFD), 8120 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8121 8122 bool ValidateCandidate(const TypoCorrection &candidate) override { 8123 if (candidate.getEditDistance() == 0) 8124 return false; 8125 8126 SmallVector<unsigned, 1> MismatchedParams; 8127 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8128 CDeclEnd = candidate.end(); 8129 CDecl != CDeclEnd; ++CDecl) { 8130 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8131 8132 if (FD && !FD->hasBody() && 8133 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8134 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8135 CXXRecordDecl *Parent = MD->getParent(); 8136 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8137 return true; 8138 } else if (!ExpectedParent) { 8139 return true; 8140 } 8141 } 8142 } 8143 8144 return false; 8145 } 8146 8147 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8148 return std::make_unique<DifferentNameValidatorCCC>(*this); 8149 } 8150 8151 private: 8152 ASTContext &Context; 8153 FunctionDecl *OriginalFD; 8154 CXXRecordDecl *ExpectedParent; 8155 }; 8156 8157 } // end anonymous namespace 8158 8159 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8160 TypoCorrectedFunctionDefinitions.insert(F); 8161 } 8162 8163 /// Generate diagnostics for an invalid function redeclaration. 8164 /// 8165 /// This routine handles generating the diagnostic messages for an invalid 8166 /// function redeclaration, including finding possible similar declarations 8167 /// or performing typo correction if there are no previous declarations with 8168 /// the same name. 8169 /// 8170 /// Returns a NamedDecl iff typo correction was performed and substituting in 8171 /// the new declaration name does not cause new errors. 8172 static NamedDecl *DiagnoseInvalidRedeclaration( 8173 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8174 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8175 DeclarationName Name = NewFD->getDeclName(); 8176 DeclContext *NewDC = NewFD->getDeclContext(); 8177 SmallVector<unsigned, 1> MismatchedParams; 8178 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8179 TypoCorrection Correction; 8180 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8181 unsigned DiagMsg = 8182 IsLocalFriend ? diag::err_no_matching_local_friend : 8183 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8184 diag::err_member_decl_does_not_match; 8185 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8186 IsLocalFriend ? Sema::LookupLocalFriendName 8187 : Sema::LookupOrdinaryName, 8188 Sema::ForVisibleRedeclaration); 8189 8190 NewFD->setInvalidDecl(); 8191 if (IsLocalFriend) 8192 SemaRef.LookupName(Prev, S); 8193 else 8194 SemaRef.LookupQualifiedName(Prev, NewDC); 8195 assert(!Prev.isAmbiguous() && 8196 "Cannot have an ambiguity in previous-declaration lookup"); 8197 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8198 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8199 MD ? MD->getParent() : nullptr); 8200 if (!Prev.empty()) { 8201 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8202 Func != FuncEnd; ++Func) { 8203 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8204 if (FD && 8205 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8206 // Add 1 to the index so that 0 can mean the mismatch didn't 8207 // involve a parameter 8208 unsigned ParamNum = 8209 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8210 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8211 } 8212 } 8213 // If the qualified name lookup yielded nothing, try typo correction 8214 } else if ((Correction = SemaRef.CorrectTypo( 8215 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8216 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8217 IsLocalFriend ? nullptr : NewDC))) { 8218 // Set up everything for the call to ActOnFunctionDeclarator 8219 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8220 ExtraArgs.D.getIdentifierLoc()); 8221 Previous.clear(); 8222 Previous.setLookupName(Correction.getCorrection()); 8223 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8224 CDeclEnd = Correction.end(); 8225 CDecl != CDeclEnd; ++CDecl) { 8226 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8227 if (FD && !FD->hasBody() && 8228 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8229 Previous.addDecl(FD); 8230 } 8231 } 8232 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8233 8234 NamedDecl *Result; 8235 // Retry building the function declaration with the new previous 8236 // declarations, and with errors suppressed. 8237 { 8238 // Trap errors. 8239 Sema::SFINAETrap Trap(SemaRef); 8240 8241 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8242 // pieces need to verify the typo-corrected C++ declaration and hopefully 8243 // eliminate the need for the parameter pack ExtraArgs. 8244 Result = SemaRef.ActOnFunctionDeclarator( 8245 ExtraArgs.S, ExtraArgs.D, 8246 Correction.getCorrectionDecl()->getDeclContext(), 8247 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8248 ExtraArgs.AddToScope); 8249 8250 if (Trap.hasErrorOccurred()) 8251 Result = nullptr; 8252 } 8253 8254 if (Result) { 8255 // Determine which correction we picked. 8256 Decl *Canonical = Result->getCanonicalDecl(); 8257 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8258 I != E; ++I) 8259 if ((*I)->getCanonicalDecl() == Canonical) 8260 Correction.setCorrectionDecl(*I); 8261 8262 // Let Sema know about the correction. 8263 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8264 SemaRef.diagnoseTypo( 8265 Correction, 8266 SemaRef.PDiag(IsLocalFriend 8267 ? diag::err_no_matching_local_friend_suggest 8268 : diag::err_member_decl_does_not_match_suggest) 8269 << Name << NewDC << IsDefinition); 8270 return Result; 8271 } 8272 8273 // Pretend the typo correction never occurred 8274 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8275 ExtraArgs.D.getIdentifierLoc()); 8276 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8277 Previous.clear(); 8278 Previous.setLookupName(Name); 8279 } 8280 8281 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8282 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8283 8284 bool NewFDisConst = false; 8285 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8286 NewFDisConst = NewMD->isConst(); 8287 8288 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8289 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8290 NearMatch != NearMatchEnd; ++NearMatch) { 8291 FunctionDecl *FD = NearMatch->first; 8292 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8293 bool FDisConst = MD && MD->isConst(); 8294 bool IsMember = MD || !IsLocalFriend; 8295 8296 // FIXME: These notes are poorly worded for the local friend case. 8297 if (unsigned Idx = NearMatch->second) { 8298 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8299 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8300 if (Loc.isInvalid()) Loc = FD->getLocation(); 8301 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8302 : diag::note_local_decl_close_param_match) 8303 << Idx << FDParam->getType() 8304 << NewFD->getParamDecl(Idx - 1)->getType(); 8305 } else if (FDisConst != NewFDisConst) { 8306 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8307 << NewFDisConst << FD->getSourceRange().getEnd(); 8308 } else 8309 SemaRef.Diag(FD->getLocation(), 8310 IsMember ? diag::note_member_def_close_match 8311 : diag::note_local_decl_close_match); 8312 } 8313 return nullptr; 8314 } 8315 8316 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8317 switch (D.getDeclSpec().getStorageClassSpec()) { 8318 default: llvm_unreachable("Unknown storage class!"); 8319 case DeclSpec::SCS_auto: 8320 case DeclSpec::SCS_register: 8321 case DeclSpec::SCS_mutable: 8322 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8323 diag::err_typecheck_sclass_func); 8324 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8325 D.setInvalidType(); 8326 break; 8327 case DeclSpec::SCS_unspecified: break; 8328 case DeclSpec::SCS_extern: 8329 if (D.getDeclSpec().isExternInLinkageSpec()) 8330 return SC_None; 8331 return SC_Extern; 8332 case DeclSpec::SCS_static: { 8333 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8334 // C99 6.7.1p5: 8335 // The declaration of an identifier for a function that has 8336 // block scope shall have no explicit storage-class specifier 8337 // other than extern 8338 // See also (C++ [dcl.stc]p4). 8339 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8340 diag::err_static_block_func); 8341 break; 8342 } else 8343 return SC_Static; 8344 } 8345 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8346 } 8347 8348 // No explicit storage class has already been returned 8349 return SC_None; 8350 } 8351 8352 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8353 DeclContext *DC, QualType &R, 8354 TypeSourceInfo *TInfo, 8355 StorageClass SC, 8356 bool &IsVirtualOkay) { 8357 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8358 DeclarationName Name = NameInfo.getName(); 8359 8360 FunctionDecl *NewFD = nullptr; 8361 bool isInline = D.getDeclSpec().isInlineSpecified(); 8362 8363 if (!SemaRef.getLangOpts().CPlusPlus) { 8364 // Determine whether the function was written with a 8365 // prototype. This true when: 8366 // - there is a prototype in the declarator, or 8367 // - the type R of the function is some kind of typedef or other non- 8368 // attributed reference to a type name (which eventually refers to a 8369 // function type). 8370 bool HasPrototype = 8371 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8372 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8373 8374 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8375 R, TInfo, SC, isInline, HasPrototype, 8376 CSK_unspecified, 8377 /*TrailingRequiresClause=*/nullptr); 8378 if (D.isInvalidType()) 8379 NewFD->setInvalidDecl(); 8380 8381 return NewFD; 8382 } 8383 8384 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8385 8386 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8387 if (ConstexprKind == CSK_constinit) { 8388 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8389 diag::err_constexpr_wrong_decl_kind) 8390 << ConstexprKind; 8391 ConstexprKind = CSK_unspecified; 8392 D.getMutableDeclSpec().ClearConstexprSpec(); 8393 } 8394 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8395 8396 // Check that the return type is not an abstract class type. 8397 // For record types, this is done by the AbstractClassUsageDiagnoser once 8398 // the class has been completely parsed. 8399 if (!DC->isRecord() && 8400 SemaRef.RequireNonAbstractType( 8401 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8402 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8403 D.setInvalidType(); 8404 8405 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8406 // This is a C++ constructor declaration. 8407 assert(DC->isRecord() && 8408 "Constructors can only be declared in a member context"); 8409 8410 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8411 return CXXConstructorDecl::Create( 8412 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8413 TInfo, ExplicitSpecifier, isInline, 8414 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8415 TrailingRequiresClause); 8416 8417 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8418 // This is a C++ destructor declaration. 8419 if (DC->isRecord()) { 8420 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8421 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8422 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8423 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8424 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8425 TrailingRequiresClause); 8426 8427 // If the destructor needs an implicit exception specification, set it 8428 // now. FIXME: It'd be nice to be able to create the right type to start 8429 // with, but the type needs to reference the destructor declaration. 8430 if (SemaRef.getLangOpts().CPlusPlus11) 8431 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8432 8433 IsVirtualOkay = true; 8434 return NewDD; 8435 8436 } else { 8437 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8438 D.setInvalidType(); 8439 8440 // Create a FunctionDecl to satisfy the function definition parsing 8441 // code path. 8442 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8443 D.getIdentifierLoc(), Name, R, TInfo, SC, 8444 isInline, 8445 /*hasPrototype=*/true, ConstexprKind, 8446 TrailingRequiresClause); 8447 } 8448 8449 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8450 if (!DC->isRecord()) { 8451 SemaRef.Diag(D.getIdentifierLoc(), 8452 diag::err_conv_function_not_member); 8453 return nullptr; 8454 } 8455 8456 SemaRef.CheckConversionDeclarator(D, R, SC); 8457 if (D.isInvalidType()) 8458 return nullptr; 8459 8460 IsVirtualOkay = true; 8461 return CXXConversionDecl::Create( 8462 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8463 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8464 TrailingRequiresClause); 8465 8466 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8467 if (TrailingRequiresClause) 8468 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8469 diag::err_trailing_requires_clause_on_deduction_guide) 8470 << TrailingRequiresClause->getSourceRange(); 8471 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8472 8473 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8474 ExplicitSpecifier, NameInfo, R, TInfo, 8475 D.getEndLoc()); 8476 } else if (DC->isRecord()) { 8477 // If the name of the function is the same as the name of the record, 8478 // then this must be an invalid constructor that has a return type. 8479 // (The parser checks for a return type and makes the declarator a 8480 // constructor if it has no return type). 8481 if (Name.getAsIdentifierInfo() && 8482 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8483 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8484 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8485 << SourceRange(D.getIdentifierLoc()); 8486 return nullptr; 8487 } 8488 8489 // This is a C++ method declaration. 8490 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8491 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8492 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8493 TrailingRequiresClause); 8494 IsVirtualOkay = !Ret->isStatic(); 8495 return Ret; 8496 } else { 8497 bool isFriend = 8498 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8499 if (!isFriend && SemaRef.CurContext->isRecord()) 8500 return nullptr; 8501 8502 // Determine whether the function was written with a 8503 // prototype. This true when: 8504 // - we're in C++ (where every function has a prototype), 8505 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8506 R, TInfo, SC, isInline, true /*HasPrototype*/, 8507 ConstexprKind, TrailingRequiresClause); 8508 } 8509 } 8510 8511 enum OpenCLParamType { 8512 ValidKernelParam, 8513 PtrPtrKernelParam, 8514 PtrKernelParam, 8515 InvalidAddrSpacePtrKernelParam, 8516 InvalidKernelParam, 8517 RecordKernelParam 8518 }; 8519 8520 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8521 // Size dependent types are just typedefs to normal integer types 8522 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8523 // integers other than by their names. 8524 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8525 8526 // Remove typedefs one by one until we reach a typedef 8527 // for a size dependent type. 8528 QualType DesugaredTy = Ty; 8529 do { 8530 ArrayRef<StringRef> Names(SizeTypeNames); 8531 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8532 if (Names.end() != Match) 8533 return true; 8534 8535 Ty = DesugaredTy; 8536 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8537 } while (DesugaredTy != Ty); 8538 8539 return false; 8540 } 8541 8542 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8543 if (PT->isPointerType()) { 8544 QualType PointeeType = PT->getPointeeType(); 8545 if (PointeeType->isPointerType()) 8546 return PtrPtrKernelParam; 8547 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8548 PointeeType.getAddressSpace() == LangAS::opencl_private || 8549 PointeeType.getAddressSpace() == LangAS::Default) 8550 return InvalidAddrSpacePtrKernelParam; 8551 return PtrKernelParam; 8552 } 8553 8554 // OpenCL v1.2 s6.9.k: 8555 // Arguments to kernel functions in a program cannot be declared with the 8556 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8557 // uintptr_t or a struct and/or union that contain fields declared to be one 8558 // of these built-in scalar types. 8559 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8560 return InvalidKernelParam; 8561 8562 if (PT->isImageType()) 8563 return PtrKernelParam; 8564 8565 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8566 return InvalidKernelParam; 8567 8568 // OpenCL extension spec v1.2 s9.5: 8569 // This extension adds support for half scalar and vector types as built-in 8570 // types that can be used for arithmetic operations, conversions etc. 8571 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8572 return InvalidKernelParam; 8573 8574 if (PT->isRecordType()) 8575 return RecordKernelParam; 8576 8577 // Look into an array argument to check if it has a forbidden type. 8578 if (PT->isArrayType()) { 8579 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8580 // Call ourself to check an underlying type of an array. Since the 8581 // getPointeeOrArrayElementType returns an innermost type which is not an 8582 // array, this recursive call only happens once. 8583 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8584 } 8585 8586 return ValidKernelParam; 8587 } 8588 8589 static void checkIsValidOpenCLKernelParameter( 8590 Sema &S, 8591 Declarator &D, 8592 ParmVarDecl *Param, 8593 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8594 QualType PT = Param->getType(); 8595 8596 // Cache the valid types we encounter to avoid rechecking structs that are 8597 // used again 8598 if (ValidTypes.count(PT.getTypePtr())) 8599 return; 8600 8601 switch (getOpenCLKernelParameterType(S, PT)) { 8602 case PtrPtrKernelParam: 8603 // OpenCL v1.2 s6.9.a: 8604 // A kernel function argument cannot be declared as a 8605 // pointer to a pointer type. 8606 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8607 D.setInvalidType(); 8608 return; 8609 8610 case InvalidAddrSpacePtrKernelParam: 8611 // OpenCL v1.0 s6.5: 8612 // __kernel function arguments declared to be a pointer of a type can point 8613 // to one of the following address spaces only : __global, __local or 8614 // __constant. 8615 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8616 D.setInvalidType(); 8617 return; 8618 8619 // OpenCL v1.2 s6.9.k: 8620 // Arguments to kernel functions in a program cannot be declared with the 8621 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8622 // uintptr_t or a struct and/or union that contain fields declared to be 8623 // one of these built-in scalar types. 8624 8625 case InvalidKernelParam: 8626 // OpenCL v1.2 s6.8 n: 8627 // A kernel function argument cannot be declared 8628 // of event_t type. 8629 // Do not diagnose half type since it is diagnosed as invalid argument 8630 // type for any function elsewhere. 8631 if (!PT->isHalfType()) { 8632 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8633 8634 // Explain what typedefs are involved. 8635 const TypedefType *Typedef = nullptr; 8636 while ((Typedef = PT->getAs<TypedefType>())) { 8637 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8638 // SourceLocation may be invalid for a built-in type. 8639 if (Loc.isValid()) 8640 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8641 PT = Typedef->desugar(); 8642 } 8643 } 8644 8645 D.setInvalidType(); 8646 return; 8647 8648 case PtrKernelParam: 8649 case ValidKernelParam: 8650 ValidTypes.insert(PT.getTypePtr()); 8651 return; 8652 8653 case RecordKernelParam: 8654 break; 8655 } 8656 8657 // Track nested structs we will inspect 8658 SmallVector<const Decl *, 4> VisitStack; 8659 8660 // Track where we are in the nested structs. Items will migrate from 8661 // VisitStack to HistoryStack as we do the DFS for bad field. 8662 SmallVector<const FieldDecl *, 4> HistoryStack; 8663 HistoryStack.push_back(nullptr); 8664 8665 // At this point we already handled everything except of a RecordType or 8666 // an ArrayType of a RecordType. 8667 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8668 const RecordType *RecTy = 8669 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8670 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8671 8672 VisitStack.push_back(RecTy->getDecl()); 8673 assert(VisitStack.back() && "First decl null?"); 8674 8675 do { 8676 const Decl *Next = VisitStack.pop_back_val(); 8677 if (!Next) { 8678 assert(!HistoryStack.empty()); 8679 // Found a marker, we have gone up a level 8680 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8681 ValidTypes.insert(Hist->getType().getTypePtr()); 8682 8683 continue; 8684 } 8685 8686 // Adds everything except the original parameter declaration (which is not a 8687 // field itself) to the history stack. 8688 const RecordDecl *RD; 8689 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8690 HistoryStack.push_back(Field); 8691 8692 QualType FieldTy = Field->getType(); 8693 // Other field types (known to be valid or invalid) are handled while we 8694 // walk around RecordDecl::fields(). 8695 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8696 "Unexpected type."); 8697 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8698 8699 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8700 } else { 8701 RD = cast<RecordDecl>(Next); 8702 } 8703 8704 // Add a null marker so we know when we've gone back up a level 8705 VisitStack.push_back(nullptr); 8706 8707 for (const auto *FD : RD->fields()) { 8708 QualType QT = FD->getType(); 8709 8710 if (ValidTypes.count(QT.getTypePtr())) 8711 continue; 8712 8713 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8714 if (ParamType == ValidKernelParam) 8715 continue; 8716 8717 if (ParamType == RecordKernelParam) { 8718 VisitStack.push_back(FD); 8719 continue; 8720 } 8721 8722 // OpenCL v1.2 s6.9.p: 8723 // Arguments to kernel functions that are declared to be a struct or union 8724 // do not allow OpenCL objects to be passed as elements of the struct or 8725 // union. 8726 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8727 ParamType == InvalidAddrSpacePtrKernelParam) { 8728 S.Diag(Param->getLocation(), 8729 diag::err_record_with_pointers_kernel_param) 8730 << PT->isUnionType() 8731 << PT; 8732 } else { 8733 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8734 } 8735 8736 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8737 << OrigRecDecl->getDeclName(); 8738 8739 // We have an error, now let's go back up through history and show where 8740 // the offending field came from 8741 for (ArrayRef<const FieldDecl *>::const_iterator 8742 I = HistoryStack.begin() + 1, 8743 E = HistoryStack.end(); 8744 I != E; ++I) { 8745 const FieldDecl *OuterField = *I; 8746 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8747 << OuterField->getType(); 8748 } 8749 8750 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8751 << QT->isPointerType() 8752 << QT; 8753 D.setInvalidType(); 8754 return; 8755 } 8756 } while (!VisitStack.empty()); 8757 } 8758 8759 /// Find the DeclContext in which a tag is implicitly declared if we see an 8760 /// elaborated type specifier in the specified context, and lookup finds 8761 /// nothing. 8762 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8763 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8764 DC = DC->getParent(); 8765 return DC; 8766 } 8767 8768 /// Find the Scope in which a tag is implicitly declared if we see an 8769 /// elaborated type specifier in the specified context, and lookup finds 8770 /// nothing. 8771 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8772 while (S->isClassScope() || 8773 (LangOpts.CPlusPlus && 8774 S->isFunctionPrototypeScope()) || 8775 ((S->getFlags() & Scope::DeclScope) == 0) || 8776 (S->getEntity() && S->getEntity()->isTransparentContext())) 8777 S = S->getParent(); 8778 return S; 8779 } 8780 8781 NamedDecl* 8782 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8783 TypeSourceInfo *TInfo, LookupResult &Previous, 8784 MultiTemplateParamsArg TemplateParamListsRef, 8785 bool &AddToScope) { 8786 QualType R = TInfo->getType(); 8787 8788 assert(R->isFunctionType()); 8789 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8790 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8791 8792 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8793 for (TemplateParameterList *TPL : TemplateParamListsRef) 8794 TemplateParamLists.push_back(TPL); 8795 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8796 if (!TemplateParamLists.empty() && 8797 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8798 TemplateParamLists.back() = Invented; 8799 else 8800 TemplateParamLists.push_back(Invented); 8801 } 8802 8803 // TODO: consider using NameInfo for diagnostic. 8804 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8805 DeclarationName Name = NameInfo.getName(); 8806 StorageClass SC = getFunctionStorageClass(*this, D); 8807 8808 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8809 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8810 diag::err_invalid_thread) 8811 << DeclSpec::getSpecifierName(TSCS); 8812 8813 if (D.isFirstDeclarationOfMember()) 8814 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8815 D.getIdentifierLoc()); 8816 8817 bool isFriend = false; 8818 FunctionTemplateDecl *FunctionTemplate = nullptr; 8819 bool isMemberSpecialization = false; 8820 bool isFunctionTemplateSpecialization = false; 8821 8822 bool isDependentClassScopeExplicitSpecialization = false; 8823 bool HasExplicitTemplateArgs = false; 8824 TemplateArgumentListInfo TemplateArgs; 8825 8826 bool isVirtualOkay = false; 8827 8828 DeclContext *OriginalDC = DC; 8829 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8830 8831 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8832 isVirtualOkay); 8833 if (!NewFD) return nullptr; 8834 8835 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8836 NewFD->setTopLevelDeclInObjCContainer(); 8837 8838 // Set the lexical context. If this is a function-scope declaration, or has a 8839 // C++ scope specifier, or is the object of a friend declaration, the lexical 8840 // context will be different from the semantic context. 8841 NewFD->setLexicalDeclContext(CurContext); 8842 8843 if (IsLocalExternDecl) 8844 NewFD->setLocalExternDecl(); 8845 8846 if (getLangOpts().CPlusPlus) { 8847 bool isInline = D.getDeclSpec().isInlineSpecified(); 8848 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8849 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8850 isFriend = D.getDeclSpec().isFriendSpecified(); 8851 if (isFriend && !isInline && D.isFunctionDefinition()) { 8852 // C++ [class.friend]p5 8853 // A function can be defined in a friend declaration of a 8854 // class . . . . Such a function is implicitly inline. 8855 NewFD->setImplicitlyInline(); 8856 } 8857 8858 // If this is a method defined in an __interface, and is not a constructor 8859 // or an overloaded operator, then set the pure flag (isVirtual will already 8860 // return true). 8861 if (const CXXRecordDecl *Parent = 8862 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8863 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8864 NewFD->setPure(true); 8865 8866 // C++ [class.union]p2 8867 // A union can have member functions, but not virtual functions. 8868 if (isVirtual && Parent->isUnion()) 8869 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8870 } 8871 8872 SetNestedNameSpecifier(*this, NewFD, D); 8873 isMemberSpecialization = false; 8874 isFunctionTemplateSpecialization = false; 8875 if (D.isInvalidType()) 8876 NewFD->setInvalidDecl(); 8877 8878 // Match up the template parameter lists with the scope specifier, then 8879 // determine whether we have a template or a template specialization. 8880 bool Invalid = false; 8881 TemplateParameterList *TemplateParams = 8882 MatchTemplateParametersToScopeSpecifier( 8883 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8884 D.getCXXScopeSpec(), 8885 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8886 ? D.getName().TemplateId 8887 : nullptr, 8888 TemplateParamLists, isFriend, isMemberSpecialization, 8889 Invalid); 8890 if (TemplateParams) { 8891 if (TemplateParams->size() > 0) { 8892 // This is a function template 8893 8894 // Check that we can declare a template here. 8895 if (CheckTemplateDeclScope(S, TemplateParams)) 8896 NewFD->setInvalidDecl(); 8897 8898 // A destructor cannot be a template. 8899 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8900 Diag(NewFD->getLocation(), diag::err_destructor_template); 8901 NewFD->setInvalidDecl(); 8902 } 8903 8904 // If we're adding a template to a dependent context, we may need to 8905 // rebuilding some of the types used within the template parameter list, 8906 // now that we know what the current instantiation is. 8907 if (DC->isDependentContext()) { 8908 ContextRAII SavedContext(*this, DC); 8909 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8910 Invalid = true; 8911 } 8912 8913 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8914 NewFD->getLocation(), 8915 Name, TemplateParams, 8916 NewFD); 8917 FunctionTemplate->setLexicalDeclContext(CurContext); 8918 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8919 8920 // For source fidelity, store the other template param lists. 8921 if (TemplateParamLists.size() > 1) { 8922 NewFD->setTemplateParameterListsInfo(Context, 8923 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8924 .drop_back(1)); 8925 } 8926 } else { 8927 // This is a function template specialization. 8928 isFunctionTemplateSpecialization = true; 8929 // For source fidelity, store all the template param lists. 8930 if (TemplateParamLists.size() > 0) 8931 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8932 8933 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8934 if (isFriend) { 8935 // We want to remove the "template<>", found here. 8936 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8937 8938 // If we remove the template<> and the name is not a 8939 // template-id, we're actually silently creating a problem: 8940 // the friend declaration will refer to an untemplated decl, 8941 // and clearly the user wants a template specialization. So 8942 // we need to insert '<>' after the name. 8943 SourceLocation InsertLoc; 8944 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8945 InsertLoc = D.getName().getSourceRange().getEnd(); 8946 InsertLoc = getLocForEndOfToken(InsertLoc); 8947 } 8948 8949 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8950 << Name << RemoveRange 8951 << FixItHint::CreateRemoval(RemoveRange) 8952 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8953 } 8954 } 8955 } else { 8956 // All template param lists were matched against the scope specifier: 8957 // this is NOT (an explicit specialization of) a template. 8958 if (TemplateParamLists.size() > 0) 8959 // For source fidelity, store all the template param lists. 8960 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8961 } 8962 8963 if (Invalid) { 8964 NewFD->setInvalidDecl(); 8965 if (FunctionTemplate) 8966 FunctionTemplate->setInvalidDecl(); 8967 } 8968 8969 // C++ [dcl.fct.spec]p5: 8970 // The virtual specifier shall only be used in declarations of 8971 // nonstatic class member functions that appear within a 8972 // member-specification of a class declaration; see 10.3. 8973 // 8974 if (isVirtual && !NewFD->isInvalidDecl()) { 8975 if (!isVirtualOkay) { 8976 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8977 diag::err_virtual_non_function); 8978 } else if (!CurContext->isRecord()) { 8979 // 'virtual' was specified outside of the class. 8980 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8981 diag::err_virtual_out_of_class) 8982 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8983 } else if (NewFD->getDescribedFunctionTemplate()) { 8984 // C++ [temp.mem]p3: 8985 // A member function template shall not be virtual. 8986 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8987 diag::err_virtual_member_function_template) 8988 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8989 } else { 8990 // Okay: Add virtual to the method. 8991 NewFD->setVirtualAsWritten(true); 8992 } 8993 8994 if (getLangOpts().CPlusPlus14 && 8995 NewFD->getReturnType()->isUndeducedType()) 8996 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8997 } 8998 8999 if (getLangOpts().CPlusPlus14 && 9000 (NewFD->isDependentContext() || 9001 (isFriend && CurContext->isDependentContext())) && 9002 NewFD->getReturnType()->isUndeducedType()) { 9003 // If the function template is referenced directly (for instance, as a 9004 // member of the current instantiation), pretend it has a dependent type. 9005 // This is not really justified by the standard, but is the only sane 9006 // thing to do. 9007 // FIXME: For a friend function, we have not marked the function as being 9008 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9009 const FunctionProtoType *FPT = 9010 NewFD->getType()->castAs<FunctionProtoType>(); 9011 QualType Result = 9012 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9013 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9014 FPT->getExtProtoInfo())); 9015 } 9016 9017 // C++ [dcl.fct.spec]p3: 9018 // The inline specifier shall not appear on a block scope function 9019 // declaration. 9020 if (isInline && !NewFD->isInvalidDecl()) { 9021 if (CurContext->isFunctionOrMethod()) { 9022 // 'inline' is not allowed on block scope function declaration. 9023 Diag(D.getDeclSpec().getInlineSpecLoc(), 9024 diag::err_inline_declaration_block_scope) << Name 9025 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9026 } 9027 } 9028 9029 // C++ [dcl.fct.spec]p6: 9030 // The explicit specifier shall be used only in the declaration of a 9031 // constructor or conversion function within its class definition; 9032 // see 12.3.1 and 12.3.2. 9033 if (hasExplicit && !NewFD->isInvalidDecl() && 9034 !isa<CXXDeductionGuideDecl>(NewFD)) { 9035 if (!CurContext->isRecord()) { 9036 // 'explicit' was specified outside of the class. 9037 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9038 diag::err_explicit_out_of_class) 9039 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9040 } else if (!isa<CXXConstructorDecl>(NewFD) && 9041 !isa<CXXConversionDecl>(NewFD)) { 9042 // 'explicit' was specified on a function that wasn't a constructor 9043 // or conversion function. 9044 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9045 diag::err_explicit_non_ctor_or_conv_function) 9046 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9047 } 9048 } 9049 9050 if (ConstexprSpecKind ConstexprKind = 9051 D.getDeclSpec().getConstexprSpecifier()) { 9052 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9053 // are implicitly inline. 9054 NewFD->setImplicitlyInline(); 9055 9056 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9057 // be either constructors or to return a literal type. Therefore, 9058 // destructors cannot be declared constexpr. 9059 if (isa<CXXDestructorDecl>(NewFD) && 9060 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9061 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9062 << ConstexprKind; 9063 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9064 } 9065 // C++20 [dcl.constexpr]p2: An allocation function, or a 9066 // deallocation function shall not be declared with the consteval 9067 // specifier. 9068 if (ConstexprKind == CSK_consteval && 9069 (NewFD->getOverloadedOperator() == OO_New || 9070 NewFD->getOverloadedOperator() == OO_Array_New || 9071 NewFD->getOverloadedOperator() == OO_Delete || 9072 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9073 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9074 diag::err_invalid_consteval_decl_kind) 9075 << NewFD; 9076 NewFD->setConstexprKind(CSK_constexpr); 9077 } 9078 } 9079 9080 // If __module_private__ was specified, mark the function accordingly. 9081 if (D.getDeclSpec().isModulePrivateSpecified()) { 9082 if (isFunctionTemplateSpecialization) { 9083 SourceLocation ModulePrivateLoc 9084 = D.getDeclSpec().getModulePrivateSpecLoc(); 9085 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9086 << 0 9087 << FixItHint::CreateRemoval(ModulePrivateLoc); 9088 } else { 9089 NewFD->setModulePrivate(); 9090 if (FunctionTemplate) 9091 FunctionTemplate->setModulePrivate(); 9092 } 9093 } 9094 9095 if (isFriend) { 9096 if (FunctionTemplate) { 9097 FunctionTemplate->setObjectOfFriendDecl(); 9098 FunctionTemplate->setAccess(AS_public); 9099 } 9100 NewFD->setObjectOfFriendDecl(); 9101 NewFD->setAccess(AS_public); 9102 } 9103 9104 // If a function is defined as defaulted or deleted, mark it as such now. 9105 // We'll do the relevant checks on defaulted / deleted functions later. 9106 switch (D.getFunctionDefinitionKind()) { 9107 case FDK_Declaration: 9108 case FDK_Definition: 9109 break; 9110 9111 case FDK_Defaulted: 9112 NewFD->setDefaulted(); 9113 break; 9114 9115 case FDK_Deleted: 9116 NewFD->setDeletedAsWritten(); 9117 break; 9118 } 9119 9120 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9121 D.isFunctionDefinition()) { 9122 // C++ [class.mfct]p2: 9123 // A member function may be defined (8.4) in its class definition, in 9124 // which case it is an inline member function (7.1.2) 9125 NewFD->setImplicitlyInline(); 9126 } 9127 9128 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9129 !CurContext->isRecord()) { 9130 // C++ [class.static]p1: 9131 // A data or function member of a class may be declared static 9132 // in a class definition, in which case it is a static member of 9133 // the class. 9134 9135 // Complain about the 'static' specifier if it's on an out-of-line 9136 // member function definition. 9137 9138 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9139 // member function template declaration and class member template 9140 // declaration (MSVC versions before 2015), warn about this. 9141 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9142 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9143 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9144 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9145 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9146 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9147 } 9148 9149 // C++11 [except.spec]p15: 9150 // A deallocation function with no exception-specification is treated 9151 // as if it were specified with noexcept(true). 9152 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9153 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9154 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9155 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9156 NewFD->setType(Context.getFunctionType( 9157 FPT->getReturnType(), FPT->getParamTypes(), 9158 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9159 } 9160 9161 // Filter out previous declarations that don't match the scope. 9162 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9163 D.getCXXScopeSpec().isNotEmpty() || 9164 isMemberSpecialization || 9165 isFunctionTemplateSpecialization); 9166 9167 // Handle GNU asm-label extension (encoded as an attribute). 9168 if (Expr *E = (Expr*) D.getAsmLabel()) { 9169 // The parser guarantees this is a string. 9170 StringLiteral *SE = cast<StringLiteral>(E); 9171 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9172 /*IsLiteralLabel=*/true, 9173 SE->getStrTokenLoc(0))); 9174 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9175 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9176 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9177 if (I != ExtnameUndeclaredIdentifiers.end()) { 9178 if (isDeclExternC(NewFD)) { 9179 NewFD->addAttr(I->second); 9180 ExtnameUndeclaredIdentifiers.erase(I); 9181 } else 9182 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9183 << /*Variable*/0 << NewFD; 9184 } 9185 } 9186 9187 // Copy the parameter declarations from the declarator D to the function 9188 // declaration NewFD, if they are available. First scavenge them into Params. 9189 SmallVector<ParmVarDecl*, 16> Params; 9190 unsigned FTIIdx; 9191 if (D.isFunctionDeclarator(FTIIdx)) { 9192 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9193 9194 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9195 // function that takes no arguments, not a function that takes a 9196 // single void argument. 9197 // We let through "const void" here because Sema::GetTypeForDeclarator 9198 // already checks for that case. 9199 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9200 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9201 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9202 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9203 Param->setDeclContext(NewFD); 9204 Params.push_back(Param); 9205 9206 if (Param->isInvalidDecl()) 9207 NewFD->setInvalidDecl(); 9208 } 9209 } 9210 9211 if (!getLangOpts().CPlusPlus) { 9212 // In C, find all the tag declarations from the prototype and move them 9213 // into the function DeclContext. Remove them from the surrounding tag 9214 // injection context of the function, which is typically but not always 9215 // the TU. 9216 DeclContext *PrototypeTagContext = 9217 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9218 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9219 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9220 9221 // We don't want to reparent enumerators. Look at their parent enum 9222 // instead. 9223 if (!TD) { 9224 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9225 TD = cast<EnumDecl>(ECD->getDeclContext()); 9226 } 9227 if (!TD) 9228 continue; 9229 DeclContext *TagDC = TD->getLexicalDeclContext(); 9230 if (!TagDC->containsDecl(TD)) 9231 continue; 9232 TagDC->removeDecl(TD); 9233 TD->setDeclContext(NewFD); 9234 NewFD->addDecl(TD); 9235 9236 // Preserve the lexical DeclContext if it is not the surrounding tag 9237 // injection context of the FD. In this example, the semantic context of 9238 // E will be f and the lexical context will be S, while both the 9239 // semantic and lexical contexts of S will be f: 9240 // void f(struct S { enum E { a } f; } s); 9241 if (TagDC != PrototypeTagContext) 9242 TD->setLexicalDeclContext(TagDC); 9243 } 9244 } 9245 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9246 // When we're declaring a function with a typedef, typeof, etc as in the 9247 // following example, we'll need to synthesize (unnamed) 9248 // parameters for use in the declaration. 9249 // 9250 // @code 9251 // typedef void fn(int); 9252 // fn f; 9253 // @endcode 9254 9255 // Synthesize a parameter for each argument type. 9256 for (const auto &AI : FT->param_types()) { 9257 ParmVarDecl *Param = 9258 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9259 Param->setScopeInfo(0, Params.size()); 9260 Params.push_back(Param); 9261 } 9262 } else { 9263 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9264 "Should not need args for typedef of non-prototype fn"); 9265 } 9266 9267 // Finally, we know we have the right number of parameters, install them. 9268 NewFD->setParams(Params); 9269 9270 if (D.getDeclSpec().isNoreturnSpecified()) 9271 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9272 D.getDeclSpec().getNoreturnSpecLoc(), 9273 AttributeCommonInfo::AS_Keyword)); 9274 9275 // Functions returning a variably modified type violate C99 6.7.5.2p2 9276 // because all functions have linkage. 9277 if (!NewFD->isInvalidDecl() && 9278 NewFD->getReturnType()->isVariablyModifiedType()) { 9279 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9280 NewFD->setInvalidDecl(); 9281 } 9282 9283 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9284 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9285 !NewFD->hasAttr<SectionAttr>()) 9286 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9287 Context, PragmaClangTextSection.SectionName, 9288 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9289 9290 // Apply an implicit SectionAttr if #pragma code_seg is active. 9291 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9292 !NewFD->hasAttr<SectionAttr>()) { 9293 NewFD->addAttr(SectionAttr::CreateImplicit( 9294 Context, CodeSegStack.CurrentValue->getString(), 9295 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9296 SectionAttr::Declspec_allocate)); 9297 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9298 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9299 ASTContext::PSF_Read, 9300 NewFD)) 9301 NewFD->dropAttr<SectionAttr>(); 9302 } 9303 9304 // Apply an implicit CodeSegAttr from class declspec or 9305 // apply an implicit SectionAttr from #pragma code_seg if active. 9306 if (!NewFD->hasAttr<CodeSegAttr>()) { 9307 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9308 D.isFunctionDefinition())) { 9309 NewFD->addAttr(SAttr); 9310 } 9311 } 9312 9313 // Handle attributes. 9314 ProcessDeclAttributes(S, NewFD, D); 9315 9316 if (getLangOpts().OpenCL) { 9317 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9318 // type declaration will generate a compilation error. 9319 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9320 if (AddressSpace != LangAS::Default) { 9321 Diag(NewFD->getLocation(), 9322 diag::err_opencl_return_value_with_address_space); 9323 NewFD->setInvalidDecl(); 9324 } 9325 } 9326 9327 if (!getLangOpts().CPlusPlus) { 9328 // Perform semantic checking on the function declaration. 9329 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9330 CheckMain(NewFD, D.getDeclSpec()); 9331 9332 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9333 CheckMSVCRTEntryPoint(NewFD); 9334 9335 if (!NewFD->isInvalidDecl()) 9336 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9337 isMemberSpecialization)); 9338 else if (!Previous.empty()) 9339 // Recover gracefully from an invalid redeclaration. 9340 D.setRedeclaration(true); 9341 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9342 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9343 "previous declaration set still overloaded"); 9344 9345 // Diagnose no-prototype function declarations with calling conventions that 9346 // don't support variadic calls. Only do this in C and do it after merging 9347 // possibly prototyped redeclarations. 9348 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9349 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9350 CallingConv CC = FT->getExtInfo().getCC(); 9351 if (!supportsVariadicCall(CC)) { 9352 // Windows system headers sometimes accidentally use stdcall without 9353 // (void) parameters, so we relax this to a warning. 9354 int DiagID = 9355 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9356 Diag(NewFD->getLocation(), DiagID) 9357 << FunctionType::getNameForCallConv(CC); 9358 } 9359 } 9360 9361 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9362 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9363 checkNonTrivialCUnion(NewFD->getReturnType(), 9364 NewFD->getReturnTypeSourceRange().getBegin(), 9365 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9366 } else { 9367 // C++11 [replacement.functions]p3: 9368 // The program's definitions shall not be specified as inline. 9369 // 9370 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9371 // 9372 // Suppress the diagnostic if the function is __attribute__((used)), since 9373 // that forces an external definition to be emitted. 9374 if (D.getDeclSpec().isInlineSpecified() && 9375 NewFD->isReplaceableGlobalAllocationFunction() && 9376 !NewFD->hasAttr<UsedAttr>()) 9377 Diag(D.getDeclSpec().getInlineSpecLoc(), 9378 diag::ext_operator_new_delete_declared_inline) 9379 << NewFD->getDeclName(); 9380 9381 // If the declarator is a template-id, translate the parser's template 9382 // argument list into our AST format. 9383 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9384 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9385 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9386 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9387 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9388 TemplateId->NumArgs); 9389 translateTemplateArguments(TemplateArgsPtr, 9390 TemplateArgs); 9391 9392 HasExplicitTemplateArgs = true; 9393 9394 if (NewFD->isInvalidDecl()) { 9395 HasExplicitTemplateArgs = false; 9396 } else if (FunctionTemplate) { 9397 // Function template with explicit template arguments. 9398 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9399 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9400 9401 HasExplicitTemplateArgs = false; 9402 } else { 9403 assert((isFunctionTemplateSpecialization || 9404 D.getDeclSpec().isFriendSpecified()) && 9405 "should have a 'template<>' for this decl"); 9406 // "friend void foo<>(int);" is an implicit specialization decl. 9407 isFunctionTemplateSpecialization = true; 9408 } 9409 } else if (isFriend && isFunctionTemplateSpecialization) { 9410 // This combination is only possible in a recovery case; the user 9411 // wrote something like: 9412 // template <> friend void foo(int); 9413 // which we're recovering from as if the user had written: 9414 // friend void foo<>(int); 9415 // Go ahead and fake up a template id. 9416 HasExplicitTemplateArgs = true; 9417 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9418 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9419 } 9420 9421 // We do not add HD attributes to specializations here because 9422 // they may have different constexpr-ness compared to their 9423 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9424 // may end up with different effective targets. Instead, a 9425 // specialization inherits its target attributes from its template 9426 // in the CheckFunctionTemplateSpecialization() call below. 9427 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9428 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9429 9430 // If it's a friend (and only if it's a friend), it's possible 9431 // that either the specialized function type or the specialized 9432 // template is dependent, and therefore matching will fail. In 9433 // this case, don't check the specialization yet. 9434 bool InstantiationDependent = false; 9435 if (isFunctionTemplateSpecialization && isFriend && 9436 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9437 TemplateSpecializationType::anyDependentTemplateArguments( 9438 TemplateArgs, 9439 InstantiationDependent))) { 9440 assert(HasExplicitTemplateArgs && 9441 "friend function specialization without template args"); 9442 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9443 Previous)) 9444 NewFD->setInvalidDecl(); 9445 } else if (isFunctionTemplateSpecialization) { 9446 if (CurContext->isDependentContext() && CurContext->isRecord() 9447 && !isFriend) { 9448 isDependentClassScopeExplicitSpecialization = true; 9449 } else if (!NewFD->isInvalidDecl() && 9450 CheckFunctionTemplateSpecialization( 9451 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9452 Previous)) 9453 NewFD->setInvalidDecl(); 9454 9455 // C++ [dcl.stc]p1: 9456 // A storage-class-specifier shall not be specified in an explicit 9457 // specialization (14.7.3) 9458 FunctionTemplateSpecializationInfo *Info = 9459 NewFD->getTemplateSpecializationInfo(); 9460 if (Info && SC != SC_None) { 9461 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9462 Diag(NewFD->getLocation(), 9463 diag::err_explicit_specialization_inconsistent_storage_class) 9464 << SC 9465 << FixItHint::CreateRemoval( 9466 D.getDeclSpec().getStorageClassSpecLoc()); 9467 9468 else 9469 Diag(NewFD->getLocation(), 9470 diag::ext_explicit_specialization_storage_class) 9471 << FixItHint::CreateRemoval( 9472 D.getDeclSpec().getStorageClassSpecLoc()); 9473 } 9474 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9475 if (CheckMemberSpecialization(NewFD, Previous)) 9476 NewFD->setInvalidDecl(); 9477 } 9478 9479 // Perform semantic checking on the function declaration. 9480 if (!isDependentClassScopeExplicitSpecialization) { 9481 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9482 CheckMain(NewFD, D.getDeclSpec()); 9483 9484 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9485 CheckMSVCRTEntryPoint(NewFD); 9486 9487 if (!NewFD->isInvalidDecl()) 9488 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9489 isMemberSpecialization)); 9490 else if (!Previous.empty()) 9491 // Recover gracefully from an invalid redeclaration. 9492 D.setRedeclaration(true); 9493 } 9494 9495 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9496 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9497 "previous declaration set still overloaded"); 9498 9499 NamedDecl *PrincipalDecl = (FunctionTemplate 9500 ? cast<NamedDecl>(FunctionTemplate) 9501 : NewFD); 9502 9503 if (isFriend && NewFD->getPreviousDecl()) { 9504 AccessSpecifier Access = AS_public; 9505 if (!NewFD->isInvalidDecl()) 9506 Access = NewFD->getPreviousDecl()->getAccess(); 9507 9508 NewFD->setAccess(Access); 9509 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9510 } 9511 9512 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9513 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9514 PrincipalDecl->setNonMemberOperator(); 9515 9516 // If we have a function template, check the template parameter 9517 // list. This will check and merge default template arguments. 9518 if (FunctionTemplate) { 9519 FunctionTemplateDecl *PrevTemplate = 9520 FunctionTemplate->getPreviousDecl(); 9521 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9522 PrevTemplate ? PrevTemplate->getTemplateParameters() 9523 : nullptr, 9524 D.getDeclSpec().isFriendSpecified() 9525 ? (D.isFunctionDefinition() 9526 ? TPC_FriendFunctionTemplateDefinition 9527 : TPC_FriendFunctionTemplate) 9528 : (D.getCXXScopeSpec().isSet() && 9529 DC && DC->isRecord() && 9530 DC->isDependentContext()) 9531 ? TPC_ClassTemplateMember 9532 : TPC_FunctionTemplate); 9533 } 9534 9535 if (NewFD->isInvalidDecl()) { 9536 // Ignore all the rest of this. 9537 } else if (!D.isRedeclaration()) { 9538 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9539 AddToScope }; 9540 // Fake up an access specifier if it's supposed to be a class member. 9541 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9542 NewFD->setAccess(AS_public); 9543 9544 // Qualified decls generally require a previous declaration. 9545 if (D.getCXXScopeSpec().isSet()) { 9546 // ...with the major exception of templated-scope or 9547 // dependent-scope friend declarations. 9548 9549 // TODO: we currently also suppress this check in dependent 9550 // contexts because (1) the parameter depth will be off when 9551 // matching friend templates and (2) we might actually be 9552 // selecting a friend based on a dependent factor. But there 9553 // are situations where these conditions don't apply and we 9554 // can actually do this check immediately. 9555 // 9556 // Unless the scope is dependent, it's always an error if qualified 9557 // redeclaration lookup found nothing at all. Diagnose that now; 9558 // nothing will diagnose that error later. 9559 if (isFriend && 9560 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9561 (!Previous.empty() && CurContext->isDependentContext()))) { 9562 // ignore these 9563 } else { 9564 // The user tried to provide an out-of-line definition for a 9565 // function that is a member of a class or namespace, but there 9566 // was no such member function declared (C++ [class.mfct]p2, 9567 // C++ [namespace.memdef]p2). For example: 9568 // 9569 // class X { 9570 // void f() const; 9571 // }; 9572 // 9573 // void X::f() { } // ill-formed 9574 // 9575 // Complain about this problem, and attempt to suggest close 9576 // matches (e.g., those that differ only in cv-qualifiers and 9577 // whether the parameter types are references). 9578 9579 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9580 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9581 AddToScope = ExtraArgs.AddToScope; 9582 return Result; 9583 } 9584 } 9585 9586 // Unqualified local friend declarations are required to resolve 9587 // to something. 9588 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9589 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9590 *this, Previous, NewFD, ExtraArgs, true, S)) { 9591 AddToScope = ExtraArgs.AddToScope; 9592 return Result; 9593 } 9594 } 9595 } else if (!D.isFunctionDefinition() && 9596 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9597 !isFriend && !isFunctionTemplateSpecialization && 9598 !isMemberSpecialization) { 9599 // An out-of-line member function declaration must also be a 9600 // definition (C++ [class.mfct]p2). 9601 // Note that this is not the case for explicit specializations of 9602 // function templates or member functions of class templates, per 9603 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9604 // extension for compatibility with old SWIG code which likes to 9605 // generate them. 9606 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9607 << D.getCXXScopeSpec().getRange(); 9608 } 9609 } 9610 9611 ProcessPragmaWeak(S, NewFD); 9612 checkAttributesAfterMerging(*this, *NewFD); 9613 9614 AddKnownFunctionAttributes(NewFD); 9615 9616 if (NewFD->hasAttr<OverloadableAttr>() && 9617 !NewFD->getType()->getAs<FunctionProtoType>()) { 9618 Diag(NewFD->getLocation(), 9619 diag::err_attribute_overloadable_no_prototype) 9620 << NewFD; 9621 9622 // Turn this into a variadic function with no parameters. 9623 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9624 FunctionProtoType::ExtProtoInfo EPI( 9625 Context.getDefaultCallingConvention(true, false)); 9626 EPI.Variadic = true; 9627 EPI.ExtInfo = FT->getExtInfo(); 9628 9629 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9630 NewFD->setType(R); 9631 } 9632 9633 // If there's a #pragma GCC visibility in scope, and this isn't a class 9634 // member, set the visibility of this function. 9635 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9636 AddPushedVisibilityAttribute(NewFD); 9637 9638 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9639 // marking the function. 9640 AddCFAuditedAttribute(NewFD); 9641 9642 // If this is a function definition, check if we have to apply optnone due to 9643 // a pragma. 9644 if(D.isFunctionDefinition()) 9645 AddRangeBasedOptnone(NewFD); 9646 9647 // If this is the first declaration of an extern C variable, update 9648 // the map of such variables. 9649 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9650 isIncompleteDeclExternC(*this, NewFD)) 9651 RegisterLocallyScopedExternCDecl(NewFD, S); 9652 9653 // Set this FunctionDecl's range up to the right paren. 9654 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9655 9656 if (D.isRedeclaration() && !Previous.empty()) { 9657 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9658 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9659 isMemberSpecialization || 9660 isFunctionTemplateSpecialization, 9661 D.isFunctionDefinition()); 9662 } 9663 9664 if (getLangOpts().CUDA) { 9665 IdentifierInfo *II = NewFD->getIdentifier(); 9666 if (II && II->isStr(getCudaConfigureFuncName()) && 9667 !NewFD->isInvalidDecl() && 9668 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9669 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9670 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9671 << getCudaConfigureFuncName(); 9672 Context.setcudaConfigureCallDecl(NewFD); 9673 } 9674 9675 // Variadic functions, other than a *declaration* of printf, are not allowed 9676 // in device-side CUDA code, unless someone passed 9677 // -fcuda-allow-variadic-functions. 9678 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9679 (NewFD->hasAttr<CUDADeviceAttr>() || 9680 NewFD->hasAttr<CUDAGlobalAttr>()) && 9681 !(II && II->isStr("printf") && NewFD->isExternC() && 9682 !D.isFunctionDefinition())) { 9683 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9684 } 9685 } 9686 9687 MarkUnusedFileScopedDecl(NewFD); 9688 9689 9690 9691 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9692 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9693 if ((getLangOpts().OpenCLVersion >= 120) 9694 && (SC == SC_Static)) { 9695 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9696 D.setInvalidType(); 9697 } 9698 9699 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9700 if (!NewFD->getReturnType()->isVoidType()) { 9701 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9702 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9703 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9704 : FixItHint()); 9705 D.setInvalidType(); 9706 } 9707 9708 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9709 for (auto Param : NewFD->parameters()) 9710 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9711 9712 if (getLangOpts().OpenCLCPlusPlus) { 9713 if (DC->isRecord()) { 9714 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9715 D.setInvalidType(); 9716 } 9717 if (FunctionTemplate) { 9718 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9719 D.setInvalidType(); 9720 } 9721 } 9722 } 9723 9724 if (getLangOpts().CPlusPlus) { 9725 if (FunctionTemplate) { 9726 if (NewFD->isInvalidDecl()) 9727 FunctionTemplate->setInvalidDecl(); 9728 return FunctionTemplate; 9729 } 9730 9731 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9732 CompleteMemberSpecialization(NewFD, Previous); 9733 } 9734 9735 for (const ParmVarDecl *Param : NewFD->parameters()) { 9736 QualType PT = Param->getType(); 9737 9738 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9739 // types. 9740 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9741 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9742 QualType ElemTy = PipeTy->getElementType(); 9743 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9744 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9745 D.setInvalidType(); 9746 } 9747 } 9748 } 9749 } 9750 9751 // Here we have an function template explicit specialization at class scope. 9752 // The actual specialization will be postponed to template instatiation 9753 // time via the ClassScopeFunctionSpecializationDecl node. 9754 if (isDependentClassScopeExplicitSpecialization) { 9755 ClassScopeFunctionSpecializationDecl *NewSpec = 9756 ClassScopeFunctionSpecializationDecl::Create( 9757 Context, CurContext, NewFD->getLocation(), 9758 cast<CXXMethodDecl>(NewFD), 9759 HasExplicitTemplateArgs, TemplateArgs); 9760 CurContext->addDecl(NewSpec); 9761 AddToScope = false; 9762 } 9763 9764 // Diagnose availability attributes. Availability cannot be used on functions 9765 // that are run during load/unload. 9766 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9767 if (NewFD->hasAttr<ConstructorAttr>()) { 9768 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9769 << 1; 9770 NewFD->dropAttr<AvailabilityAttr>(); 9771 } 9772 if (NewFD->hasAttr<DestructorAttr>()) { 9773 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9774 << 2; 9775 NewFD->dropAttr<AvailabilityAttr>(); 9776 } 9777 } 9778 9779 // Diagnose no_builtin attribute on function declaration that are not a 9780 // definition. 9781 // FIXME: We should really be doing this in 9782 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9783 // the FunctionDecl and at this point of the code 9784 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9785 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9786 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9787 switch (D.getFunctionDefinitionKind()) { 9788 case FDK_Defaulted: 9789 case FDK_Deleted: 9790 Diag(NBA->getLocation(), 9791 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9792 << NBA->getSpelling(); 9793 break; 9794 case FDK_Declaration: 9795 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9796 << NBA->getSpelling(); 9797 break; 9798 case FDK_Definition: 9799 break; 9800 } 9801 9802 return NewFD; 9803 } 9804 9805 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9806 /// when __declspec(code_seg) "is applied to a class, all member functions of 9807 /// the class and nested classes -- this includes compiler-generated special 9808 /// member functions -- are put in the specified segment." 9809 /// The actual behavior is a little more complicated. The Microsoft compiler 9810 /// won't check outer classes if there is an active value from #pragma code_seg. 9811 /// The CodeSeg is always applied from the direct parent but only from outer 9812 /// classes when the #pragma code_seg stack is empty. See: 9813 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9814 /// available since MS has removed the page. 9815 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9816 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9817 if (!Method) 9818 return nullptr; 9819 const CXXRecordDecl *Parent = Method->getParent(); 9820 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9821 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9822 NewAttr->setImplicit(true); 9823 return NewAttr; 9824 } 9825 9826 // The Microsoft compiler won't check outer classes for the CodeSeg 9827 // when the #pragma code_seg stack is active. 9828 if (S.CodeSegStack.CurrentValue) 9829 return nullptr; 9830 9831 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9832 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9833 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9834 NewAttr->setImplicit(true); 9835 return NewAttr; 9836 } 9837 } 9838 return nullptr; 9839 } 9840 9841 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9842 /// containing class. Otherwise it will return implicit SectionAttr if the 9843 /// function is a definition and there is an active value on CodeSegStack 9844 /// (from the current #pragma code-seg value). 9845 /// 9846 /// \param FD Function being declared. 9847 /// \param IsDefinition Whether it is a definition or just a declarartion. 9848 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9849 /// nullptr if no attribute should be added. 9850 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9851 bool IsDefinition) { 9852 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9853 return A; 9854 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9855 CodeSegStack.CurrentValue) 9856 return SectionAttr::CreateImplicit( 9857 getASTContext(), CodeSegStack.CurrentValue->getString(), 9858 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9859 SectionAttr::Declspec_allocate); 9860 return nullptr; 9861 } 9862 9863 /// Determines if we can perform a correct type check for \p D as a 9864 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9865 /// best-effort check. 9866 /// 9867 /// \param NewD The new declaration. 9868 /// \param OldD The old declaration. 9869 /// \param NewT The portion of the type of the new declaration to check. 9870 /// \param OldT The portion of the type of the old declaration to check. 9871 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9872 QualType NewT, QualType OldT) { 9873 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9874 return true; 9875 9876 // For dependently-typed local extern declarations and friends, we can't 9877 // perform a correct type check in general until instantiation: 9878 // 9879 // int f(); 9880 // template<typename T> void g() { T f(); } 9881 // 9882 // (valid if g() is only instantiated with T = int). 9883 if (NewT->isDependentType() && 9884 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9885 return false; 9886 9887 // Similarly, if the previous declaration was a dependent local extern 9888 // declaration, we don't really know its type yet. 9889 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9890 return false; 9891 9892 return true; 9893 } 9894 9895 /// Checks if the new declaration declared in dependent context must be 9896 /// put in the same redeclaration chain as the specified declaration. 9897 /// 9898 /// \param D Declaration that is checked. 9899 /// \param PrevDecl Previous declaration found with proper lookup method for the 9900 /// same declaration name. 9901 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9902 /// belongs to. 9903 /// 9904 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9905 if (!D->getLexicalDeclContext()->isDependentContext()) 9906 return true; 9907 9908 // Don't chain dependent friend function definitions until instantiation, to 9909 // permit cases like 9910 // 9911 // void func(); 9912 // template<typename T> class C1 { friend void func() {} }; 9913 // template<typename T> class C2 { friend void func() {} }; 9914 // 9915 // ... which is valid if only one of C1 and C2 is ever instantiated. 9916 // 9917 // FIXME: This need only apply to function definitions. For now, we proxy 9918 // this by checking for a file-scope function. We do not want this to apply 9919 // to friend declarations nominating member functions, because that gets in 9920 // the way of access checks. 9921 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9922 return false; 9923 9924 auto *VD = dyn_cast<ValueDecl>(D); 9925 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9926 return !VD || !PrevVD || 9927 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9928 PrevVD->getType()); 9929 } 9930 9931 /// Check the target attribute of the function for MultiVersion 9932 /// validity. 9933 /// 9934 /// Returns true if there was an error, false otherwise. 9935 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9936 const auto *TA = FD->getAttr<TargetAttr>(); 9937 assert(TA && "MultiVersion Candidate requires a target attribute"); 9938 ParsedTargetAttr ParseInfo = TA->parse(); 9939 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9940 enum ErrType { Feature = 0, Architecture = 1 }; 9941 9942 if (!ParseInfo.Architecture.empty() && 9943 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9944 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9945 << Architecture << ParseInfo.Architecture; 9946 return true; 9947 } 9948 9949 for (const auto &Feat : ParseInfo.Features) { 9950 auto BareFeat = StringRef{Feat}.substr(1); 9951 if (Feat[0] == '-') { 9952 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9953 << Feature << ("no-" + BareFeat).str(); 9954 return true; 9955 } 9956 9957 if (!TargetInfo.validateCpuSupports(BareFeat) || 9958 !TargetInfo.isValidFeatureName(BareFeat)) { 9959 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9960 << Feature << BareFeat; 9961 return true; 9962 } 9963 } 9964 return false; 9965 } 9966 9967 // Provide a white-list of attributes that are allowed to be combined with 9968 // multiversion functions. 9969 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9970 MultiVersionKind MVType) { 9971 switch (Kind) { 9972 default: 9973 return false; 9974 case attr::Used: 9975 return MVType == MultiVersionKind::Target; 9976 } 9977 } 9978 9979 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9980 MultiVersionKind MVType) { 9981 for (const Attr *A : FD->attrs()) { 9982 switch (A->getKind()) { 9983 case attr::CPUDispatch: 9984 case attr::CPUSpecific: 9985 if (MVType != MultiVersionKind::CPUDispatch && 9986 MVType != MultiVersionKind::CPUSpecific) 9987 return true; 9988 break; 9989 case attr::Target: 9990 if (MVType != MultiVersionKind::Target) 9991 return true; 9992 break; 9993 default: 9994 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 9995 return true; 9996 break; 9997 } 9998 } 9999 return false; 10000 } 10001 10002 bool Sema::areMultiversionVariantFunctionsCompatible( 10003 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10004 const PartialDiagnostic &NoProtoDiagID, 10005 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10006 const PartialDiagnosticAt &NoSupportDiagIDAt, 10007 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10008 bool ConstexprSupported, bool CLinkageMayDiffer) { 10009 enum DoesntSupport { 10010 FuncTemplates = 0, 10011 VirtFuncs = 1, 10012 DeducedReturn = 2, 10013 Constructors = 3, 10014 Destructors = 4, 10015 DeletedFuncs = 5, 10016 DefaultedFuncs = 6, 10017 ConstexprFuncs = 7, 10018 ConstevalFuncs = 8, 10019 }; 10020 enum Different { 10021 CallingConv = 0, 10022 ReturnType = 1, 10023 ConstexprSpec = 2, 10024 InlineSpec = 3, 10025 StorageClass = 4, 10026 Linkage = 5, 10027 }; 10028 10029 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10030 !OldFD->getType()->getAs<FunctionProtoType>()) { 10031 Diag(OldFD->getLocation(), NoProtoDiagID); 10032 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10033 return true; 10034 } 10035 10036 if (NoProtoDiagID.getDiagID() != 0 && 10037 !NewFD->getType()->getAs<FunctionProtoType>()) 10038 return Diag(NewFD->getLocation(), NoProtoDiagID); 10039 10040 if (!TemplatesSupported && 10041 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10042 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10043 << FuncTemplates; 10044 10045 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10046 if (NewCXXFD->isVirtual()) 10047 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10048 << VirtFuncs; 10049 10050 if (isa<CXXConstructorDecl>(NewCXXFD)) 10051 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10052 << Constructors; 10053 10054 if (isa<CXXDestructorDecl>(NewCXXFD)) 10055 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10056 << Destructors; 10057 } 10058 10059 if (NewFD->isDeleted()) 10060 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10061 << DeletedFuncs; 10062 10063 if (NewFD->isDefaulted()) 10064 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10065 << DefaultedFuncs; 10066 10067 if (!ConstexprSupported && NewFD->isConstexpr()) 10068 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10069 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10070 10071 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10072 const auto *NewType = cast<FunctionType>(NewQType); 10073 QualType NewReturnType = NewType->getReturnType(); 10074 10075 if (NewReturnType->isUndeducedType()) 10076 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10077 << DeducedReturn; 10078 10079 // Ensure the return type is identical. 10080 if (OldFD) { 10081 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10082 const auto *OldType = cast<FunctionType>(OldQType); 10083 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10084 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10085 10086 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10087 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10088 10089 QualType OldReturnType = OldType->getReturnType(); 10090 10091 if (OldReturnType != NewReturnType) 10092 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10093 10094 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10095 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10096 10097 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10098 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10099 10100 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10101 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10102 10103 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10104 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10105 10106 if (CheckEquivalentExceptionSpec( 10107 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10108 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10109 return true; 10110 } 10111 return false; 10112 } 10113 10114 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10115 const FunctionDecl *NewFD, 10116 bool CausesMV, 10117 MultiVersionKind MVType) { 10118 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10119 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10120 if (OldFD) 10121 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10122 return true; 10123 } 10124 10125 bool IsCPUSpecificCPUDispatchMVType = 10126 MVType == MultiVersionKind::CPUDispatch || 10127 MVType == MultiVersionKind::CPUSpecific; 10128 10129 // For now, disallow all other attributes. These should be opt-in, but 10130 // an analysis of all of them is a future FIXME. 10131 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10132 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10133 << IsCPUSpecificCPUDispatchMVType; 10134 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10135 return true; 10136 } 10137 10138 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10139 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10140 << IsCPUSpecificCPUDispatchMVType; 10141 10142 // Only allow transition to MultiVersion if it hasn't been used. 10143 if (OldFD && CausesMV && OldFD->isUsed(false)) 10144 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10145 10146 return S.areMultiversionVariantFunctionsCompatible( 10147 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10148 PartialDiagnosticAt(NewFD->getLocation(), 10149 S.PDiag(diag::note_multiversioning_caused_here)), 10150 PartialDiagnosticAt(NewFD->getLocation(), 10151 S.PDiag(diag::err_multiversion_doesnt_support) 10152 << IsCPUSpecificCPUDispatchMVType), 10153 PartialDiagnosticAt(NewFD->getLocation(), 10154 S.PDiag(diag::err_multiversion_diff)), 10155 /*TemplatesSupported=*/false, 10156 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10157 /*CLinkageMayDiffer=*/false); 10158 } 10159 10160 /// Check the validity of a multiversion function declaration that is the 10161 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10162 /// 10163 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10164 /// 10165 /// Returns true if there was an error, false otherwise. 10166 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10167 MultiVersionKind MVType, 10168 const TargetAttr *TA) { 10169 assert(MVType != MultiVersionKind::None && 10170 "Function lacks multiversion attribute"); 10171 10172 // Target only causes MV if it is default, otherwise this is a normal 10173 // function. 10174 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10175 return false; 10176 10177 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10178 FD->setInvalidDecl(); 10179 return true; 10180 } 10181 10182 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10183 FD->setInvalidDecl(); 10184 return true; 10185 } 10186 10187 FD->setIsMultiVersion(); 10188 return false; 10189 } 10190 10191 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10192 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10193 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10194 return true; 10195 } 10196 10197 return false; 10198 } 10199 10200 static bool CheckTargetCausesMultiVersioning( 10201 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10202 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10203 LookupResult &Previous) { 10204 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10205 ParsedTargetAttr NewParsed = NewTA->parse(); 10206 // Sort order doesn't matter, it just needs to be consistent. 10207 llvm::sort(NewParsed.Features); 10208 10209 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10210 // to change, this is a simple redeclaration. 10211 if (!NewTA->isDefaultVersion() && 10212 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10213 return false; 10214 10215 // Otherwise, this decl causes MultiVersioning. 10216 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10217 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10218 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10219 NewFD->setInvalidDecl(); 10220 return true; 10221 } 10222 10223 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10224 MultiVersionKind::Target)) { 10225 NewFD->setInvalidDecl(); 10226 return true; 10227 } 10228 10229 if (CheckMultiVersionValue(S, NewFD)) { 10230 NewFD->setInvalidDecl(); 10231 return true; 10232 } 10233 10234 // If this is 'default', permit the forward declaration. 10235 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10236 Redeclaration = true; 10237 OldDecl = OldFD; 10238 OldFD->setIsMultiVersion(); 10239 NewFD->setIsMultiVersion(); 10240 return false; 10241 } 10242 10243 if (CheckMultiVersionValue(S, OldFD)) { 10244 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10245 NewFD->setInvalidDecl(); 10246 return true; 10247 } 10248 10249 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10250 10251 if (OldParsed == NewParsed) { 10252 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10253 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10254 NewFD->setInvalidDecl(); 10255 return true; 10256 } 10257 10258 for (const auto *FD : OldFD->redecls()) { 10259 const auto *CurTA = FD->getAttr<TargetAttr>(); 10260 // We allow forward declarations before ANY multiversioning attributes, but 10261 // nothing after the fact. 10262 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10263 (!CurTA || CurTA->isInherited())) { 10264 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10265 << 0; 10266 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10267 NewFD->setInvalidDecl(); 10268 return true; 10269 } 10270 } 10271 10272 OldFD->setIsMultiVersion(); 10273 NewFD->setIsMultiVersion(); 10274 Redeclaration = false; 10275 MergeTypeWithPrevious = false; 10276 OldDecl = nullptr; 10277 Previous.clear(); 10278 return false; 10279 } 10280 10281 /// Check the validity of a new function declaration being added to an existing 10282 /// multiversioned declaration collection. 10283 static bool CheckMultiVersionAdditionalDecl( 10284 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10285 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10286 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10287 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10288 LookupResult &Previous) { 10289 10290 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10291 // Disallow mixing of multiversioning types. 10292 if ((OldMVType == MultiVersionKind::Target && 10293 NewMVType != MultiVersionKind::Target) || 10294 (NewMVType == MultiVersionKind::Target && 10295 OldMVType != MultiVersionKind::Target)) { 10296 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10297 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10298 NewFD->setInvalidDecl(); 10299 return true; 10300 } 10301 10302 ParsedTargetAttr NewParsed; 10303 if (NewTA) { 10304 NewParsed = NewTA->parse(); 10305 llvm::sort(NewParsed.Features); 10306 } 10307 10308 bool UseMemberUsingDeclRules = 10309 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10310 10311 // Next, check ALL non-overloads to see if this is a redeclaration of a 10312 // previous member of the MultiVersion set. 10313 for (NamedDecl *ND : Previous) { 10314 FunctionDecl *CurFD = ND->getAsFunction(); 10315 if (!CurFD) 10316 continue; 10317 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10318 continue; 10319 10320 if (NewMVType == MultiVersionKind::Target) { 10321 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10322 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10323 NewFD->setIsMultiVersion(); 10324 Redeclaration = true; 10325 OldDecl = ND; 10326 return false; 10327 } 10328 10329 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10330 if (CurParsed == NewParsed) { 10331 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10332 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10333 NewFD->setInvalidDecl(); 10334 return true; 10335 } 10336 } else { 10337 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10338 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10339 // Handle CPUDispatch/CPUSpecific versions. 10340 // Only 1 CPUDispatch function is allowed, this will make it go through 10341 // the redeclaration errors. 10342 if (NewMVType == MultiVersionKind::CPUDispatch && 10343 CurFD->hasAttr<CPUDispatchAttr>()) { 10344 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10345 std::equal( 10346 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10347 NewCPUDisp->cpus_begin(), 10348 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10349 return Cur->getName() == New->getName(); 10350 })) { 10351 NewFD->setIsMultiVersion(); 10352 Redeclaration = true; 10353 OldDecl = ND; 10354 return false; 10355 } 10356 10357 // If the declarations don't match, this is an error condition. 10358 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10359 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10360 NewFD->setInvalidDecl(); 10361 return true; 10362 } 10363 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10364 10365 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10366 std::equal( 10367 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10368 NewCPUSpec->cpus_begin(), 10369 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10370 return Cur->getName() == New->getName(); 10371 })) { 10372 NewFD->setIsMultiVersion(); 10373 Redeclaration = true; 10374 OldDecl = ND; 10375 return false; 10376 } 10377 10378 // Only 1 version of CPUSpecific is allowed for each CPU. 10379 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10380 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10381 if (CurII == NewII) { 10382 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10383 << NewII; 10384 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10385 NewFD->setInvalidDecl(); 10386 return true; 10387 } 10388 } 10389 } 10390 } 10391 // If the two decls aren't the same MVType, there is no possible error 10392 // condition. 10393 } 10394 } 10395 10396 // Else, this is simply a non-redecl case. Checking the 'value' is only 10397 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10398 // handled in the attribute adding step. 10399 if (NewMVType == MultiVersionKind::Target && 10400 CheckMultiVersionValue(S, NewFD)) { 10401 NewFD->setInvalidDecl(); 10402 return true; 10403 } 10404 10405 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10406 !OldFD->isMultiVersion(), NewMVType)) { 10407 NewFD->setInvalidDecl(); 10408 return true; 10409 } 10410 10411 // Permit forward declarations in the case where these two are compatible. 10412 if (!OldFD->isMultiVersion()) { 10413 OldFD->setIsMultiVersion(); 10414 NewFD->setIsMultiVersion(); 10415 Redeclaration = true; 10416 OldDecl = OldFD; 10417 return false; 10418 } 10419 10420 NewFD->setIsMultiVersion(); 10421 Redeclaration = false; 10422 MergeTypeWithPrevious = false; 10423 OldDecl = nullptr; 10424 Previous.clear(); 10425 return false; 10426 } 10427 10428 10429 /// Check the validity of a mulitversion function declaration. 10430 /// Also sets the multiversion'ness' of the function itself. 10431 /// 10432 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10433 /// 10434 /// Returns true if there was an error, false otherwise. 10435 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10436 bool &Redeclaration, NamedDecl *&OldDecl, 10437 bool &MergeTypeWithPrevious, 10438 LookupResult &Previous) { 10439 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10440 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10441 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10442 10443 // Mixing Multiversioning types is prohibited. 10444 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10445 (NewCPUDisp && NewCPUSpec)) { 10446 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10447 NewFD->setInvalidDecl(); 10448 return true; 10449 } 10450 10451 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10452 10453 // Main isn't allowed to become a multiversion function, however it IS 10454 // permitted to have 'main' be marked with the 'target' optimization hint. 10455 if (NewFD->isMain()) { 10456 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10457 MVType == MultiVersionKind::CPUDispatch || 10458 MVType == MultiVersionKind::CPUSpecific) { 10459 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10460 NewFD->setInvalidDecl(); 10461 return true; 10462 } 10463 return false; 10464 } 10465 10466 if (!OldDecl || !OldDecl->getAsFunction() || 10467 OldDecl->getDeclContext()->getRedeclContext() != 10468 NewFD->getDeclContext()->getRedeclContext()) { 10469 // If there's no previous declaration, AND this isn't attempting to cause 10470 // multiversioning, this isn't an error condition. 10471 if (MVType == MultiVersionKind::None) 10472 return false; 10473 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10474 } 10475 10476 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10477 10478 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10479 return false; 10480 10481 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10482 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10483 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10484 NewFD->setInvalidDecl(); 10485 return true; 10486 } 10487 10488 // Handle the target potentially causes multiversioning case. 10489 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10490 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10491 Redeclaration, OldDecl, 10492 MergeTypeWithPrevious, Previous); 10493 10494 // At this point, we have a multiversion function decl (in OldFD) AND an 10495 // appropriate attribute in the current function decl. Resolve that these are 10496 // still compatible with previous declarations. 10497 return CheckMultiVersionAdditionalDecl( 10498 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10499 OldDecl, MergeTypeWithPrevious, Previous); 10500 } 10501 10502 /// Perform semantic checking of a new function declaration. 10503 /// 10504 /// Performs semantic analysis of the new function declaration 10505 /// NewFD. This routine performs all semantic checking that does not 10506 /// require the actual declarator involved in the declaration, and is 10507 /// used both for the declaration of functions as they are parsed 10508 /// (called via ActOnDeclarator) and for the declaration of functions 10509 /// that have been instantiated via C++ template instantiation (called 10510 /// via InstantiateDecl). 10511 /// 10512 /// \param IsMemberSpecialization whether this new function declaration is 10513 /// a member specialization (that replaces any definition provided by the 10514 /// previous declaration). 10515 /// 10516 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10517 /// 10518 /// \returns true if the function declaration is a redeclaration. 10519 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10520 LookupResult &Previous, 10521 bool IsMemberSpecialization) { 10522 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10523 "Variably modified return types are not handled here"); 10524 10525 // Determine whether the type of this function should be merged with 10526 // a previous visible declaration. This never happens for functions in C++, 10527 // and always happens in C if the previous declaration was visible. 10528 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10529 !Previous.isShadowed(); 10530 10531 bool Redeclaration = false; 10532 NamedDecl *OldDecl = nullptr; 10533 bool MayNeedOverloadableChecks = false; 10534 10535 // Merge or overload the declaration with an existing declaration of 10536 // the same name, if appropriate. 10537 if (!Previous.empty()) { 10538 // Determine whether NewFD is an overload of PrevDecl or 10539 // a declaration that requires merging. If it's an overload, 10540 // there's no more work to do here; we'll just add the new 10541 // function to the scope. 10542 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10543 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10544 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10545 Redeclaration = true; 10546 OldDecl = Candidate; 10547 } 10548 } else { 10549 MayNeedOverloadableChecks = true; 10550 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10551 /*NewIsUsingDecl*/ false)) { 10552 case Ovl_Match: 10553 Redeclaration = true; 10554 break; 10555 10556 case Ovl_NonFunction: 10557 Redeclaration = true; 10558 break; 10559 10560 case Ovl_Overload: 10561 Redeclaration = false; 10562 break; 10563 } 10564 } 10565 } 10566 10567 // Check for a previous extern "C" declaration with this name. 10568 if (!Redeclaration && 10569 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10570 if (!Previous.empty()) { 10571 // This is an extern "C" declaration with the same name as a previous 10572 // declaration, and thus redeclares that entity... 10573 Redeclaration = true; 10574 OldDecl = Previous.getFoundDecl(); 10575 MergeTypeWithPrevious = false; 10576 10577 // ... except in the presence of __attribute__((overloadable)). 10578 if (OldDecl->hasAttr<OverloadableAttr>() || 10579 NewFD->hasAttr<OverloadableAttr>()) { 10580 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10581 MayNeedOverloadableChecks = true; 10582 Redeclaration = false; 10583 OldDecl = nullptr; 10584 } 10585 } 10586 } 10587 } 10588 10589 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10590 MergeTypeWithPrevious, Previous)) 10591 return Redeclaration; 10592 10593 // C++11 [dcl.constexpr]p8: 10594 // A constexpr specifier for a non-static member function that is not 10595 // a constructor declares that member function to be const. 10596 // 10597 // This needs to be delayed until we know whether this is an out-of-line 10598 // definition of a static member function. 10599 // 10600 // This rule is not present in C++1y, so we produce a backwards 10601 // compatibility warning whenever it happens in C++11. 10602 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10603 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10604 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10605 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10606 CXXMethodDecl *OldMD = nullptr; 10607 if (OldDecl) 10608 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10609 if (!OldMD || !OldMD->isStatic()) { 10610 const FunctionProtoType *FPT = 10611 MD->getType()->castAs<FunctionProtoType>(); 10612 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10613 EPI.TypeQuals.addConst(); 10614 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10615 FPT->getParamTypes(), EPI)); 10616 10617 // Warn that we did this, if we're not performing template instantiation. 10618 // In that case, we'll have warned already when the template was defined. 10619 if (!inTemplateInstantiation()) { 10620 SourceLocation AddConstLoc; 10621 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10622 .IgnoreParens().getAs<FunctionTypeLoc>()) 10623 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10624 10625 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10626 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10627 } 10628 } 10629 } 10630 10631 if (Redeclaration) { 10632 // NewFD and OldDecl represent declarations that need to be 10633 // merged. 10634 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10635 NewFD->setInvalidDecl(); 10636 return Redeclaration; 10637 } 10638 10639 Previous.clear(); 10640 Previous.addDecl(OldDecl); 10641 10642 if (FunctionTemplateDecl *OldTemplateDecl = 10643 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10644 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10645 FunctionTemplateDecl *NewTemplateDecl 10646 = NewFD->getDescribedFunctionTemplate(); 10647 assert(NewTemplateDecl && "Template/non-template mismatch"); 10648 10649 // The call to MergeFunctionDecl above may have created some state in 10650 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10651 // can add it as a redeclaration. 10652 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10653 10654 NewFD->setPreviousDeclaration(OldFD); 10655 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10656 if (NewFD->isCXXClassMember()) { 10657 NewFD->setAccess(OldTemplateDecl->getAccess()); 10658 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10659 } 10660 10661 // If this is an explicit specialization of a member that is a function 10662 // template, mark it as a member specialization. 10663 if (IsMemberSpecialization && 10664 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10665 NewTemplateDecl->setMemberSpecialization(); 10666 assert(OldTemplateDecl->isMemberSpecialization()); 10667 // Explicit specializations of a member template do not inherit deleted 10668 // status from the parent member template that they are specializing. 10669 if (OldFD->isDeleted()) { 10670 // FIXME: This assert will not hold in the presence of modules. 10671 assert(OldFD->getCanonicalDecl() == OldFD); 10672 // FIXME: We need an update record for this AST mutation. 10673 OldFD->setDeletedAsWritten(false); 10674 } 10675 } 10676 10677 } else { 10678 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10679 auto *OldFD = cast<FunctionDecl>(OldDecl); 10680 // This needs to happen first so that 'inline' propagates. 10681 NewFD->setPreviousDeclaration(OldFD); 10682 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10683 if (NewFD->isCXXClassMember()) 10684 NewFD->setAccess(OldFD->getAccess()); 10685 } 10686 } 10687 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10688 !NewFD->getAttr<OverloadableAttr>()) { 10689 assert((Previous.empty() || 10690 llvm::any_of(Previous, 10691 [](const NamedDecl *ND) { 10692 return ND->hasAttr<OverloadableAttr>(); 10693 })) && 10694 "Non-redecls shouldn't happen without overloadable present"); 10695 10696 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10697 const auto *FD = dyn_cast<FunctionDecl>(ND); 10698 return FD && !FD->hasAttr<OverloadableAttr>(); 10699 }); 10700 10701 if (OtherUnmarkedIter != Previous.end()) { 10702 Diag(NewFD->getLocation(), 10703 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10704 Diag((*OtherUnmarkedIter)->getLocation(), 10705 diag::note_attribute_overloadable_prev_overload) 10706 << false; 10707 10708 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10709 } 10710 } 10711 10712 // Semantic checking for this function declaration (in isolation). 10713 10714 if (getLangOpts().CPlusPlus) { 10715 // C++-specific checks. 10716 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10717 CheckConstructor(Constructor); 10718 } else if (CXXDestructorDecl *Destructor = 10719 dyn_cast<CXXDestructorDecl>(NewFD)) { 10720 CXXRecordDecl *Record = Destructor->getParent(); 10721 QualType ClassType = Context.getTypeDeclType(Record); 10722 10723 // FIXME: Shouldn't we be able to perform this check even when the class 10724 // type is dependent? Both gcc and edg can handle that. 10725 if (!ClassType->isDependentType()) { 10726 DeclarationName Name 10727 = Context.DeclarationNames.getCXXDestructorName( 10728 Context.getCanonicalType(ClassType)); 10729 if (NewFD->getDeclName() != Name) { 10730 Diag(NewFD->getLocation(), diag::err_destructor_name); 10731 NewFD->setInvalidDecl(); 10732 return Redeclaration; 10733 } 10734 } 10735 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10736 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10737 CheckDeductionGuideTemplate(TD); 10738 10739 // A deduction guide is not on the list of entities that can be 10740 // explicitly specialized. 10741 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10742 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10743 << /*explicit specialization*/ 1; 10744 } 10745 10746 // Find any virtual functions that this function overrides. 10747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10748 if (!Method->isFunctionTemplateSpecialization() && 10749 !Method->getDescribedFunctionTemplate() && 10750 Method->isCanonicalDecl()) { 10751 AddOverriddenMethods(Method->getParent(), Method); 10752 } 10753 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10754 // C++2a [class.virtual]p6 10755 // A virtual method shall not have a requires-clause. 10756 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10757 diag::err_constrained_virtual_method); 10758 10759 if (Method->isStatic()) 10760 checkThisInStaticMemberFunctionType(Method); 10761 } 10762 10763 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10764 ActOnConversionDeclarator(Conversion); 10765 10766 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10767 if (NewFD->isOverloadedOperator() && 10768 CheckOverloadedOperatorDeclaration(NewFD)) { 10769 NewFD->setInvalidDecl(); 10770 return Redeclaration; 10771 } 10772 10773 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10774 if (NewFD->getLiteralIdentifier() && 10775 CheckLiteralOperatorDeclaration(NewFD)) { 10776 NewFD->setInvalidDecl(); 10777 return Redeclaration; 10778 } 10779 10780 // In C++, check default arguments now that we have merged decls. Unless 10781 // the lexical context is the class, because in this case this is done 10782 // during delayed parsing anyway. 10783 if (!CurContext->isRecord()) 10784 CheckCXXDefaultArguments(NewFD); 10785 10786 // If this function declares a builtin function, check the type of this 10787 // declaration against the expected type for the builtin. 10788 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10789 ASTContext::GetBuiltinTypeError Error; 10790 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10791 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10792 // If the type of the builtin differs only in its exception 10793 // specification, that's OK. 10794 // FIXME: If the types do differ in this way, it would be better to 10795 // retain the 'noexcept' form of the type. 10796 if (!T.isNull() && 10797 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10798 NewFD->getType())) 10799 // The type of this function differs from the type of the builtin, 10800 // so forget about the builtin entirely. 10801 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10802 } 10803 10804 // If this function is declared as being extern "C", then check to see if 10805 // the function returns a UDT (class, struct, or union type) that is not C 10806 // compatible, and if it does, warn the user. 10807 // But, issue any diagnostic on the first declaration only. 10808 if (Previous.empty() && NewFD->isExternC()) { 10809 QualType R = NewFD->getReturnType(); 10810 if (R->isIncompleteType() && !R->isVoidType()) 10811 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10812 << NewFD << R; 10813 else if (!R.isPODType(Context) && !R->isVoidType() && 10814 !R->isObjCObjectPointerType()) 10815 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10816 } 10817 10818 // C++1z [dcl.fct]p6: 10819 // [...] whether the function has a non-throwing exception-specification 10820 // [is] part of the function type 10821 // 10822 // This results in an ABI break between C++14 and C++17 for functions whose 10823 // declared type includes an exception-specification in a parameter or 10824 // return type. (Exception specifications on the function itself are OK in 10825 // most cases, and exception specifications are not permitted in most other 10826 // contexts where they could make it into a mangling.) 10827 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10828 auto HasNoexcept = [&](QualType T) -> bool { 10829 // Strip off declarator chunks that could be between us and a function 10830 // type. We don't need to look far, exception specifications are very 10831 // restricted prior to C++17. 10832 if (auto *RT = T->getAs<ReferenceType>()) 10833 T = RT->getPointeeType(); 10834 else if (T->isAnyPointerType()) 10835 T = T->getPointeeType(); 10836 else if (auto *MPT = T->getAs<MemberPointerType>()) 10837 T = MPT->getPointeeType(); 10838 if (auto *FPT = T->getAs<FunctionProtoType>()) 10839 if (FPT->isNothrow()) 10840 return true; 10841 return false; 10842 }; 10843 10844 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10845 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10846 for (QualType T : FPT->param_types()) 10847 AnyNoexcept |= HasNoexcept(T); 10848 if (AnyNoexcept) 10849 Diag(NewFD->getLocation(), 10850 diag::warn_cxx17_compat_exception_spec_in_signature) 10851 << NewFD; 10852 } 10853 10854 if (!Redeclaration && LangOpts.CUDA) 10855 checkCUDATargetOverload(NewFD, Previous); 10856 } 10857 return Redeclaration; 10858 } 10859 10860 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10861 // C++11 [basic.start.main]p3: 10862 // A program that [...] declares main to be inline, static or 10863 // constexpr is ill-formed. 10864 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10865 // appear in a declaration of main. 10866 // static main is not an error under C99, but we should warn about it. 10867 // We accept _Noreturn main as an extension. 10868 if (FD->getStorageClass() == SC_Static) 10869 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10870 ? diag::err_static_main : diag::warn_static_main) 10871 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10872 if (FD->isInlineSpecified()) 10873 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10874 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10875 if (DS.isNoreturnSpecified()) { 10876 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10877 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10878 Diag(NoreturnLoc, diag::ext_noreturn_main); 10879 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10880 << FixItHint::CreateRemoval(NoreturnRange); 10881 } 10882 if (FD->isConstexpr()) { 10883 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10884 << FD->isConsteval() 10885 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10886 FD->setConstexprKind(CSK_unspecified); 10887 } 10888 10889 if (getLangOpts().OpenCL) { 10890 Diag(FD->getLocation(), diag::err_opencl_no_main) 10891 << FD->hasAttr<OpenCLKernelAttr>(); 10892 FD->setInvalidDecl(); 10893 return; 10894 } 10895 10896 QualType T = FD->getType(); 10897 assert(T->isFunctionType() && "function decl is not of function type"); 10898 const FunctionType* FT = T->castAs<FunctionType>(); 10899 10900 // Set default calling convention for main() 10901 if (FT->getCallConv() != CC_C) { 10902 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10903 FD->setType(QualType(FT, 0)); 10904 T = Context.getCanonicalType(FD->getType()); 10905 } 10906 10907 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10908 // In C with GNU extensions we allow main() to have non-integer return 10909 // type, but we should warn about the extension, and we disable the 10910 // implicit-return-zero rule. 10911 10912 // GCC in C mode accepts qualified 'int'. 10913 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10914 FD->setHasImplicitReturnZero(true); 10915 else { 10916 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10917 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10918 if (RTRange.isValid()) 10919 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10920 << FixItHint::CreateReplacement(RTRange, "int"); 10921 } 10922 } else { 10923 // In C and C++, main magically returns 0 if you fall off the end; 10924 // set the flag which tells us that. 10925 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10926 10927 // All the standards say that main() should return 'int'. 10928 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10929 FD->setHasImplicitReturnZero(true); 10930 else { 10931 // Otherwise, this is just a flat-out error. 10932 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10933 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10934 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10935 : FixItHint()); 10936 FD->setInvalidDecl(true); 10937 } 10938 } 10939 10940 // Treat protoless main() as nullary. 10941 if (isa<FunctionNoProtoType>(FT)) return; 10942 10943 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10944 unsigned nparams = FTP->getNumParams(); 10945 assert(FD->getNumParams() == nparams); 10946 10947 bool HasExtraParameters = (nparams > 3); 10948 10949 if (FTP->isVariadic()) { 10950 Diag(FD->getLocation(), diag::ext_variadic_main); 10951 // FIXME: if we had information about the location of the ellipsis, we 10952 // could add a FixIt hint to remove it as a parameter. 10953 } 10954 10955 // Darwin passes an undocumented fourth argument of type char**. If 10956 // other platforms start sprouting these, the logic below will start 10957 // getting shifty. 10958 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10959 HasExtraParameters = false; 10960 10961 if (HasExtraParameters) { 10962 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10963 FD->setInvalidDecl(true); 10964 nparams = 3; 10965 } 10966 10967 // FIXME: a lot of the following diagnostics would be improved 10968 // if we had some location information about types. 10969 10970 QualType CharPP = 10971 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10972 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10973 10974 for (unsigned i = 0; i < nparams; ++i) { 10975 QualType AT = FTP->getParamType(i); 10976 10977 bool mismatch = true; 10978 10979 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10980 mismatch = false; 10981 else if (Expected[i] == CharPP) { 10982 // As an extension, the following forms are okay: 10983 // char const ** 10984 // char const * const * 10985 // char * const * 10986 10987 QualifierCollector qs; 10988 const PointerType* PT; 10989 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10990 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10991 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10992 Context.CharTy)) { 10993 qs.removeConst(); 10994 mismatch = !qs.empty(); 10995 } 10996 } 10997 10998 if (mismatch) { 10999 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11000 // TODO: suggest replacing given type with expected type 11001 FD->setInvalidDecl(true); 11002 } 11003 } 11004 11005 if (nparams == 1 && !FD->isInvalidDecl()) { 11006 Diag(FD->getLocation(), diag::warn_main_one_arg); 11007 } 11008 11009 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11010 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11011 FD->setInvalidDecl(); 11012 } 11013 } 11014 11015 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11016 QualType T = FD->getType(); 11017 assert(T->isFunctionType() && "function decl is not of function type"); 11018 const FunctionType *FT = T->castAs<FunctionType>(); 11019 11020 // Set an implicit return of 'zero' if the function can return some integral, 11021 // enumeration, pointer or nullptr type. 11022 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11023 FT->getReturnType()->isAnyPointerType() || 11024 FT->getReturnType()->isNullPtrType()) 11025 // DllMain is exempt because a return value of zero means it failed. 11026 if (FD->getName() != "DllMain") 11027 FD->setHasImplicitReturnZero(true); 11028 11029 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11030 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11031 FD->setInvalidDecl(); 11032 } 11033 } 11034 11035 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11036 // FIXME: Need strict checking. In C89, we need to check for 11037 // any assignment, increment, decrement, function-calls, or 11038 // commas outside of a sizeof. In C99, it's the same list, 11039 // except that the aforementioned are allowed in unevaluated 11040 // expressions. Everything else falls under the 11041 // "may accept other forms of constant expressions" exception. 11042 // (We never end up here for C++, so the constant expression 11043 // rules there don't matter.) 11044 const Expr *Culprit; 11045 if (Init->isConstantInitializer(Context, false, &Culprit)) 11046 return false; 11047 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11048 << Culprit->getSourceRange(); 11049 return true; 11050 } 11051 11052 namespace { 11053 // Visits an initialization expression to see if OrigDecl is evaluated in 11054 // its own initialization and throws a warning if it does. 11055 class SelfReferenceChecker 11056 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11057 Sema &S; 11058 Decl *OrigDecl; 11059 bool isRecordType; 11060 bool isPODType; 11061 bool isReferenceType; 11062 11063 bool isInitList; 11064 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11065 11066 public: 11067 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11068 11069 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11070 S(S), OrigDecl(OrigDecl) { 11071 isPODType = false; 11072 isRecordType = false; 11073 isReferenceType = false; 11074 isInitList = false; 11075 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11076 isPODType = VD->getType().isPODType(S.Context); 11077 isRecordType = VD->getType()->isRecordType(); 11078 isReferenceType = VD->getType()->isReferenceType(); 11079 } 11080 } 11081 11082 // For most expressions, just call the visitor. For initializer lists, 11083 // track the index of the field being initialized since fields are 11084 // initialized in order allowing use of previously initialized fields. 11085 void CheckExpr(Expr *E) { 11086 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11087 if (!InitList) { 11088 Visit(E); 11089 return; 11090 } 11091 11092 // Track and increment the index here. 11093 isInitList = true; 11094 InitFieldIndex.push_back(0); 11095 for (auto Child : InitList->children()) { 11096 CheckExpr(cast<Expr>(Child)); 11097 ++InitFieldIndex.back(); 11098 } 11099 InitFieldIndex.pop_back(); 11100 } 11101 11102 // Returns true if MemberExpr is checked and no further checking is needed. 11103 // Returns false if additional checking is required. 11104 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11105 llvm::SmallVector<FieldDecl*, 4> Fields; 11106 Expr *Base = E; 11107 bool ReferenceField = false; 11108 11109 // Get the field members used. 11110 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11111 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11112 if (!FD) 11113 return false; 11114 Fields.push_back(FD); 11115 if (FD->getType()->isReferenceType()) 11116 ReferenceField = true; 11117 Base = ME->getBase()->IgnoreParenImpCasts(); 11118 } 11119 11120 // Keep checking only if the base Decl is the same. 11121 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11122 if (!DRE || DRE->getDecl() != OrigDecl) 11123 return false; 11124 11125 // A reference field can be bound to an unininitialized field. 11126 if (CheckReference && !ReferenceField) 11127 return true; 11128 11129 // Convert FieldDecls to their index number. 11130 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11131 for (const FieldDecl *I : llvm::reverse(Fields)) 11132 UsedFieldIndex.push_back(I->getFieldIndex()); 11133 11134 // See if a warning is needed by checking the first difference in index 11135 // numbers. If field being used has index less than the field being 11136 // initialized, then the use is safe. 11137 for (auto UsedIter = UsedFieldIndex.begin(), 11138 UsedEnd = UsedFieldIndex.end(), 11139 OrigIter = InitFieldIndex.begin(), 11140 OrigEnd = InitFieldIndex.end(); 11141 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11142 if (*UsedIter < *OrigIter) 11143 return true; 11144 if (*UsedIter > *OrigIter) 11145 break; 11146 } 11147 11148 // TODO: Add a different warning which will print the field names. 11149 HandleDeclRefExpr(DRE); 11150 return true; 11151 } 11152 11153 // For most expressions, the cast is directly above the DeclRefExpr. 11154 // For conditional operators, the cast can be outside the conditional 11155 // operator if both expressions are DeclRefExpr's. 11156 void HandleValue(Expr *E) { 11157 E = E->IgnoreParens(); 11158 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11159 HandleDeclRefExpr(DRE); 11160 return; 11161 } 11162 11163 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11164 Visit(CO->getCond()); 11165 HandleValue(CO->getTrueExpr()); 11166 HandleValue(CO->getFalseExpr()); 11167 return; 11168 } 11169 11170 if (BinaryConditionalOperator *BCO = 11171 dyn_cast<BinaryConditionalOperator>(E)) { 11172 Visit(BCO->getCond()); 11173 HandleValue(BCO->getFalseExpr()); 11174 return; 11175 } 11176 11177 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11178 HandleValue(OVE->getSourceExpr()); 11179 return; 11180 } 11181 11182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11183 if (BO->getOpcode() == BO_Comma) { 11184 Visit(BO->getLHS()); 11185 HandleValue(BO->getRHS()); 11186 return; 11187 } 11188 } 11189 11190 if (isa<MemberExpr>(E)) { 11191 if (isInitList) { 11192 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11193 false /*CheckReference*/)) 11194 return; 11195 } 11196 11197 Expr *Base = E->IgnoreParenImpCasts(); 11198 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11199 // Check for static member variables and don't warn on them. 11200 if (!isa<FieldDecl>(ME->getMemberDecl())) 11201 return; 11202 Base = ME->getBase()->IgnoreParenImpCasts(); 11203 } 11204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11205 HandleDeclRefExpr(DRE); 11206 return; 11207 } 11208 11209 Visit(E); 11210 } 11211 11212 // Reference types not handled in HandleValue are handled here since all 11213 // uses of references are bad, not just r-value uses. 11214 void VisitDeclRefExpr(DeclRefExpr *E) { 11215 if (isReferenceType) 11216 HandleDeclRefExpr(E); 11217 } 11218 11219 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11220 if (E->getCastKind() == CK_LValueToRValue) { 11221 HandleValue(E->getSubExpr()); 11222 return; 11223 } 11224 11225 Inherited::VisitImplicitCastExpr(E); 11226 } 11227 11228 void VisitMemberExpr(MemberExpr *E) { 11229 if (isInitList) { 11230 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11231 return; 11232 } 11233 11234 // Don't warn on arrays since they can be treated as pointers. 11235 if (E->getType()->canDecayToPointerType()) return; 11236 11237 // Warn when a non-static method call is followed by non-static member 11238 // field accesses, which is followed by a DeclRefExpr. 11239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11240 bool Warn = (MD && !MD->isStatic()); 11241 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11242 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11243 if (!isa<FieldDecl>(ME->getMemberDecl())) 11244 Warn = false; 11245 Base = ME->getBase()->IgnoreParenImpCasts(); 11246 } 11247 11248 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11249 if (Warn) 11250 HandleDeclRefExpr(DRE); 11251 return; 11252 } 11253 11254 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11255 // Visit that expression. 11256 Visit(Base); 11257 } 11258 11259 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11260 Expr *Callee = E->getCallee(); 11261 11262 if (isa<UnresolvedLookupExpr>(Callee)) 11263 return Inherited::VisitCXXOperatorCallExpr(E); 11264 11265 Visit(Callee); 11266 for (auto Arg: E->arguments()) 11267 HandleValue(Arg->IgnoreParenImpCasts()); 11268 } 11269 11270 void VisitUnaryOperator(UnaryOperator *E) { 11271 // For POD record types, addresses of its own members are well-defined. 11272 if (E->getOpcode() == UO_AddrOf && isRecordType && 11273 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11274 if (!isPODType) 11275 HandleValue(E->getSubExpr()); 11276 return; 11277 } 11278 11279 if (E->isIncrementDecrementOp()) { 11280 HandleValue(E->getSubExpr()); 11281 return; 11282 } 11283 11284 Inherited::VisitUnaryOperator(E); 11285 } 11286 11287 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11288 11289 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11290 if (E->getConstructor()->isCopyConstructor()) { 11291 Expr *ArgExpr = E->getArg(0); 11292 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11293 if (ILE->getNumInits() == 1) 11294 ArgExpr = ILE->getInit(0); 11295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11296 if (ICE->getCastKind() == CK_NoOp) 11297 ArgExpr = ICE->getSubExpr(); 11298 HandleValue(ArgExpr); 11299 return; 11300 } 11301 Inherited::VisitCXXConstructExpr(E); 11302 } 11303 11304 void VisitCallExpr(CallExpr *E) { 11305 // Treat std::move as a use. 11306 if (E->isCallToStdMove()) { 11307 HandleValue(E->getArg(0)); 11308 return; 11309 } 11310 11311 Inherited::VisitCallExpr(E); 11312 } 11313 11314 void VisitBinaryOperator(BinaryOperator *E) { 11315 if (E->isCompoundAssignmentOp()) { 11316 HandleValue(E->getLHS()); 11317 Visit(E->getRHS()); 11318 return; 11319 } 11320 11321 Inherited::VisitBinaryOperator(E); 11322 } 11323 11324 // A custom visitor for BinaryConditionalOperator is needed because the 11325 // regular visitor would check the condition and true expression separately 11326 // but both point to the same place giving duplicate diagnostics. 11327 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11328 Visit(E->getCond()); 11329 Visit(E->getFalseExpr()); 11330 } 11331 11332 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11333 Decl* ReferenceDecl = DRE->getDecl(); 11334 if (OrigDecl != ReferenceDecl) return; 11335 unsigned diag; 11336 if (isReferenceType) { 11337 diag = diag::warn_uninit_self_reference_in_reference_init; 11338 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11339 diag = diag::warn_static_self_reference_in_init; 11340 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11341 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11342 DRE->getDecl()->getType()->isRecordType()) { 11343 diag = diag::warn_uninit_self_reference_in_init; 11344 } else { 11345 // Local variables will be handled by the CFG analysis. 11346 return; 11347 } 11348 11349 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11350 S.PDiag(diag) 11351 << DRE->getDecl() << OrigDecl->getLocation() 11352 << DRE->getSourceRange()); 11353 } 11354 }; 11355 11356 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11357 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11358 bool DirectInit) { 11359 // Parameters arguments are occassionially constructed with itself, 11360 // for instance, in recursive functions. Skip them. 11361 if (isa<ParmVarDecl>(OrigDecl)) 11362 return; 11363 11364 E = E->IgnoreParens(); 11365 11366 // Skip checking T a = a where T is not a record or reference type. 11367 // Doing so is a way to silence uninitialized warnings. 11368 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11369 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11370 if (ICE->getCastKind() == CK_LValueToRValue) 11371 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11372 if (DRE->getDecl() == OrigDecl) 11373 return; 11374 11375 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11376 } 11377 } // end anonymous namespace 11378 11379 namespace { 11380 // Simple wrapper to add the name of a variable or (if no variable is 11381 // available) a DeclarationName into a diagnostic. 11382 struct VarDeclOrName { 11383 VarDecl *VDecl; 11384 DeclarationName Name; 11385 11386 friend const Sema::SemaDiagnosticBuilder & 11387 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11388 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11389 } 11390 }; 11391 } // end anonymous namespace 11392 11393 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11394 DeclarationName Name, QualType Type, 11395 TypeSourceInfo *TSI, 11396 SourceRange Range, bool DirectInit, 11397 Expr *Init) { 11398 bool IsInitCapture = !VDecl; 11399 assert((!VDecl || !VDecl->isInitCapture()) && 11400 "init captures are expected to be deduced prior to initialization"); 11401 11402 VarDeclOrName VN{VDecl, Name}; 11403 11404 DeducedType *Deduced = Type->getContainedDeducedType(); 11405 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11406 11407 // C++11 [dcl.spec.auto]p3 11408 if (!Init) { 11409 assert(VDecl && "no init for init capture deduction?"); 11410 11411 // Except for class argument deduction, and then for an initializing 11412 // declaration only, i.e. no static at class scope or extern. 11413 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11414 VDecl->hasExternalStorage() || 11415 VDecl->isStaticDataMember()) { 11416 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11417 << VDecl->getDeclName() << Type; 11418 return QualType(); 11419 } 11420 } 11421 11422 ArrayRef<Expr*> DeduceInits; 11423 if (Init) 11424 DeduceInits = Init; 11425 11426 if (DirectInit) { 11427 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11428 DeduceInits = PL->exprs(); 11429 } 11430 11431 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11432 assert(VDecl && "non-auto type for init capture deduction?"); 11433 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11434 InitializationKind Kind = InitializationKind::CreateForInit( 11435 VDecl->getLocation(), DirectInit, Init); 11436 // FIXME: Initialization should not be taking a mutable list of inits. 11437 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11438 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11439 InitsCopy); 11440 } 11441 11442 if (DirectInit) { 11443 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11444 DeduceInits = IL->inits(); 11445 } 11446 11447 // Deduction only works if we have exactly one source expression. 11448 if (DeduceInits.empty()) { 11449 // It isn't possible to write this directly, but it is possible to 11450 // end up in this situation with "auto x(some_pack...);" 11451 Diag(Init->getBeginLoc(), IsInitCapture 11452 ? diag::err_init_capture_no_expression 11453 : diag::err_auto_var_init_no_expression) 11454 << VN << Type << Range; 11455 return QualType(); 11456 } 11457 11458 if (DeduceInits.size() > 1) { 11459 Diag(DeduceInits[1]->getBeginLoc(), 11460 IsInitCapture ? diag::err_init_capture_multiple_expressions 11461 : diag::err_auto_var_init_multiple_expressions) 11462 << VN << Type << Range; 11463 return QualType(); 11464 } 11465 11466 Expr *DeduceInit = DeduceInits[0]; 11467 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11468 Diag(Init->getBeginLoc(), IsInitCapture 11469 ? diag::err_init_capture_paren_braces 11470 : diag::err_auto_var_init_paren_braces) 11471 << isa<InitListExpr>(Init) << VN << Type << Range; 11472 return QualType(); 11473 } 11474 11475 // Expressions default to 'id' when we're in a debugger. 11476 bool DefaultedAnyToId = false; 11477 if (getLangOpts().DebuggerCastResultToId && 11478 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11479 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11480 if (Result.isInvalid()) { 11481 return QualType(); 11482 } 11483 Init = Result.get(); 11484 DefaultedAnyToId = true; 11485 } 11486 11487 // C++ [dcl.decomp]p1: 11488 // If the assignment-expression [...] has array type A and no ref-qualifier 11489 // is present, e has type cv A 11490 if (VDecl && isa<DecompositionDecl>(VDecl) && 11491 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11492 DeduceInit->getType()->isConstantArrayType()) 11493 return Context.getQualifiedType(DeduceInit->getType(), 11494 Type.getQualifiers()); 11495 11496 QualType DeducedType; 11497 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11498 if (!IsInitCapture) 11499 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11500 else if (isa<InitListExpr>(Init)) 11501 Diag(Range.getBegin(), 11502 diag::err_init_capture_deduction_failure_from_init_list) 11503 << VN 11504 << (DeduceInit->getType().isNull() ? TSI->getType() 11505 : DeduceInit->getType()) 11506 << DeduceInit->getSourceRange(); 11507 else 11508 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11509 << VN << TSI->getType() 11510 << (DeduceInit->getType().isNull() ? TSI->getType() 11511 : DeduceInit->getType()) 11512 << DeduceInit->getSourceRange(); 11513 } 11514 11515 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11516 // 'id' instead of a specific object type prevents most of our usual 11517 // checks. 11518 // We only want to warn outside of template instantiations, though: 11519 // inside a template, the 'id' could have come from a parameter. 11520 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11521 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11522 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11523 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11524 } 11525 11526 return DeducedType; 11527 } 11528 11529 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11530 Expr *Init) { 11531 assert(!Init || !Init->containsErrors()); 11532 QualType DeducedType = deduceVarTypeFromInitializer( 11533 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11534 VDecl->getSourceRange(), DirectInit, Init); 11535 if (DeducedType.isNull()) { 11536 VDecl->setInvalidDecl(); 11537 return true; 11538 } 11539 11540 VDecl->setType(DeducedType); 11541 assert(VDecl->isLinkageValid()); 11542 11543 // In ARC, infer lifetime. 11544 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11545 VDecl->setInvalidDecl(); 11546 11547 if (getLangOpts().OpenCL) 11548 deduceOpenCLAddressSpace(VDecl); 11549 11550 // If this is a redeclaration, check that the type we just deduced matches 11551 // the previously declared type. 11552 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11553 // We never need to merge the type, because we cannot form an incomplete 11554 // array of auto, nor deduce such a type. 11555 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11556 } 11557 11558 // Check the deduced type is valid for a variable declaration. 11559 CheckVariableDeclarationType(VDecl); 11560 return VDecl->isInvalidDecl(); 11561 } 11562 11563 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11564 SourceLocation Loc) { 11565 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11566 Init = EWC->getSubExpr(); 11567 11568 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11569 Init = CE->getSubExpr(); 11570 11571 QualType InitType = Init->getType(); 11572 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11573 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11574 "shouldn't be called if type doesn't have a non-trivial C struct"); 11575 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11576 for (auto I : ILE->inits()) { 11577 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11578 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11579 continue; 11580 SourceLocation SL = I->getExprLoc(); 11581 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11582 } 11583 return; 11584 } 11585 11586 if (isa<ImplicitValueInitExpr>(Init)) { 11587 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11588 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11589 NTCUK_Init); 11590 } else { 11591 // Assume all other explicit initializers involving copying some existing 11592 // object. 11593 // TODO: ignore any explicit initializers where we can guarantee 11594 // copy-elision. 11595 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11596 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11597 } 11598 } 11599 11600 namespace { 11601 11602 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11603 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11604 // in the source code or implicitly by the compiler if it is in a union 11605 // defined in a system header and has non-trivial ObjC ownership 11606 // qualifications. We don't want those fields to participate in determining 11607 // whether the containing union is non-trivial. 11608 return FD->hasAttr<UnavailableAttr>(); 11609 } 11610 11611 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11612 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11613 void> { 11614 using Super = 11615 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11616 void>; 11617 11618 DiagNonTrivalCUnionDefaultInitializeVisitor( 11619 QualType OrigTy, SourceLocation OrigLoc, 11620 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11621 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11622 11623 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11624 const FieldDecl *FD, bool InNonTrivialUnion) { 11625 if (const auto *AT = S.Context.getAsArrayType(QT)) 11626 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11627 InNonTrivialUnion); 11628 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11629 } 11630 11631 void visitARCStrong(QualType QT, const FieldDecl *FD, 11632 bool InNonTrivialUnion) { 11633 if (InNonTrivialUnion) 11634 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11635 << 1 << 0 << QT << FD->getName(); 11636 } 11637 11638 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11639 if (InNonTrivialUnion) 11640 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11641 << 1 << 0 << QT << FD->getName(); 11642 } 11643 11644 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11645 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11646 if (RD->isUnion()) { 11647 if (OrigLoc.isValid()) { 11648 bool IsUnion = false; 11649 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11650 IsUnion = OrigRD->isUnion(); 11651 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11652 << 0 << OrigTy << IsUnion << UseContext; 11653 // Reset OrigLoc so that this diagnostic is emitted only once. 11654 OrigLoc = SourceLocation(); 11655 } 11656 InNonTrivialUnion = true; 11657 } 11658 11659 if (InNonTrivialUnion) 11660 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11661 << 0 << 0 << QT.getUnqualifiedType() << ""; 11662 11663 for (const FieldDecl *FD : RD->fields()) 11664 if (!shouldIgnoreForRecordTriviality(FD)) 11665 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11666 } 11667 11668 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11669 11670 // The non-trivial C union type or the struct/union type that contains a 11671 // non-trivial C union. 11672 QualType OrigTy; 11673 SourceLocation OrigLoc; 11674 Sema::NonTrivialCUnionContext UseContext; 11675 Sema &S; 11676 }; 11677 11678 struct DiagNonTrivalCUnionDestructedTypeVisitor 11679 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11680 using Super = 11681 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11682 11683 DiagNonTrivalCUnionDestructedTypeVisitor( 11684 QualType OrigTy, SourceLocation OrigLoc, 11685 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11686 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11687 11688 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11689 const FieldDecl *FD, bool InNonTrivialUnion) { 11690 if (const auto *AT = S.Context.getAsArrayType(QT)) 11691 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11692 InNonTrivialUnion); 11693 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11694 } 11695 11696 void visitARCStrong(QualType QT, const FieldDecl *FD, 11697 bool InNonTrivialUnion) { 11698 if (InNonTrivialUnion) 11699 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11700 << 1 << 1 << QT << FD->getName(); 11701 } 11702 11703 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11704 if (InNonTrivialUnion) 11705 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11706 << 1 << 1 << QT << FD->getName(); 11707 } 11708 11709 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11710 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11711 if (RD->isUnion()) { 11712 if (OrigLoc.isValid()) { 11713 bool IsUnion = false; 11714 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11715 IsUnion = OrigRD->isUnion(); 11716 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11717 << 1 << OrigTy << IsUnion << UseContext; 11718 // Reset OrigLoc so that this diagnostic is emitted only once. 11719 OrigLoc = SourceLocation(); 11720 } 11721 InNonTrivialUnion = true; 11722 } 11723 11724 if (InNonTrivialUnion) 11725 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11726 << 0 << 1 << QT.getUnqualifiedType() << ""; 11727 11728 for (const FieldDecl *FD : RD->fields()) 11729 if (!shouldIgnoreForRecordTriviality(FD)) 11730 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11731 } 11732 11733 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11734 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11735 bool InNonTrivialUnion) {} 11736 11737 // The non-trivial C union type or the struct/union type that contains a 11738 // non-trivial C union. 11739 QualType OrigTy; 11740 SourceLocation OrigLoc; 11741 Sema::NonTrivialCUnionContext UseContext; 11742 Sema &S; 11743 }; 11744 11745 struct DiagNonTrivalCUnionCopyVisitor 11746 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11747 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11748 11749 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11750 Sema::NonTrivialCUnionContext UseContext, 11751 Sema &S) 11752 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11753 11754 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11755 const FieldDecl *FD, bool InNonTrivialUnion) { 11756 if (const auto *AT = S.Context.getAsArrayType(QT)) 11757 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11758 InNonTrivialUnion); 11759 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11760 } 11761 11762 void visitARCStrong(QualType QT, const FieldDecl *FD, 11763 bool InNonTrivialUnion) { 11764 if (InNonTrivialUnion) 11765 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11766 << 1 << 2 << QT << FD->getName(); 11767 } 11768 11769 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11770 if (InNonTrivialUnion) 11771 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11772 << 1 << 2 << QT << FD->getName(); 11773 } 11774 11775 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11776 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11777 if (RD->isUnion()) { 11778 if (OrigLoc.isValid()) { 11779 bool IsUnion = false; 11780 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11781 IsUnion = OrigRD->isUnion(); 11782 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11783 << 2 << OrigTy << IsUnion << UseContext; 11784 // Reset OrigLoc so that this diagnostic is emitted only once. 11785 OrigLoc = SourceLocation(); 11786 } 11787 InNonTrivialUnion = true; 11788 } 11789 11790 if (InNonTrivialUnion) 11791 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11792 << 0 << 2 << QT.getUnqualifiedType() << ""; 11793 11794 for (const FieldDecl *FD : RD->fields()) 11795 if (!shouldIgnoreForRecordTriviality(FD)) 11796 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11797 } 11798 11799 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11800 const FieldDecl *FD, bool InNonTrivialUnion) {} 11801 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11802 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11803 bool InNonTrivialUnion) {} 11804 11805 // The non-trivial C union type or the struct/union type that contains a 11806 // non-trivial C union. 11807 QualType OrigTy; 11808 SourceLocation OrigLoc; 11809 Sema::NonTrivialCUnionContext UseContext; 11810 Sema &S; 11811 }; 11812 11813 } // namespace 11814 11815 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11816 NonTrivialCUnionContext UseContext, 11817 unsigned NonTrivialKind) { 11818 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11819 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11820 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11821 "shouldn't be called if type doesn't have a non-trivial C union"); 11822 11823 if ((NonTrivialKind & NTCUK_Init) && 11824 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11825 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11826 .visit(QT, nullptr, false); 11827 if ((NonTrivialKind & NTCUK_Destruct) && 11828 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11829 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11830 .visit(QT, nullptr, false); 11831 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11832 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11833 .visit(QT, nullptr, false); 11834 } 11835 11836 /// AddInitializerToDecl - Adds the initializer Init to the 11837 /// declaration dcl. If DirectInit is true, this is C++ direct 11838 /// initialization rather than copy initialization. 11839 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11840 // If there is no declaration, there was an error parsing it. Just ignore 11841 // the initializer. 11842 if (!RealDecl || RealDecl->isInvalidDecl()) { 11843 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11844 return; 11845 } 11846 11847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11848 // Pure-specifiers are handled in ActOnPureSpecifier. 11849 Diag(Method->getLocation(), diag::err_member_function_initialization) 11850 << Method->getDeclName() << Init->getSourceRange(); 11851 Method->setInvalidDecl(); 11852 return; 11853 } 11854 11855 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11856 if (!VDecl) { 11857 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11858 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11859 RealDecl->setInvalidDecl(); 11860 return; 11861 } 11862 11863 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11864 if (VDecl->getType()->isUndeducedType()) { 11865 // Attempt typo correction early so that the type of the init expression can 11866 // be deduced based on the chosen correction if the original init contains a 11867 // TypoExpr. 11868 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11869 if (!Res.isUsable()) { 11870 // There are unresolved typos in Init, just drop them. 11871 // FIXME: improve the recovery strategy to preserve the Init. 11872 RealDecl->setInvalidDecl(); 11873 return; 11874 } 11875 if (Res.get()->containsErrors()) { 11876 // Invalidate the decl as we don't know the type for recovery-expr yet. 11877 RealDecl->setInvalidDecl(); 11878 VDecl->setInit(Res.get()); 11879 return; 11880 } 11881 Init = Res.get(); 11882 11883 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11884 return; 11885 } 11886 11887 // dllimport cannot be used on variable definitions. 11888 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11889 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11890 VDecl->setInvalidDecl(); 11891 return; 11892 } 11893 11894 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11895 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11896 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11897 VDecl->setInvalidDecl(); 11898 return; 11899 } 11900 11901 if (!VDecl->getType()->isDependentType()) { 11902 // A definition must end up with a complete type, which means it must be 11903 // complete with the restriction that an array type might be completed by 11904 // the initializer; note that later code assumes this restriction. 11905 QualType BaseDeclType = VDecl->getType(); 11906 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11907 BaseDeclType = Array->getElementType(); 11908 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11909 diag::err_typecheck_decl_incomplete_type)) { 11910 RealDecl->setInvalidDecl(); 11911 return; 11912 } 11913 11914 // The variable can not have an abstract class type. 11915 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11916 diag::err_abstract_type_in_decl, 11917 AbstractVariableType)) 11918 VDecl->setInvalidDecl(); 11919 } 11920 11921 // If adding the initializer will turn this declaration into a definition, 11922 // and we already have a definition for this variable, diagnose or otherwise 11923 // handle the situation. 11924 VarDecl *Def; 11925 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11926 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11927 !VDecl->isThisDeclarationADemotedDefinition() && 11928 checkVarDeclRedefinition(Def, VDecl)) 11929 return; 11930 11931 if (getLangOpts().CPlusPlus) { 11932 // C++ [class.static.data]p4 11933 // If a static data member is of const integral or const 11934 // enumeration type, its declaration in the class definition can 11935 // specify a constant-initializer which shall be an integral 11936 // constant expression (5.19). In that case, the member can appear 11937 // in integral constant expressions. The member shall still be 11938 // defined in a namespace scope if it is used in the program and the 11939 // namespace scope definition shall not contain an initializer. 11940 // 11941 // We already performed a redefinition check above, but for static 11942 // data members we also need to check whether there was an in-class 11943 // declaration with an initializer. 11944 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11945 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11946 << VDecl->getDeclName(); 11947 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11948 diag::note_previous_initializer) 11949 << 0; 11950 return; 11951 } 11952 11953 if (VDecl->hasLocalStorage()) 11954 setFunctionHasBranchProtectedScope(); 11955 11956 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11957 VDecl->setInvalidDecl(); 11958 return; 11959 } 11960 } 11961 11962 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11963 // a kernel function cannot be initialized." 11964 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11965 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11966 VDecl->setInvalidDecl(); 11967 return; 11968 } 11969 11970 // The LoaderUninitialized attribute acts as a definition (of undef). 11971 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11972 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11973 VDecl->setInvalidDecl(); 11974 return; 11975 } 11976 11977 // Get the decls type and save a reference for later, since 11978 // CheckInitializerTypes may change it. 11979 QualType DclT = VDecl->getType(), SavT = DclT; 11980 11981 // Expressions default to 'id' when we're in a debugger 11982 // and we are assigning it to a variable of Objective-C pointer type. 11983 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11984 Init->getType() == Context.UnknownAnyTy) { 11985 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11986 if (Result.isInvalid()) { 11987 VDecl->setInvalidDecl(); 11988 return; 11989 } 11990 Init = Result.get(); 11991 } 11992 11993 // Perform the initialization. 11994 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11995 if (!VDecl->isInvalidDecl()) { 11996 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11997 InitializationKind Kind = InitializationKind::CreateForInit( 11998 VDecl->getLocation(), DirectInit, Init); 11999 12000 MultiExprArg Args = Init; 12001 if (CXXDirectInit) 12002 Args = MultiExprArg(CXXDirectInit->getExprs(), 12003 CXXDirectInit->getNumExprs()); 12004 12005 // Try to correct any TypoExprs in the initialization arguments. 12006 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12007 ExprResult Res = CorrectDelayedTyposInExpr( 12008 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 12009 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12010 return Init.Failed() ? ExprError() : E; 12011 }); 12012 if (Res.isInvalid()) { 12013 VDecl->setInvalidDecl(); 12014 } else if (Res.get() != Args[Idx]) { 12015 Args[Idx] = Res.get(); 12016 } 12017 } 12018 if (VDecl->isInvalidDecl()) 12019 return; 12020 12021 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12022 /*TopLevelOfInitList=*/false, 12023 /*TreatUnavailableAsInvalid=*/false); 12024 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12025 if (Result.isInvalid()) { 12026 // If the provied initializer fails to initialize the var decl, 12027 // we attach a recovery expr for better recovery. 12028 auto RecoveryExpr = 12029 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12030 if (RecoveryExpr.get()) 12031 VDecl->setInit(RecoveryExpr.get()); 12032 return; 12033 } 12034 12035 Init = Result.getAs<Expr>(); 12036 } 12037 12038 // Check for self-references within variable initializers. 12039 // Variables declared within a function/method body (except for references) 12040 // are handled by a dataflow analysis. 12041 // This is undefined behavior in C++, but valid in C. 12042 if (getLangOpts().CPlusPlus) { 12043 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12044 VDecl->getType()->isReferenceType()) { 12045 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12046 } 12047 } 12048 12049 // If the type changed, it means we had an incomplete type that was 12050 // completed by the initializer. For example: 12051 // int ary[] = { 1, 3, 5 }; 12052 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12053 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12054 VDecl->setType(DclT); 12055 12056 if (!VDecl->isInvalidDecl()) { 12057 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12058 12059 if (VDecl->hasAttr<BlocksAttr>()) 12060 checkRetainCycles(VDecl, Init); 12061 12062 // It is safe to assign a weak reference into a strong variable. 12063 // Although this code can still have problems: 12064 // id x = self.weakProp; 12065 // id y = self.weakProp; 12066 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12067 // paths through the function. This should be revisited if 12068 // -Wrepeated-use-of-weak is made flow-sensitive. 12069 if (FunctionScopeInfo *FSI = getCurFunction()) 12070 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12071 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12072 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12073 Init->getBeginLoc())) 12074 FSI->markSafeWeakUse(Init); 12075 } 12076 12077 // The initialization is usually a full-expression. 12078 // 12079 // FIXME: If this is a braced initialization of an aggregate, it is not 12080 // an expression, and each individual field initializer is a separate 12081 // full-expression. For instance, in: 12082 // 12083 // struct Temp { ~Temp(); }; 12084 // struct S { S(Temp); }; 12085 // struct T { S a, b; } t = { Temp(), Temp() } 12086 // 12087 // we should destroy the first Temp before constructing the second. 12088 ExprResult Result = 12089 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12090 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12091 if (Result.isInvalid()) { 12092 VDecl->setInvalidDecl(); 12093 return; 12094 } 12095 Init = Result.get(); 12096 12097 // Attach the initializer to the decl. 12098 VDecl->setInit(Init); 12099 12100 if (VDecl->isLocalVarDecl()) { 12101 // Don't check the initializer if the declaration is malformed. 12102 if (VDecl->isInvalidDecl()) { 12103 // do nothing 12104 12105 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12106 // This is true even in C++ for OpenCL. 12107 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12108 CheckForConstantInitializer(Init, DclT); 12109 12110 // Otherwise, C++ does not restrict the initializer. 12111 } else if (getLangOpts().CPlusPlus) { 12112 // do nothing 12113 12114 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12115 // static storage duration shall be constant expressions or string literals. 12116 } else if (VDecl->getStorageClass() == SC_Static) { 12117 CheckForConstantInitializer(Init, DclT); 12118 12119 // C89 is stricter than C99 for aggregate initializers. 12120 // C89 6.5.7p3: All the expressions [...] in an initializer list 12121 // for an object that has aggregate or union type shall be 12122 // constant expressions. 12123 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12124 isa<InitListExpr>(Init)) { 12125 const Expr *Culprit; 12126 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12127 Diag(Culprit->getExprLoc(), 12128 diag::ext_aggregate_init_not_constant) 12129 << Culprit->getSourceRange(); 12130 } 12131 } 12132 12133 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12134 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12135 if (VDecl->hasLocalStorage()) 12136 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12137 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12138 VDecl->getLexicalDeclContext()->isRecord()) { 12139 // This is an in-class initialization for a static data member, e.g., 12140 // 12141 // struct S { 12142 // static const int value = 17; 12143 // }; 12144 12145 // C++ [class.mem]p4: 12146 // A member-declarator can contain a constant-initializer only 12147 // if it declares a static member (9.4) of const integral or 12148 // const enumeration type, see 9.4.2. 12149 // 12150 // C++11 [class.static.data]p3: 12151 // If a non-volatile non-inline const static data member is of integral 12152 // or enumeration type, its declaration in the class definition can 12153 // specify a brace-or-equal-initializer in which every initializer-clause 12154 // that is an assignment-expression is a constant expression. A static 12155 // data member of literal type can be declared in the class definition 12156 // with the constexpr specifier; if so, its declaration shall specify a 12157 // brace-or-equal-initializer in which every initializer-clause that is 12158 // an assignment-expression is a constant expression. 12159 12160 // Do nothing on dependent types. 12161 if (DclT->isDependentType()) { 12162 12163 // Allow any 'static constexpr' members, whether or not they are of literal 12164 // type. We separately check that every constexpr variable is of literal 12165 // type. 12166 } else if (VDecl->isConstexpr()) { 12167 12168 // Require constness. 12169 } else if (!DclT.isConstQualified()) { 12170 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12171 << Init->getSourceRange(); 12172 VDecl->setInvalidDecl(); 12173 12174 // We allow integer constant expressions in all cases. 12175 } else if (DclT->isIntegralOrEnumerationType()) { 12176 // Check whether the expression is a constant expression. 12177 SourceLocation Loc; 12178 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12179 // In C++11, a non-constexpr const static data member with an 12180 // in-class initializer cannot be volatile. 12181 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12182 else if (Init->isValueDependent()) 12183 ; // Nothing to check. 12184 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12185 ; // Ok, it's an ICE! 12186 else if (Init->getType()->isScopedEnumeralType() && 12187 Init->isCXX11ConstantExpr(Context)) 12188 ; // Ok, it is a scoped-enum constant expression. 12189 else if (Init->isEvaluatable(Context)) { 12190 // If we can constant fold the initializer through heroics, accept it, 12191 // but report this as a use of an extension for -pedantic. 12192 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12193 << Init->getSourceRange(); 12194 } else { 12195 // Otherwise, this is some crazy unknown case. Report the issue at the 12196 // location provided by the isIntegerConstantExpr failed check. 12197 Diag(Loc, diag::err_in_class_initializer_non_constant) 12198 << Init->getSourceRange(); 12199 VDecl->setInvalidDecl(); 12200 } 12201 12202 // We allow foldable floating-point constants as an extension. 12203 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12204 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12205 // it anyway and provide a fixit to add the 'constexpr'. 12206 if (getLangOpts().CPlusPlus11) { 12207 Diag(VDecl->getLocation(), 12208 diag::ext_in_class_initializer_float_type_cxx11) 12209 << DclT << Init->getSourceRange(); 12210 Diag(VDecl->getBeginLoc(), 12211 diag::note_in_class_initializer_float_type_cxx11) 12212 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12213 } else { 12214 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12215 << DclT << Init->getSourceRange(); 12216 12217 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12218 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12219 << Init->getSourceRange(); 12220 VDecl->setInvalidDecl(); 12221 } 12222 } 12223 12224 // Suggest adding 'constexpr' in C++11 for literal types. 12225 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12226 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12227 << DclT << Init->getSourceRange() 12228 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12229 VDecl->setConstexpr(true); 12230 12231 } else { 12232 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12233 << DclT << Init->getSourceRange(); 12234 VDecl->setInvalidDecl(); 12235 } 12236 } else if (VDecl->isFileVarDecl()) { 12237 // In C, extern is typically used to avoid tentative definitions when 12238 // declaring variables in headers, but adding an intializer makes it a 12239 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12240 // In C++, extern is often used to give implictly static const variables 12241 // external linkage, so don't warn in that case. If selectany is present, 12242 // this might be header code intended for C and C++ inclusion, so apply the 12243 // C++ rules. 12244 if (VDecl->getStorageClass() == SC_Extern && 12245 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12246 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12247 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12248 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12249 Diag(VDecl->getLocation(), diag::warn_extern_init); 12250 12251 // In Microsoft C++ mode, a const variable defined in namespace scope has 12252 // external linkage by default if the variable is declared with 12253 // __declspec(dllexport). 12254 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12255 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12256 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12257 VDecl->setStorageClass(SC_Extern); 12258 12259 // C99 6.7.8p4. All file scoped initializers need to be constant. 12260 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12261 CheckForConstantInitializer(Init, DclT); 12262 } 12263 12264 QualType InitType = Init->getType(); 12265 if (!InitType.isNull() && 12266 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12267 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12268 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12269 12270 // We will represent direct-initialization similarly to copy-initialization: 12271 // int x(1); -as-> int x = 1; 12272 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12273 // 12274 // Clients that want to distinguish between the two forms, can check for 12275 // direct initializer using VarDecl::getInitStyle(). 12276 // A major benefit is that clients that don't particularly care about which 12277 // exactly form was it (like the CodeGen) can handle both cases without 12278 // special case code. 12279 12280 // C++ 8.5p11: 12281 // The form of initialization (using parentheses or '=') is generally 12282 // insignificant, but does matter when the entity being initialized has a 12283 // class type. 12284 if (CXXDirectInit) { 12285 assert(DirectInit && "Call-style initializer must be direct init."); 12286 VDecl->setInitStyle(VarDecl::CallInit); 12287 } else if (DirectInit) { 12288 // This must be list-initialization. No other way is direct-initialization. 12289 VDecl->setInitStyle(VarDecl::ListInit); 12290 } 12291 12292 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12293 DeclsToCheckForDeferredDiags.push_back(VDecl); 12294 CheckCompleteVariableDeclaration(VDecl); 12295 } 12296 12297 /// ActOnInitializerError - Given that there was an error parsing an 12298 /// initializer for the given declaration, try to return to some form 12299 /// of sanity. 12300 void Sema::ActOnInitializerError(Decl *D) { 12301 // Our main concern here is re-establishing invariants like "a 12302 // variable's type is either dependent or complete". 12303 if (!D || D->isInvalidDecl()) return; 12304 12305 VarDecl *VD = dyn_cast<VarDecl>(D); 12306 if (!VD) return; 12307 12308 // Bindings are not usable if we can't make sense of the initializer. 12309 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12310 for (auto *BD : DD->bindings()) 12311 BD->setInvalidDecl(); 12312 12313 // Auto types are meaningless if we can't make sense of the initializer. 12314 if (ParsingInitForAutoVars.count(D)) { 12315 D->setInvalidDecl(); 12316 return; 12317 } 12318 12319 QualType Ty = VD->getType(); 12320 if (Ty->isDependentType()) return; 12321 12322 // Require a complete type. 12323 if (RequireCompleteType(VD->getLocation(), 12324 Context.getBaseElementType(Ty), 12325 diag::err_typecheck_decl_incomplete_type)) { 12326 VD->setInvalidDecl(); 12327 return; 12328 } 12329 12330 // Require a non-abstract type. 12331 if (RequireNonAbstractType(VD->getLocation(), Ty, 12332 diag::err_abstract_type_in_decl, 12333 AbstractVariableType)) { 12334 VD->setInvalidDecl(); 12335 return; 12336 } 12337 12338 // Don't bother complaining about constructors or destructors, 12339 // though. 12340 } 12341 12342 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12343 // If there is no declaration, there was an error parsing it. Just ignore it. 12344 if (!RealDecl) 12345 return; 12346 12347 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12348 QualType Type = Var->getType(); 12349 12350 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12351 if (isa<DecompositionDecl>(RealDecl)) { 12352 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12353 Var->setInvalidDecl(); 12354 return; 12355 } 12356 12357 if (Type->isUndeducedType() && 12358 DeduceVariableDeclarationType(Var, false, nullptr)) 12359 return; 12360 12361 // C++11 [class.static.data]p3: A static data member can be declared with 12362 // the constexpr specifier; if so, its declaration shall specify 12363 // a brace-or-equal-initializer. 12364 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12365 // the definition of a variable [...] or the declaration of a static data 12366 // member. 12367 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12368 !Var->isThisDeclarationADemotedDefinition()) { 12369 if (Var->isStaticDataMember()) { 12370 // C++1z removes the relevant rule; the in-class declaration is always 12371 // a definition there. 12372 if (!getLangOpts().CPlusPlus17 && 12373 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12374 Diag(Var->getLocation(), 12375 diag::err_constexpr_static_mem_var_requires_init) 12376 << Var->getDeclName(); 12377 Var->setInvalidDecl(); 12378 return; 12379 } 12380 } else { 12381 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12382 Var->setInvalidDecl(); 12383 return; 12384 } 12385 } 12386 12387 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12388 // be initialized. 12389 if (!Var->isInvalidDecl() && 12390 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12391 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12392 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12393 Var->setInvalidDecl(); 12394 return; 12395 } 12396 12397 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12398 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12399 if (!RD->hasTrivialDefaultConstructor()) { 12400 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12401 Var->setInvalidDecl(); 12402 return; 12403 } 12404 } 12405 if (Var->getStorageClass() == SC_Extern) { 12406 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12407 << Var; 12408 Var->setInvalidDecl(); 12409 return; 12410 } 12411 } 12412 12413 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12414 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12415 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12416 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12417 NTCUC_DefaultInitializedObject, NTCUK_Init); 12418 12419 12420 switch (DefKind) { 12421 case VarDecl::Definition: 12422 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12423 break; 12424 12425 // We have an out-of-line definition of a static data member 12426 // that has an in-class initializer, so we type-check this like 12427 // a declaration. 12428 // 12429 LLVM_FALLTHROUGH; 12430 12431 case VarDecl::DeclarationOnly: 12432 // It's only a declaration. 12433 12434 // Block scope. C99 6.7p7: If an identifier for an object is 12435 // declared with no linkage (C99 6.2.2p6), the type for the 12436 // object shall be complete. 12437 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12438 !Var->hasLinkage() && !Var->isInvalidDecl() && 12439 RequireCompleteType(Var->getLocation(), Type, 12440 diag::err_typecheck_decl_incomplete_type)) 12441 Var->setInvalidDecl(); 12442 12443 // Make sure that the type is not abstract. 12444 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12445 RequireNonAbstractType(Var->getLocation(), Type, 12446 diag::err_abstract_type_in_decl, 12447 AbstractVariableType)) 12448 Var->setInvalidDecl(); 12449 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12450 Var->getStorageClass() == SC_PrivateExtern) { 12451 Diag(Var->getLocation(), diag::warn_private_extern); 12452 Diag(Var->getLocation(), diag::note_private_extern); 12453 } 12454 12455 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12456 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12457 ExternalDeclarations.push_back(Var); 12458 12459 return; 12460 12461 case VarDecl::TentativeDefinition: 12462 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12463 // object that has file scope without an initializer, and without a 12464 // storage-class specifier or with the storage-class specifier "static", 12465 // constitutes a tentative definition. Note: A tentative definition with 12466 // external linkage is valid (C99 6.2.2p5). 12467 if (!Var->isInvalidDecl()) { 12468 if (const IncompleteArrayType *ArrayT 12469 = Context.getAsIncompleteArrayType(Type)) { 12470 if (RequireCompleteSizedType( 12471 Var->getLocation(), ArrayT->getElementType(), 12472 diag::err_array_incomplete_or_sizeless_type)) 12473 Var->setInvalidDecl(); 12474 } else if (Var->getStorageClass() == SC_Static) { 12475 // C99 6.9.2p3: If the declaration of an identifier for an object is 12476 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12477 // declared type shall not be an incomplete type. 12478 // NOTE: code such as the following 12479 // static struct s; 12480 // struct s { int a; }; 12481 // is accepted by gcc. Hence here we issue a warning instead of 12482 // an error and we do not invalidate the static declaration. 12483 // NOTE: to avoid multiple warnings, only check the first declaration. 12484 if (Var->isFirstDecl()) 12485 RequireCompleteType(Var->getLocation(), Type, 12486 diag::ext_typecheck_decl_incomplete_type); 12487 } 12488 } 12489 12490 // Record the tentative definition; we're done. 12491 if (!Var->isInvalidDecl()) 12492 TentativeDefinitions.push_back(Var); 12493 return; 12494 } 12495 12496 // Provide a specific diagnostic for uninitialized variable 12497 // definitions with incomplete array type. 12498 if (Type->isIncompleteArrayType()) { 12499 Diag(Var->getLocation(), 12500 diag::err_typecheck_incomplete_array_needs_initializer); 12501 Var->setInvalidDecl(); 12502 return; 12503 } 12504 12505 // Provide a specific diagnostic for uninitialized variable 12506 // definitions with reference type. 12507 if (Type->isReferenceType()) { 12508 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12509 << Var->getDeclName() 12510 << SourceRange(Var->getLocation(), Var->getLocation()); 12511 Var->setInvalidDecl(); 12512 return; 12513 } 12514 12515 // Do not attempt to type-check the default initializer for a 12516 // variable with dependent type. 12517 if (Type->isDependentType()) 12518 return; 12519 12520 if (Var->isInvalidDecl()) 12521 return; 12522 12523 if (!Var->hasAttr<AliasAttr>()) { 12524 if (RequireCompleteType(Var->getLocation(), 12525 Context.getBaseElementType(Type), 12526 diag::err_typecheck_decl_incomplete_type)) { 12527 Var->setInvalidDecl(); 12528 return; 12529 } 12530 } else { 12531 return; 12532 } 12533 12534 // The variable can not have an abstract class type. 12535 if (RequireNonAbstractType(Var->getLocation(), Type, 12536 diag::err_abstract_type_in_decl, 12537 AbstractVariableType)) { 12538 Var->setInvalidDecl(); 12539 return; 12540 } 12541 12542 // Check for jumps past the implicit initializer. C++0x 12543 // clarifies that this applies to a "variable with automatic 12544 // storage duration", not a "local variable". 12545 // C++11 [stmt.dcl]p3 12546 // A program that jumps from a point where a variable with automatic 12547 // storage duration is not in scope to a point where it is in scope is 12548 // ill-formed unless the variable has scalar type, class type with a 12549 // trivial default constructor and a trivial destructor, a cv-qualified 12550 // version of one of these types, or an array of one of the preceding 12551 // types and is declared without an initializer. 12552 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12553 if (const RecordType *Record 12554 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12555 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12556 // Mark the function (if we're in one) for further checking even if the 12557 // looser rules of C++11 do not require such checks, so that we can 12558 // diagnose incompatibilities with C++98. 12559 if (!CXXRecord->isPOD()) 12560 setFunctionHasBranchProtectedScope(); 12561 } 12562 } 12563 // In OpenCL, we can't initialize objects in the __local address space, 12564 // even implicitly, so don't synthesize an implicit initializer. 12565 if (getLangOpts().OpenCL && 12566 Var->getType().getAddressSpace() == LangAS::opencl_local) 12567 return; 12568 // C++03 [dcl.init]p9: 12569 // If no initializer is specified for an object, and the 12570 // object is of (possibly cv-qualified) non-POD class type (or 12571 // array thereof), the object shall be default-initialized; if 12572 // the object is of const-qualified type, the underlying class 12573 // type shall have a user-declared default 12574 // constructor. Otherwise, if no initializer is specified for 12575 // a non- static object, the object and its subobjects, if 12576 // any, have an indeterminate initial value); if the object 12577 // or any of its subobjects are of const-qualified type, the 12578 // program is ill-formed. 12579 // C++0x [dcl.init]p11: 12580 // If no initializer is specified for an object, the object is 12581 // default-initialized; [...]. 12582 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12583 InitializationKind Kind 12584 = InitializationKind::CreateDefault(Var->getLocation()); 12585 12586 InitializationSequence InitSeq(*this, Entity, Kind, None); 12587 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12588 12589 if (Init.get()) { 12590 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12591 // This is important for template substitution. 12592 Var->setInitStyle(VarDecl::CallInit); 12593 } else if (Init.isInvalid()) { 12594 // If default-init fails, attach a recovery-expr initializer to track 12595 // that initialization was attempted and failed. 12596 auto RecoveryExpr = 12597 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12598 if (RecoveryExpr.get()) 12599 Var->setInit(RecoveryExpr.get()); 12600 } 12601 12602 CheckCompleteVariableDeclaration(Var); 12603 } 12604 } 12605 12606 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12607 // If there is no declaration, there was an error parsing it. Ignore it. 12608 if (!D) 12609 return; 12610 12611 VarDecl *VD = dyn_cast<VarDecl>(D); 12612 if (!VD) { 12613 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12614 D->setInvalidDecl(); 12615 return; 12616 } 12617 12618 VD->setCXXForRangeDecl(true); 12619 12620 // for-range-declaration cannot be given a storage class specifier. 12621 int Error = -1; 12622 switch (VD->getStorageClass()) { 12623 case SC_None: 12624 break; 12625 case SC_Extern: 12626 Error = 0; 12627 break; 12628 case SC_Static: 12629 Error = 1; 12630 break; 12631 case SC_PrivateExtern: 12632 Error = 2; 12633 break; 12634 case SC_Auto: 12635 Error = 3; 12636 break; 12637 case SC_Register: 12638 Error = 4; 12639 break; 12640 } 12641 if (Error != -1) { 12642 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12643 << VD->getDeclName() << Error; 12644 D->setInvalidDecl(); 12645 } 12646 } 12647 12648 StmtResult 12649 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12650 IdentifierInfo *Ident, 12651 ParsedAttributes &Attrs, 12652 SourceLocation AttrEnd) { 12653 // C++1y [stmt.iter]p1: 12654 // A range-based for statement of the form 12655 // for ( for-range-identifier : for-range-initializer ) statement 12656 // is equivalent to 12657 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12658 DeclSpec DS(Attrs.getPool().getFactory()); 12659 12660 const char *PrevSpec; 12661 unsigned DiagID; 12662 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12663 getPrintingPolicy()); 12664 12665 Declarator D(DS, DeclaratorContext::ForContext); 12666 D.SetIdentifier(Ident, IdentLoc); 12667 D.takeAttributes(Attrs, AttrEnd); 12668 12669 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12670 IdentLoc); 12671 Decl *Var = ActOnDeclarator(S, D); 12672 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12673 FinalizeDeclaration(Var); 12674 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12675 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12676 } 12677 12678 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12679 if (var->isInvalidDecl()) return; 12680 12681 if (getLangOpts().OpenCL) { 12682 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12683 // initialiser 12684 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12685 !var->hasInit()) { 12686 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12687 << 1 /*Init*/; 12688 var->setInvalidDecl(); 12689 return; 12690 } 12691 } 12692 12693 // In Objective-C, don't allow jumps past the implicit initialization of a 12694 // local retaining variable. 12695 if (getLangOpts().ObjC && 12696 var->hasLocalStorage()) { 12697 switch (var->getType().getObjCLifetime()) { 12698 case Qualifiers::OCL_None: 12699 case Qualifiers::OCL_ExplicitNone: 12700 case Qualifiers::OCL_Autoreleasing: 12701 break; 12702 12703 case Qualifiers::OCL_Weak: 12704 case Qualifiers::OCL_Strong: 12705 setFunctionHasBranchProtectedScope(); 12706 break; 12707 } 12708 } 12709 12710 if (var->hasLocalStorage() && 12711 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12712 setFunctionHasBranchProtectedScope(); 12713 12714 // Warn about externally-visible variables being defined without a 12715 // prior declaration. We only want to do this for global 12716 // declarations, but we also specifically need to avoid doing it for 12717 // class members because the linkage of an anonymous class can 12718 // change if it's later given a typedef name. 12719 if (var->isThisDeclarationADefinition() && 12720 var->getDeclContext()->getRedeclContext()->isFileContext() && 12721 var->isExternallyVisible() && var->hasLinkage() && 12722 !var->isInline() && !var->getDescribedVarTemplate() && 12723 !isa<VarTemplatePartialSpecializationDecl>(var) && 12724 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12725 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12726 var->getLocation())) { 12727 // Find a previous declaration that's not a definition. 12728 VarDecl *prev = var->getPreviousDecl(); 12729 while (prev && prev->isThisDeclarationADefinition()) 12730 prev = prev->getPreviousDecl(); 12731 12732 if (!prev) { 12733 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12734 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12735 << /* variable */ 0; 12736 } 12737 } 12738 12739 // Cache the result of checking for constant initialization. 12740 Optional<bool> CacheHasConstInit; 12741 const Expr *CacheCulprit = nullptr; 12742 auto checkConstInit = [&]() mutable { 12743 if (!CacheHasConstInit) 12744 CacheHasConstInit = var->getInit()->isConstantInitializer( 12745 Context, var->getType()->isReferenceType(), &CacheCulprit); 12746 return *CacheHasConstInit; 12747 }; 12748 12749 if (var->getTLSKind() == VarDecl::TLS_Static) { 12750 if (var->getType().isDestructedType()) { 12751 // GNU C++98 edits for __thread, [basic.start.term]p3: 12752 // The type of an object with thread storage duration shall not 12753 // have a non-trivial destructor. 12754 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12755 if (getLangOpts().CPlusPlus11) 12756 Diag(var->getLocation(), diag::note_use_thread_local); 12757 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12758 if (!checkConstInit()) { 12759 // GNU C++98 edits for __thread, [basic.start.init]p4: 12760 // An object of thread storage duration shall not require dynamic 12761 // initialization. 12762 // FIXME: Need strict checking here. 12763 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12764 << CacheCulprit->getSourceRange(); 12765 if (getLangOpts().CPlusPlus11) 12766 Diag(var->getLocation(), diag::note_use_thread_local); 12767 } 12768 } 12769 } 12770 12771 // Apply section attributes and pragmas to global variables. 12772 bool GlobalStorage = var->hasGlobalStorage(); 12773 if (GlobalStorage && var->isThisDeclarationADefinition() && 12774 !inTemplateInstantiation()) { 12775 PragmaStack<StringLiteral *> *Stack = nullptr; 12776 int SectionFlags = ASTContext::PSF_Read; 12777 if (var->getType().isConstQualified()) 12778 Stack = &ConstSegStack; 12779 else if (!var->getInit()) { 12780 Stack = &BSSSegStack; 12781 SectionFlags |= ASTContext::PSF_Write; 12782 } else { 12783 Stack = &DataSegStack; 12784 SectionFlags |= ASTContext::PSF_Write; 12785 } 12786 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12787 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12788 SectionFlags |= ASTContext::PSF_Implicit; 12789 UnifySection(SA->getName(), SectionFlags, var); 12790 } else if (Stack->CurrentValue) { 12791 SectionFlags |= ASTContext::PSF_Implicit; 12792 auto SectionName = Stack->CurrentValue->getString(); 12793 var->addAttr(SectionAttr::CreateImplicit( 12794 Context, SectionName, Stack->CurrentPragmaLocation, 12795 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12796 if (UnifySection(SectionName, SectionFlags, var)) 12797 var->dropAttr<SectionAttr>(); 12798 } 12799 12800 // Apply the init_seg attribute if this has an initializer. If the 12801 // initializer turns out to not be dynamic, we'll end up ignoring this 12802 // attribute. 12803 if (CurInitSeg && var->getInit()) 12804 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12805 CurInitSegLoc, 12806 AttributeCommonInfo::AS_Pragma)); 12807 } 12808 12809 // All the following checks are C++ only. 12810 if (!getLangOpts().CPlusPlus) { 12811 // If this variable must be emitted, add it as an initializer for the 12812 // current module. 12813 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12814 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12815 return; 12816 } 12817 12818 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12819 CheckCompleteDecompositionDeclaration(DD); 12820 12821 QualType type = var->getType(); 12822 if (type->isDependentType()) return; 12823 12824 if (var->hasAttr<BlocksAttr>()) 12825 getCurFunction()->addByrefBlockVar(var); 12826 12827 Expr *Init = var->getInit(); 12828 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12829 QualType baseType = Context.getBaseElementType(type); 12830 12831 if (Init && !Init->isValueDependent()) { 12832 if (var->isConstexpr()) { 12833 SmallVector<PartialDiagnosticAt, 8> Notes; 12834 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12835 SourceLocation DiagLoc = var->getLocation(); 12836 // If the note doesn't add any useful information other than a source 12837 // location, fold it into the primary diagnostic. 12838 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12839 diag::note_invalid_subexpr_in_const_expr) { 12840 DiagLoc = Notes[0].first; 12841 Notes.clear(); 12842 } 12843 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12844 << var << Init->getSourceRange(); 12845 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12846 Diag(Notes[I].first, Notes[I].second); 12847 } 12848 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12849 // Check whether the initializer of a const variable of integral or 12850 // enumeration type is an ICE now, since we can't tell whether it was 12851 // initialized by a constant expression if we check later. 12852 var->checkInitIsICE(); 12853 } 12854 12855 // Don't emit further diagnostics about constexpr globals since they 12856 // were just diagnosed. 12857 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12858 // FIXME: Need strict checking in C++03 here. 12859 bool DiagErr = getLangOpts().CPlusPlus11 12860 ? !var->checkInitIsICE() : !checkConstInit(); 12861 if (DiagErr) { 12862 auto *Attr = var->getAttr<ConstInitAttr>(); 12863 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12864 << Init->getSourceRange(); 12865 Diag(Attr->getLocation(), 12866 diag::note_declared_required_constant_init_here) 12867 << Attr->getRange() << Attr->isConstinit(); 12868 if (getLangOpts().CPlusPlus11) { 12869 APValue Value; 12870 SmallVector<PartialDiagnosticAt, 8> Notes; 12871 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12872 for (auto &it : Notes) 12873 Diag(it.first, it.second); 12874 } else { 12875 Diag(CacheCulprit->getExprLoc(), 12876 diag::note_invalid_subexpr_in_const_expr) 12877 << CacheCulprit->getSourceRange(); 12878 } 12879 } 12880 } 12881 else if (!var->isConstexpr() && IsGlobal && 12882 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12883 var->getLocation())) { 12884 // Warn about globals which don't have a constant initializer. Don't 12885 // warn about globals with a non-trivial destructor because we already 12886 // warned about them. 12887 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12888 if (!(RD && !RD->hasTrivialDestructor())) { 12889 if (!checkConstInit()) 12890 Diag(var->getLocation(), diag::warn_global_constructor) 12891 << Init->getSourceRange(); 12892 } 12893 } 12894 } 12895 12896 // Require the destructor. 12897 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12898 FinalizeVarWithDestructor(var, recordType); 12899 12900 // If this variable must be emitted, add it as an initializer for the current 12901 // module. 12902 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12903 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12904 } 12905 12906 /// Determines if a variable's alignment is dependent. 12907 static bool hasDependentAlignment(VarDecl *VD) { 12908 if (VD->getType()->isDependentType()) 12909 return true; 12910 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12911 if (I->isAlignmentDependent()) 12912 return true; 12913 return false; 12914 } 12915 12916 /// Check if VD needs to be dllexport/dllimport due to being in a 12917 /// dllexport/import function. 12918 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12919 assert(VD->isStaticLocal()); 12920 12921 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12922 12923 // Find outermost function when VD is in lambda function. 12924 while (FD && !getDLLAttr(FD) && 12925 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12926 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12927 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12928 } 12929 12930 if (!FD) 12931 return; 12932 12933 // Static locals inherit dll attributes from their function. 12934 if (Attr *A = getDLLAttr(FD)) { 12935 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12936 NewAttr->setInherited(true); 12937 VD->addAttr(NewAttr); 12938 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12939 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12940 NewAttr->setInherited(true); 12941 VD->addAttr(NewAttr); 12942 12943 // Export this function to enforce exporting this static variable even 12944 // if it is not used in this compilation unit. 12945 if (!FD->hasAttr<DLLExportAttr>()) 12946 FD->addAttr(NewAttr); 12947 12948 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12949 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12950 NewAttr->setInherited(true); 12951 VD->addAttr(NewAttr); 12952 } 12953 } 12954 12955 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12956 /// any semantic actions necessary after any initializer has been attached. 12957 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12958 // Note that we are no longer parsing the initializer for this declaration. 12959 ParsingInitForAutoVars.erase(ThisDecl); 12960 12961 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12962 if (!VD) 12963 return; 12964 12965 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12966 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12967 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12968 if (PragmaClangBSSSection.Valid) 12969 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12970 Context, PragmaClangBSSSection.SectionName, 12971 PragmaClangBSSSection.PragmaLocation, 12972 AttributeCommonInfo::AS_Pragma)); 12973 if (PragmaClangDataSection.Valid) 12974 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12975 Context, PragmaClangDataSection.SectionName, 12976 PragmaClangDataSection.PragmaLocation, 12977 AttributeCommonInfo::AS_Pragma)); 12978 if (PragmaClangRodataSection.Valid) 12979 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12980 Context, PragmaClangRodataSection.SectionName, 12981 PragmaClangRodataSection.PragmaLocation, 12982 AttributeCommonInfo::AS_Pragma)); 12983 if (PragmaClangRelroSection.Valid) 12984 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12985 Context, PragmaClangRelroSection.SectionName, 12986 PragmaClangRelroSection.PragmaLocation, 12987 AttributeCommonInfo::AS_Pragma)); 12988 } 12989 12990 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12991 for (auto *BD : DD->bindings()) { 12992 FinalizeDeclaration(BD); 12993 } 12994 } 12995 12996 checkAttributesAfterMerging(*this, *VD); 12997 12998 // Perform TLS alignment check here after attributes attached to the variable 12999 // which may affect the alignment have been processed. Only perform the check 13000 // if the target has a maximum TLS alignment (zero means no constraints). 13001 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13002 // Protect the check so that it's not performed on dependent types and 13003 // dependent alignments (we can't determine the alignment in that case). 13004 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13005 !VD->isInvalidDecl()) { 13006 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13007 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13008 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13009 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13010 << (unsigned)MaxAlignChars.getQuantity(); 13011 } 13012 } 13013 } 13014 13015 if (VD->isStaticLocal()) { 13016 CheckStaticLocalForDllExport(VD); 13017 13018 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13019 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13020 // function, only __shared__ variables or variables without any device 13021 // memory qualifiers may be declared with static storage class. 13022 // Note: It is unclear how a function-scope non-const static variable 13023 // without device memory qualifier is implemented, therefore only static 13024 // const variable without device memory qualifier is allowed. 13025 [&]() { 13026 if (!getLangOpts().CUDA) 13027 return; 13028 if (VD->hasAttr<CUDASharedAttr>()) 13029 return; 13030 if (VD->getType().isConstQualified() && 13031 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13032 return; 13033 if (CUDADiagIfDeviceCode(VD->getLocation(), 13034 diag::err_device_static_local_var) 13035 << CurrentCUDATarget()) 13036 VD->setInvalidDecl(); 13037 }(); 13038 } 13039 } 13040 13041 // Perform check for initializers of device-side global variables. 13042 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13043 // 7.5). We must also apply the same checks to all __shared__ 13044 // variables whether they are local or not. CUDA also allows 13045 // constant initializers for __constant__ and __device__ variables. 13046 if (getLangOpts().CUDA) 13047 checkAllowedCUDAInitializer(VD); 13048 13049 // Grab the dllimport or dllexport attribute off of the VarDecl. 13050 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13051 13052 // Imported static data members cannot be defined out-of-line. 13053 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13054 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13055 VD->isThisDeclarationADefinition()) { 13056 // We allow definitions of dllimport class template static data members 13057 // with a warning. 13058 CXXRecordDecl *Context = 13059 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13060 bool IsClassTemplateMember = 13061 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13062 Context->getDescribedClassTemplate(); 13063 13064 Diag(VD->getLocation(), 13065 IsClassTemplateMember 13066 ? diag::warn_attribute_dllimport_static_field_definition 13067 : diag::err_attribute_dllimport_static_field_definition); 13068 Diag(IA->getLocation(), diag::note_attribute); 13069 if (!IsClassTemplateMember) 13070 VD->setInvalidDecl(); 13071 } 13072 } 13073 13074 // dllimport/dllexport variables cannot be thread local, their TLS index 13075 // isn't exported with the variable. 13076 if (DLLAttr && VD->getTLSKind()) { 13077 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13078 if (F && getDLLAttr(F)) { 13079 assert(VD->isStaticLocal()); 13080 // But if this is a static local in a dlimport/dllexport function, the 13081 // function will never be inlined, which means the var would never be 13082 // imported, so having it marked import/export is safe. 13083 } else { 13084 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13085 << DLLAttr; 13086 VD->setInvalidDecl(); 13087 } 13088 } 13089 13090 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13091 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13092 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13093 VD->dropAttr<UsedAttr>(); 13094 } 13095 } 13096 13097 const DeclContext *DC = VD->getDeclContext(); 13098 // If there's a #pragma GCC visibility in scope, and this isn't a class 13099 // member, set the visibility of this variable. 13100 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13101 AddPushedVisibilityAttribute(VD); 13102 13103 // FIXME: Warn on unused var template partial specializations. 13104 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13105 MarkUnusedFileScopedDecl(VD); 13106 13107 // Now we have parsed the initializer and can update the table of magic 13108 // tag values. 13109 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13110 !VD->getType()->isIntegralOrEnumerationType()) 13111 return; 13112 13113 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13114 const Expr *MagicValueExpr = VD->getInit(); 13115 if (!MagicValueExpr) { 13116 continue; 13117 } 13118 llvm::APSInt MagicValueInt; 13119 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13120 Diag(I->getRange().getBegin(), 13121 diag::err_type_tag_for_datatype_not_ice) 13122 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13123 continue; 13124 } 13125 if (MagicValueInt.getActiveBits() > 64) { 13126 Diag(I->getRange().getBegin(), 13127 diag::err_type_tag_for_datatype_too_large) 13128 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13129 continue; 13130 } 13131 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13132 RegisterTypeTagForDatatype(I->getArgumentKind(), 13133 MagicValue, 13134 I->getMatchingCType(), 13135 I->getLayoutCompatible(), 13136 I->getMustBeNull()); 13137 } 13138 } 13139 13140 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13141 auto *VD = dyn_cast<VarDecl>(DD); 13142 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13143 } 13144 13145 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13146 ArrayRef<Decl *> Group) { 13147 SmallVector<Decl*, 8> Decls; 13148 13149 if (DS.isTypeSpecOwned()) 13150 Decls.push_back(DS.getRepAsDecl()); 13151 13152 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13153 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13154 bool DiagnosedMultipleDecomps = false; 13155 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13156 bool DiagnosedNonDeducedAuto = false; 13157 13158 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13159 if (Decl *D = Group[i]) { 13160 // For declarators, there are some additional syntactic-ish checks we need 13161 // to perform. 13162 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13163 if (!FirstDeclaratorInGroup) 13164 FirstDeclaratorInGroup = DD; 13165 if (!FirstDecompDeclaratorInGroup) 13166 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13167 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13168 !hasDeducedAuto(DD)) 13169 FirstNonDeducedAutoInGroup = DD; 13170 13171 if (FirstDeclaratorInGroup != DD) { 13172 // A decomposition declaration cannot be combined with any other 13173 // declaration in the same group. 13174 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13175 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13176 diag::err_decomp_decl_not_alone) 13177 << FirstDeclaratorInGroup->getSourceRange() 13178 << DD->getSourceRange(); 13179 DiagnosedMultipleDecomps = true; 13180 } 13181 13182 // A declarator that uses 'auto' in any way other than to declare a 13183 // variable with a deduced type cannot be combined with any other 13184 // declarator in the same group. 13185 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13186 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13187 diag::err_auto_non_deduced_not_alone) 13188 << FirstNonDeducedAutoInGroup->getType() 13189 ->hasAutoForTrailingReturnType() 13190 << FirstDeclaratorInGroup->getSourceRange() 13191 << DD->getSourceRange(); 13192 DiagnosedNonDeducedAuto = true; 13193 } 13194 } 13195 } 13196 13197 Decls.push_back(D); 13198 } 13199 } 13200 13201 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13202 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13203 handleTagNumbering(Tag, S); 13204 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13205 getLangOpts().CPlusPlus) 13206 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13207 } 13208 } 13209 13210 return BuildDeclaratorGroup(Decls); 13211 } 13212 13213 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13214 /// group, performing any necessary semantic checking. 13215 Sema::DeclGroupPtrTy 13216 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13217 // C++14 [dcl.spec.auto]p7: (DR1347) 13218 // If the type that replaces the placeholder type is not the same in each 13219 // deduction, the program is ill-formed. 13220 if (Group.size() > 1) { 13221 QualType Deduced; 13222 VarDecl *DeducedDecl = nullptr; 13223 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13224 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13225 if (!D || D->isInvalidDecl()) 13226 break; 13227 DeducedType *DT = D->getType()->getContainedDeducedType(); 13228 if (!DT || DT->getDeducedType().isNull()) 13229 continue; 13230 if (Deduced.isNull()) { 13231 Deduced = DT->getDeducedType(); 13232 DeducedDecl = D; 13233 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13234 auto *AT = dyn_cast<AutoType>(DT); 13235 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13236 diag::err_auto_different_deductions) 13237 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13238 << DeducedDecl->getDeclName() << DT->getDeducedType() 13239 << D->getDeclName(); 13240 if (DeducedDecl->hasInit()) 13241 Dia << DeducedDecl->getInit()->getSourceRange(); 13242 if (D->getInit()) 13243 Dia << D->getInit()->getSourceRange(); 13244 D->setInvalidDecl(); 13245 break; 13246 } 13247 } 13248 } 13249 13250 ActOnDocumentableDecls(Group); 13251 13252 return DeclGroupPtrTy::make( 13253 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13254 } 13255 13256 void Sema::ActOnDocumentableDecl(Decl *D) { 13257 ActOnDocumentableDecls(D); 13258 } 13259 13260 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13261 // Don't parse the comment if Doxygen diagnostics are ignored. 13262 if (Group.empty() || !Group[0]) 13263 return; 13264 13265 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13266 Group[0]->getLocation()) && 13267 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13268 Group[0]->getLocation())) 13269 return; 13270 13271 if (Group.size() >= 2) { 13272 // This is a decl group. Normally it will contain only declarations 13273 // produced from declarator list. But in case we have any definitions or 13274 // additional declaration references: 13275 // 'typedef struct S {} S;' 13276 // 'typedef struct S *S;' 13277 // 'struct S *pS;' 13278 // FinalizeDeclaratorGroup adds these as separate declarations. 13279 Decl *MaybeTagDecl = Group[0]; 13280 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13281 Group = Group.slice(1); 13282 } 13283 } 13284 13285 // FIMXE: We assume every Decl in the group is in the same file. 13286 // This is false when preprocessor constructs the group from decls in 13287 // different files (e. g. macros or #include). 13288 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13289 } 13290 13291 /// Common checks for a parameter-declaration that should apply to both function 13292 /// parameters and non-type template parameters. 13293 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13294 // Check that there are no default arguments inside the type of this 13295 // parameter. 13296 if (getLangOpts().CPlusPlus) 13297 CheckExtraCXXDefaultArguments(D); 13298 13299 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13300 if (D.getCXXScopeSpec().isSet()) { 13301 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13302 << D.getCXXScopeSpec().getRange(); 13303 } 13304 13305 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13306 // simple identifier except [...irrelevant cases...]. 13307 switch (D.getName().getKind()) { 13308 case UnqualifiedIdKind::IK_Identifier: 13309 break; 13310 13311 case UnqualifiedIdKind::IK_OperatorFunctionId: 13312 case UnqualifiedIdKind::IK_ConversionFunctionId: 13313 case UnqualifiedIdKind::IK_LiteralOperatorId: 13314 case UnqualifiedIdKind::IK_ConstructorName: 13315 case UnqualifiedIdKind::IK_DestructorName: 13316 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13317 case UnqualifiedIdKind::IK_DeductionGuideName: 13318 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13319 << GetNameForDeclarator(D).getName(); 13320 break; 13321 13322 case UnqualifiedIdKind::IK_TemplateId: 13323 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13324 // GetNameForDeclarator would not produce a useful name in this case. 13325 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13326 break; 13327 } 13328 } 13329 13330 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13331 /// to introduce parameters into function prototype scope. 13332 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13333 const DeclSpec &DS = D.getDeclSpec(); 13334 13335 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13336 13337 // C++03 [dcl.stc]p2 also permits 'auto'. 13338 StorageClass SC = SC_None; 13339 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13340 SC = SC_Register; 13341 // In C++11, the 'register' storage class specifier is deprecated. 13342 // In C++17, it is not allowed, but we tolerate it as an extension. 13343 if (getLangOpts().CPlusPlus11) { 13344 Diag(DS.getStorageClassSpecLoc(), 13345 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13346 : diag::warn_deprecated_register) 13347 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13348 } 13349 } else if (getLangOpts().CPlusPlus && 13350 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13351 SC = SC_Auto; 13352 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13353 Diag(DS.getStorageClassSpecLoc(), 13354 diag::err_invalid_storage_class_in_func_decl); 13355 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13356 } 13357 13358 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13359 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13360 << DeclSpec::getSpecifierName(TSCS); 13361 if (DS.isInlineSpecified()) 13362 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13363 << getLangOpts().CPlusPlus17; 13364 if (DS.hasConstexprSpecifier()) 13365 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13366 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13367 13368 DiagnoseFunctionSpecifiers(DS); 13369 13370 CheckFunctionOrTemplateParamDeclarator(S, D); 13371 13372 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13373 QualType parmDeclType = TInfo->getType(); 13374 13375 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13376 IdentifierInfo *II = D.getIdentifier(); 13377 if (II) { 13378 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13379 ForVisibleRedeclaration); 13380 LookupName(R, S); 13381 if (R.isSingleResult()) { 13382 NamedDecl *PrevDecl = R.getFoundDecl(); 13383 if (PrevDecl->isTemplateParameter()) { 13384 // Maybe we will complain about the shadowed template parameter. 13385 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13386 // Just pretend that we didn't see the previous declaration. 13387 PrevDecl = nullptr; 13388 } else if (S->isDeclScope(PrevDecl)) { 13389 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13390 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13391 13392 // Recover by removing the name 13393 II = nullptr; 13394 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13395 D.setInvalidType(true); 13396 } 13397 } 13398 } 13399 13400 // Temporarily put parameter variables in the translation unit, not 13401 // the enclosing context. This prevents them from accidentally 13402 // looking like class members in C++. 13403 ParmVarDecl *New = 13404 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13405 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13406 13407 if (D.isInvalidType()) 13408 New->setInvalidDecl(); 13409 13410 assert(S->isFunctionPrototypeScope()); 13411 assert(S->getFunctionPrototypeDepth() >= 1); 13412 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13413 S->getNextFunctionPrototypeIndex()); 13414 13415 // Add the parameter declaration into this scope. 13416 S->AddDecl(New); 13417 if (II) 13418 IdResolver.AddDecl(New); 13419 13420 ProcessDeclAttributes(S, New, D); 13421 13422 if (D.getDeclSpec().isModulePrivateSpecified()) 13423 Diag(New->getLocation(), diag::err_module_private_local) 13424 << 1 << New->getDeclName() 13425 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13426 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13427 13428 if (New->hasAttr<BlocksAttr>()) { 13429 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13430 } 13431 13432 if (getLangOpts().OpenCL) 13433 deduceOpenCLAddressSpace(New); 13434 13435 return New; 13436 } 13437 13438 /// Synthesizes a variable for a parameter arising from a 13439 /// typedef. 13440 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13441 SourceLocation Loc, 13442 QualType T) { 13443 /* FIXME: setting StartLoc == Loc. 13444 Would it be worth to modify callers so as to provide proper source 13445 location for the unnamed parameters, embedding the parameter's type? */ 13446 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13447 T, Context.getTrivialTypeSourceInfo(T, Loc), 13448 SC_None, nullptr); 13449 Param->setImplicit(); 13450 return Param; 13451 } 13452 13453 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13454 // Don't diagnose unused-parameter errors in template instantiations; we 13455 // will already have done so in the template itself. 13456 if (inTemplateInstantiation()) 13457 return; 13458 13459 for (const ParmVarDecl *Parameter : Parameters) { 13460 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13461 !Parameter->hasAttr<UnusedAttr>()) { 13462 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13463 << Parameter->getDeclName(); 13464 } 13465 } 13466 } 13467 13468 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13469 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13470 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13471 return; 13472 13473 // Warn if the return value is pass-by-value and larger than the specified 13474 // threshold. 13475 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13476 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13477 if (Size > LangOpts.NumLargeByValueCopy) 13478 Diag(D->getLocation(), diag::warn_return_value_size) 13479 << D->getDeclName() << Size; 13480 } 13481 13482 // Warn if any parameter is pass-by-value and larger than the specified 13483 // threshold. 13484 for (const ParmVarDecl *Parameter : Parameters) { 13485 QualType T = Parameter->getType(); 13486 if (T->isDependentType() || !T.isPODType(Context)) 13487 continue; 13488 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13489 if (Size > LangOpts.NumLargeByValueCopy) 13490 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13491 << Parameter->getDeclName() << Size; 13492 } 13493 } 13494 13495 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13496 SourceLocation NameLoc, IdentifierInfo *Name, 13497 QualType T, TypeSourceInfo *TSInfo, 13498 StorageClass SC) { 13499 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13500 if (getLangOpts().ObjCAutoRefCount && 13501 T.getObjCLifetime() == Qualifiers::OCL_None && 13502 T->isObjCLifetimeType()) { 13503 13504 Qualifiers::ObjCLifetime lifetime; 13505 13506 // Special cases for arrays: 13507 // - if it's const, use __unsafe_unretained 13508 // - otherwise, it's an error 13509 if (T->isArrayType()) { 13510 if (!T.isConstQualified()) { 13511 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13512 DelayedDiagnostics.add( 13513 sema::DelayedDiagnostic::makeForbiddenType( 13514 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13515 else 13516 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13517 << TSInfo->getTypeLoc().getSourceRange(); 13518 } 13519 lifetime = Qualifiers::OCL_ExplicitNone; 13520 } else { 13521 lifetime = T->getObjCARCImplicitLifetime(); 13522 } 13523 T = Context.getLifetimeQualifiedType(T, lifetime); 13524 } 13525 13526 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13527 Context.getAdjustedParameterType(T), 13528 TSInfo, SC, nullptr); 13529 13530 // Make a note if we created a new pack in the scope of a lambda, so that 13531 // we know that references to that pack must also be expanded within the 13532 // lambda scope. 13533 if (New->isParameterPack()) 13534 if (auto *LSI = getEnclosingLambda()) 13535 LSI->LocalPacks.push_back(New); 13536 13537 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13538 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13539 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13540 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13541 13542 // Parameters can not be abstract class types. 13543 // For record types, this is done by the AbstractClassUsageDiagnoser once 13544 // the class has been completely parsed. 13545 if (!CurContext->isRecord() && 13546 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13547 AbstractParamType)) 13548 New->setInvalidDecl(); 13549 13550 // Parameter declarators cannot be interface types. All ObjC objects are 13551 // passed by reference. 13552 if (T->isObjCObjectType()) { 13553 SourceLocation TypeEndLoc = 13554 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13555 Diag(NameLoc, 13556 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13557 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13558 T = Context.getObjCObjectPointerType(T); 13559 New->setType(T); 13560 } 13561 13562 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13563 // duration shall not be qualified by an address-space qualifier." 13564 // Since all parameters have automatic store duration, they can not have 13565 // an address space. 13566 if (T.getAddressSpace() != LangAS::Default && 13567 // OpenCL allows function arguments declared to be an array of a type 13568 // to be qualified with an address space. 13569 !(getLangOpts().OpenCL && 13570 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13571 Diag(NameLoc, diag::err_arg_with_address_space); 13572 New->setInvalidDecl(); 13573 } 13574 13575 return New; 13576 } 13577 13578 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13579 SourceLocation LocAfterDecls) { 13580 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13581 13582 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13583 // for a K&R function. 13584 if (!FTI.hasPrototype) { 13585 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13586 --i; 13587 if (FTI.Params[i].Param == nullptr) { 13588 SmallString<256> Code; 13589 llvm::raw_svector_ostream(Code) 13590 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13591 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13592 << FTI.Params[i].Ident 13593 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13594 13595 // Implicitly declare the argument as type 'int' for lack of a better 13596 // type. 13597 AttributeFactory attrs; 13598 DeclSpec DS(attrs); 13599 const char* PrevSpec; // unused 13600 unsigned DiagID; // unused 13601 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13602 DiagID, Context.getPrintingPolicy()); 13603 // Use the identifier location for the type source range. 13604 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13605 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13606 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13607 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13608 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13609 } 13610 } 13611 } 13612 } 13613 13614 Decl * 13615 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13616 MultiTemplateParamsArg TemplateParameterLists, 13617 SkipBodyInfo *SkipBody) { 13618 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13619 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13620 Scope *ParentScope = FnBodyScope->getParent(); 13621 13622 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13623 // we define a non-templated function definition, we will create a declaration 13624 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13625 // The base function declaration will have the equivalent of an `omp declare 13626 // variant` annotation which specifies the mangled definition as a 13627 // specialization function under the OpenMP context defined as part of the 13628 // `omp begin declare variant`. 13629 FunctionDecl *BaseFD = nullptr; 13630 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13631 TemplateParameterLists.empty()) 13632 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13633 ParentScope, D); 13634 13635 D.setFunctionDefinitionKind(FDK_Definition); 13636 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13637 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13638 13639 if (BaseFD) 13640 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13641 cast<FunctionDecl>(Dcl), BaseFD); 13642 13643 return Dcl; 13644 } 13645 13646 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13647 Consumer.HandleInlineFunctionDefinition(D); 13648 } 13649 13650 static bool 13651 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13652 const FunctionDecl *&PossiblePrototype) { 13653 // Don't warn about invalid declarations. 13654 if (FD->isInvalidDecl()) 13655 return false; 13656 13657 // Or declarations that aren't global. 13658 if (!FD->isGlobal()) 13659 return false; 13660 13661 // Don't warn about C++ member functions. 13662 if (isa<CXXMethodDecl>(FD)) 13663 return false; 13664 13665 // Don't warn about 'main'. 13666 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13667 if (IdentifierInfo *II = FD->getIdentifier()) 13668 if (II->isStr("main")) 13669 return false; 13670 13671 // Don't warn about inline functions. 13672 if (FD->isInlined()) 13673 return false; 13674 13675 // Don't warn about function templates. 13676 if (FD->getDescribedFunctionTemplate()) 13677 return false; 13678 13679 // Don't warn about function template specializations. 13680 if (FD->isFunctionTemplateSpecialization()) 13681 return false; 13682 13683 // Don't warn for OpenCL kernels. 13684 if (FD->hasAttr<OpenCLKernelAttr>()) 13685 return false; 13686 13687 // Don't warn on explicitly deleted functions. 13688 if (FD->isDeleted()) 13689 return false; 13690 13691 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13692 Prev; Prev = Prev->getPreviousDecl()) { 13693 // Ignore any declarations that occur in function or method 13694 // scope, because they aren't visible from the header. 13695 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13696 continue; 13697 13698 PossiblePrototype = Prev; 13699 return Prev->getType()->isFunctionNoProtoType(); 13700 } 13701 13702 return true; 13703 } 13704 13705 void 13706 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13707 const FunctionDecl *EffectiveDefinition, 13708 SkipBodyInfo *SkipBody) { 13709 const FunctionDecl *Definition = EffectiveDefinition; 13710 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13711 // If this is a friend function defined in a class template, it does not 13712 // have a body until it is used, nevertheless it is a definition, see 13713 // [temp.inst]p2: 13714 // 13715 // ... for the purpose of determining whether an instantiated redeclaration 13716 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13717 // corresponds to a definition in the template is considered to be a 13718 // definition. 13719 // 13720 // The following code must produce redefinition error: 13721 // 13722 // template<typename T> struct C20 { friend void func_20() {} }; 13723 // C20<int> c20i; 13724 // void func_20() {} 13725 // 13726 for (auto I : FD->redecls()) { 13727 if (I != FD && !I->isInvalidDecl() && 13728 I->getFriendObjectKind() != Decl::FOK_None) { 13729 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13730 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13731 // A merged copy of the same function, instantiated as a member of 13732 // the same class, is OK. 13733 if (declaresSameEntity(OrigFD, Original) && 13734 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13735 cast<Decl>(FD->getLexicalDeclContext()))) 13736 continue; 13737 } 13738 13739 if (Original->isThisDeclarationADefinition()) { 13740 Definition = I; 13741 break; 13742 } 13743 } 13744 } 13745 } 13746 } 13747 13748 if (!Definition) 13749 // Similar to friend functions a friend function template may be a 13750 // definition and do not have a body if it is instantiated in a class 13751 // template. 13752 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13753 for (auto I : FTD->redecls()) { 13754 auto D = cast<FunctionTemplateDecl>(I); 13755 if (D != FTD) { 13756 assert(!D->isThisDeclarationADefinition() && 13757 "More than one definition in redeclaration chain"); 13758 if (D->getFriendObjectKind() != Decl::FOK_None) 13759 if (FunctionTemplateDecl *FT = 13760 D->getInstantiatedFromMemberTemplate()) { 13761 if (FT->isThisDeclarationADefinition()) { 13762 Definition = D->getTemplatedDecl(); 13763 break; 13764 } 13765 } 13766 } 13767 } 13768 } 13769 13770 if (!Definition) 13771 return; 13772 13773 if (canRedefineFunction(Definition, getLangOpts())) 13774 return; 13775 13776 // Don't emit an error when this is redefinition of a typo-corrected 13777 // definition. 13778 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13779 return; 13780 13781 // If we don't have a visible definition of the function, and it's inline or 13782 // a template, skip the new definition. 13783 if (SkipBody && !hasVisibleDefinition(Definition) && 13784 (Definition->getFormalLinkage() == InternalLinkage || 13785 Definition->isInlined() || 13786 Definition->getDescribedFunctionTemplate() || 13787 Definition->getNumTemplateParameterLists())) { 13788 SkipBody->ShouldSkip = true; 13789 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13790 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13791 makeMergedDefinitionVisible(TD); 13792 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13793 return; 13794 } 13795 13796 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13797 Definition->getStorageClass() == SC_Extern) 13798 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13799 << FD->getDeclName() << getLangOpts().CPlusPlus; 13800 else 13801 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13802 13803 Diag(Definition->getLocation(), diag::note_previous_definition); 13804 FD->setInvalidDecl(); 13805 } 13806 13807 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13808 Sema &S) { 13809 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13810 13811 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13812 LSI->CallOperator = CallOperator; 13813 LSI->Lambda = LambdaClass; 13814 LSI->ReturnType = CallOperator->getReturnType(); 13815 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13816 13817 if (LCD == LCD_None) 13818 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13819 else if (LCD == LCD_ByCopy) 13820 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13821 else if (LCD == LCD_ByRef) 13822 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13823 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13824 13825 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13826 LSI->Mutable = !CallOperator->isConst(); 13827 13828 // Add the captures to the LSI so they can be noted as already 13829 // captured within tryCaptureVar. 13830 auto I = LambdaClass->field_begin(); 13831 for (const auto &C : LambdaClass->captures()) { 13832 if (C.capturesVariable()) { 13833 VarDecl *VD = C.getCapturedVar(); 13834 if (VD->isInitCapture()) 13835 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13836 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13837 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13838 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13839 /*EllipsisLoc*/C.isPackExpansion() 13840 ? C.getEllipsisLoc() : SourceLocation(), 13841 I->getType(), /*Invalid*/false); 13842 13843 } else if (C.capturesThis()) { 13844 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13845 C.getCaptureKind() == LCK_StarThis); 13846 } else { 13847 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13848 I->getType()); 13849 } 13850 ++I; 13851 } 13852 } 13853 13854 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13855 SkipBodyInfo *SkipBody) { 13856 if (!D) { 13857 // Parsing the function declaration failed in some way. Push on a fake scope 13858 // anyway so we can try to parse the function body. 13859 PushFunctionScope(); 13860 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13861 return D; 13862 } 13863 13864 FunctionDecl *FD = nullptr; 13865 13866 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13867 FD = FunTmpl->getTemplatedDecl(); 13868 else 13869 FD = cast<FunctionDecl>(D); 13870 13871 // Do not push if it is a lambda because one is already pushed when building 13872 // the lambda in ActOnStartOfLambdaDefinition(). 13873 if (!isLambdaCallOperator(FD)) 13874 PushExpressionEvaluationContext( 13875 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13876 : ExprEvalContexts.back().Context); 13877 13878 // Check for defining attributes before the check for redefinition. 13879 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13880 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13881 FD->dropAttr<AliasAttr>(); 13882 FD->setInvalidDecl(); 13883 } 13884 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13885 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13886 FD->dropAttr<IFuncAttr>(); 13887 FD->setInvalidDecl(); 13888 } 13889 13890 // See if this is a redefinition. If 'will have body' is already set, then 13891 // these checks were already performed when it was set. 13892 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13893 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13894 13895 // If we're skipping the body, we're done. Don't enter the scope. 13896 if (SkipBody && SkipBody->ShouldSkip) 13897 return D; 13898 } 13899 13900 // Mark this function as "will have a body eventually". This lets users to 13901 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13902 // this function. 13903 FD->setWillHaveBody(); 13904 13905 // If we are instantiating a generic lambda call operator, push 13906 // a LambdaScopeInfo onto the function stack. But use the information 13907 // that's already been calculated (ActOnLambdaExpr) to prime the current 13908 // LambdaScopeInfo. 13909 // When the template operator is being specialized, the LambdaScopeInfo, 13910 // has to be properly restored so that tryCaptureVariable doesn't try 13911 // and capture any new variables. In addition when calculating potential 13912 // captures during transformation of nested lambdas, it is necessary to 13913 // have the LSI properly restored. 13914 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13915 assert(inTemplateInstantiation() && 13916 "There should be an active template instantiation on the stack " 13917 "when instantiating a generic lambda!"); 13918 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13919 } else { 13920 // Enter a new function scope 13921 PushFunctionScope(); 13922 } 13923 13924 // Builtin functions cannot be defined. 13925 if (unsigned BuiltinID = FD->getBuiltinID()) { 13926 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13927 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13928 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13929 FD->setInvalidDecl(); 13930 } 13931 } 13932 13933 // The return type of a function definition must be complete 13934 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13935 QualType ResultType = FD->getReturnType(); 13936 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13937 !FD->isInvalidDecl() && 13938 RequireCompleteType(FD->getLocation(), ResultType, 13939 diag::err_func_def_incomplete_result)) 13940 FD->setInvalidDecl(); 13941 13942 if (FnBodyScope) 13943 PushDeclContext(FnBodyScope, FD); 13944 13945 // Check the validity of our function parameters 13946 CheckParmsForFunctionDef(FD->parameters(), 13947 /*CheckParameterNames=*/true); 13948 13949 // Add non-parameter declarations already in the function to the current 13950 // scope. 13951 if (FnBodyScope) { 13952 for (Decl *NPD : FD->decls()) { 13953 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13954 if (!NonParmDecl) 13955 continue; 13956 assert(!isa<ParmVarDecl>(NonParmDecl) && 13957 "parameters should not be in newly created FD yet"); 13958 13959 // If the decl has a name, make it accessible in the current scope. 13960 if (NonParmDecl->getDeclName()) 13961 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13962 13963 // Similarly, dive into enums and fish their constants out, making them 13964 // accessible in this scope. 13965 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13966 for (auto *EI : ED->enumerators()) 13967 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13968 } 13969 } 13970 } 13971 13972 // Introduce our parameters into the function scope 13973 for (auto Param : FD->parameters()) { 13974 Param->setOwningFunction(FD); 13975 13976 // If this has an identifier, add it to the scope stack. 13977 if (Param->getIdentifier() && FnBodyScope) { 13978 CheckShadow(FnBodyScope, Param); 13979 13980 PushOnScopeChains(Param, FnBodyScope); 13981 } 13982 } 13983 13984 // Ensure that the function's exception specification is instantiated. 13985 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13986 ResolveExceptionSpec(D->getLocation(), FPT); 13987 13988 // dllimport cannot be applied to non-inline function definitions. 13989 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13990 !FD->isTemplateInstantiation()) { 13991 assert(!FD->hasAttr<DLLExportAttr>()); 13992 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13993 FD->setInvalidDecl(); 13994 return D; 13995 } 13996 // We want to attach documentation to original Decl (which might be 13997 // a function template). 13998 ActOnDocumentableDecl(D); 13999 if (getCurLexicalContext()->isObjCContainer() && 14000 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14001 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14002 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14003 14004 return D; 14005 } 14006 14007 /// Given the set of return statements within a function body, 14008 /// compute the variables that are subject to the named return value 14009 /// optimization. 14010 /// 14011 /// Each of the variables that is subject to the named return value 14012 /// optimization will be marked as NRVO variables in the AST, and any 14013 /// return statement that has a marked NRVO variable as its NRVO candidate can 14014 /// use the named return value optimization. 14015 /// 14016 /// This function applies a very simplistic algorithm for NRVO: if every return 14017 /// statement in the scope of a variable has the same NRVO candidate, that 14018 /// candidate is an NRVO variable. 14019 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14020 ReturnStmt **Returns = Scope->Returns.data(); 14021 14022 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14023 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14024 if (!NRVOCandidate->isNRVOVariable()) 14025 Returns[I]->setNRVOCandidate(nullptr); 14026 } 14027 } 14028 } 14029 14030 bool Sema::canDelayFunctionBody(const Declarator &D) { 14031 // We can't delay parsing the body of a constexpr function template (yet). 14032 if (D.getDeclSpec().hasConstexprSpecifier()) 14033 return false; 14034 14035 // We can't delay parsing the body of a function template with a deduced 14036 // return type (yet). 14037 if (D.getDeclSpec().hasAutoTypeSpec()) { 14038 // If the placeholder introduces a non-deduced trailing return type, 14039 // we can still delay parsing it. 14040 if (D.getNumTypeObjects()) { 14041 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14042 if (Outer.Kind == DeclaratorChunk::Function && 14043 Outer.Fun.hasTrailingReturnType()) { 14044 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14045 return Ty.isNull() || !Ty->isUndeducedType(); 14046 } 14047 } 14048 return false; 14049 } 14050 14051 return true; 14052 } 14053 14054 bool Sema::canSkipFunctionBody(Decl *D) { 14055 // We cannot skip the body of a function (or function template) which is 14056 // constexpr, since we may need to evaluate its body in order to parse the 14057 // rest of the file. 14058 // We cannot skip the body of a function with an undeduced return type, 14059 // because any callers of that function need to know the type. 14060 if (const FunctionDecl *FD = D->getAsFunction()) { 14061 if (FD->isConstexpr()) 14062 return false; 14063 // We can't simply call Type::isUndeducedType here, because inside template 14064 // auto can be deduced to a dependent type, which is not considered 14065 // "undeduced". 14066 if (FD->getReturnType()->getContainedDeducedType()) 14067 return false; 14068 } 14069 return Consumer.shouldSkipFunctionBody(D); 14070 } 14071 14072 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14073 if (!Decl) 14074 return nullptr; 14075 if (FunctionDecl *FD = Decl->getAsFunction()) 14076 FD->setHasSkippedBody(); 14077 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14078 MD->setHasSkippedBody(); 14079 return Decl; 14080 } 14081 14082 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14083 return ActOnFinishFunctionBody(D, BodyArg, false); 14084 } 14085 14086 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14087 /// body. 14088 class ExitFunctionBodyRAII { 14089 public: 14090 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14091 ~ExitFunctionBodyRAII() { 14092 if (!IsLambda) 14093 S.PopExpressionEvaluationContext(); 14094 } 14095 14096 private: 14097 Sema &S; 14098 bool IsLambda = false; 14099 }; 14100 14101 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14102 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14103 14104 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14105 if (EscapeInfo.count(BD)) 14106 return EscapeInfo[BD]; 14107 14108 bool R = false; 14109 const BlockDecl *CurBD = BD; 14110 14111 do { 14112 R = !CurBD->doesNotEscape(); 14113 if (R) 14114 break; 14115 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14116 } while (CurBD); 14117 14118 return EscapeInfo[BD] = R; 14119 }; 14120 14121 // If the location where 'self' is implicitly retained is inside a escaping 14122 // block, emit a diagnostic. 14123 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14124 S.ImplicitlyRetainedSelfLocs) 14125 if (IsOrNestedInEscapingBlock(P.second)) 14126 S.Diag(P.first, diag::warn_implicitly_retains_self) 14127 << FixItHint::CreateInsertion(P.first, "self->"); 14128 } 14129 14130 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14131 bool IsInstantiation) { 14132 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14133 14134 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14135 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14136 14137 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14138 CheckCompletedCoroutineBody(FD, Body); 14139 14140 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14141 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14142 // meant to pop the context added in ActOnStartOfFunctionDef(). 14143 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14144 14145 if (FD) { 14146 FD->setBody(Body); 14147 FD->setWillHaveBody(false); 14148 14149 if (getLangOpts().CPlusPlus14) { 14150 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14151 FD->getReturnType()->isUndeducedType()) { 14152 // If the function has a deduced result type but contains no 'return' 14153 // statements, the result type as written must be exactly 'auto', and 14154 // the deduced result type is 'void'. 14155 if (!FD->getReturnType()->getAs<AutoType>()) { 14156 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14157 << FD->getReturnType(); 14158 FD->setInvalidDecl(); 14159 } else { 14160 // Substitute 'void' for the 'auto' in the type. 14161 TypeLoc ResultType = getReturnTypeLoc(FD); 14162 Context.adjustDeducedFunctionResultType( 14163 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14164 } 14165 } 14166 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14167 // In C++11, we don't use 'auto' deduction rules for lambda call 14168 // operators because we don't support return type deduction. 14169 auto *LSI = getCurLambda(); 14170 if (LSI->HasImplicitReturnType) { 14171 deduceClosureReturnType(*LSI); 14172 14173 // C++11 [expr.prim.lambda]p4: 14174 // [...] if there are no return statements in the compound-statement 14175 // [the deduced type is] the type void 14176 QualType RetType = 14177 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14178 14179 // Update the return type to the deduced type. 14180 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14181 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14182 Proto->getExtProtoInfo())); 14183 } 14184 } 14185 14186 // If the function implicitly returns zero (like 'main') or is naked, 14187 // don't complain about missing return statements. 14188 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14189 WP.disableCheckFallThrough(); 14190 14191 // MSVC permits the use of pure specifier (=0) on function definition, 14192 // defined at class scope, warn about this non-standard construct. 14193 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14194 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14195 14196 if (!FD->isInvalidDecl()) { 14197 // Don't diagnose unused parameters of defaulted or deleted functions. 14198 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14199 DiagnoseUnusedParameters(FD->parameters()); 14200 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14201 FD->getReturnType(), FD); 14202 14203 // If this is a structor, we need a vtable. 14204 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14205 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14206 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14207 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14208 14209 // Try to apply the named return value optimization. We have to check 14210 // if we can do this here because lambdas keep return statements around 14211 // to deduce an implicit return type. 14212 if (FD->getReturnType()->isRecordType() && 14213 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14214 computeNRVO(Body, getCurFunction()); 14215 } 14216 14217 // GNU warning -Wmissing-prototypes: 14218 // Warn if a global function is defined without a previous 14219 // prototype declaration. This warning is issued even if the 14220 // definition itself provides a prototype. The aim is to detect 14221 // global functions that fail to be declared in header files. 14222 const FunctionDecl *PossiblePrototype = nullptr; 14223 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14224 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14225 14226 if (PossiblePrototype) { 14227 // We found a declaration that is not a prototype, 14228 // but that could be a zero-parameter prototype 14229 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14230 TypeLoc TL = TI->getTypeLoc(); 14231 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14232 Diag(PossiblePrototype->getLocation(), 14233 diag::note_declaration_not_a_prototype) 14234 << (FD->getNumParams() != 0) 14235 << (FD->getNumParams() == 0 14236 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14237 : FixItHint{}); 14238 } 14239 } else { 14240 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14241 << /* function */ 1 14242 << (FD->getStorageClass() == SC_None 14243 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14244 "static ") 14245 : FixItHint{}); 14246 } 14247 14248 // GNU warning -Wstrict-prototypes 14249 // Warn if K&R function is defined without a previous declaration. 14250 // This warning is issued only if the definition itself does not provide 14251 // a prototype. Only K&R definitions do not provide a prototype. 14252 if (!FD->hasWrittenPrototype()) { 14253 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14254 TypeLoc TL = TI->getTypeLoc(); 14255 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14256 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14257 } 14258 } 14259 14260 // Warn on CPUDispatch with an actual body. 14261 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14262 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14263 if (!CmpndBody->body_empty()) 14264 Diag(CmpndBody->body_front()->getBeginLoc(), 14265 diag::warn_dispatch_body_ignored); 14266 14267 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14268 const CXXMethodDecl *KeyFunction; 14269 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14270 MD->isVirtual() && 14271 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14272 MD == KeyFunction->getCanonicalDecl()) { 14273 // Update the key-function state if necessary for this ABI. 14274 if (FD->isInlined() && 14275 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14276 Context.setNonKeyFunction(MD); 14277 14278 // If the newly-chosen key function is already defined, then we 14279 // need to mark the vtable as used retroactively. 14280 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14281 const FunctionDecl *Definition; 14282 if (KeyFunction && KeyFunction->isDefined(Definition)) 14283 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14284 } else { 14285 // We just defined they key function; mark the vtable as used. 14286 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14287 } 14288 } 14289 } 14290 14291 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14292 "Function parsing confused"); 14293 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14294 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14295 MD->setBody(Body); 14296 if (!MD->isInvalidDecl()) { 14297 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14298 MD->getReturnType(), MD); 14299 14300 if (Body) 14301 computeNRVO(Body, getCurFunction()); 14302 } 14303 if (getCurFunction()->ObjCShouldCallSuper) { 14304 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14305 << MD->getSelector().getAsString(); 14306 getCurFunction()->ObjCShouldCallSuper = false; 14307 } 14308 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14309 const ObjCMethodDecl *InitMethod = nullptr; 14310 bool isDesignated = 14311 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14312 assert(isDesignated && InitMethod); 14313 (void)isDesignated; 14314 14315 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14316 auto IFace = MD->getClassInterface(); 14317 if (!IFace) 14318 return false; 14319 auto SuperD = IFace->getSuperClass(); 14320 if (!SuperD) 14321 return false; 14322 return SuperD->getIdentifier() == 14323 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14324 }; 14325 // Don't issue this warning for unavailable inits or direct subclasses 14326 // of NSObject. 14327 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14328 Diag(MD->getLocation(), 14329 diag::warn_objc_designated_init_missing_super_call); 14330 Diag(InitMethod->getLocation(), 14331 diag::note_objc_designated_init_marked_here); 14332 } 14333 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14334 } 14335 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14336 // Don't issue this warning for unavaialable inits. 14337 if (!MD->isUnavailable()) 14338 Diag(MD->getLocation(), 14339 diag::warn_objc_secondary_init_missing_init_call); 14340 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14341 } 14342 14343 diagnoseImplicitlyRetainedSelf(*this); 14344 } else { 14345 // Parsing the function declaration failed in some way. Pop the fake scope 14346 // we pushed on. 14347 PopFunctionScopeInfo(ActivePolicy, dcl); 14348 return nullptr; 14349 } 14350 14351 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14352 DiagnoseUnguardedAvailabilityViolations(dcl); 14353 14354 assert(!getCurFunction()->ObjCShouldCallSuper && 14355 "This should only be set for ObjC methods, which should have been " 14356 "handled in the block above."); 14357 14358 // Verify and clean out per-function state. 14359 if (Body && (!FD || !FD->isDefaulted())) { 14360 // C++ constructors that have function-try-blocks can't have return 14361 // statements in the handlers of that block. (C++ [except.handle]p14) 14362 // Verify this. 14363 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14364 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14365 14366 // Verify that gotos and switch cases don't jump into scopes illegally. 14367 if (getCurFunction()->NeedsScopeChecking() && 14368 !PP.isCodeCompletionEnabled()) 14369 DiagnoseInvalidJumps(Body); 14370 14371 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14372 if (!Destructor->getParent()->isDependentType()) 14373 CheckDestructor(Destructor); 14374 14375 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14376 Destructor->getParent()); 14377 } 14378 14379 // If any errors have occurred, clear out any temporaries that may have 14380 // been leftover. This ensures that these temporaries won't be picked up for 14381 // deletion in some later function. 14382 if (getDiagnostics().hasErrorOccurred() || 14383 getDiagnostics().getSuppressAllDiagnostics()) { 14384 DiscardCleanupsInEvaluationContext(); 14385 } 14386 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14387 !isa<FunctionTemplateDecl>(dcl)) { 14388 // Since the body is valid, issue any analysis-based warnings that are 14389 // enabled. 14390 ActivePolicy = &WP; 14391 } 14392 14393 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14394 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14395 FD->setInvalidDecl(); 14396 14397 if (FD && FD->hasAttr<NakedAttr>()) { 14398 for (const Stmt *S : Body->children()) { 14399 // Allow local register variables without initializer as they don't 14400 // require prologue. 14401 bool RegisterVariables = false; 14402 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14403 for (const auto *Decl : DS->decls()) { 14404 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14405 RegisterVariables = 14406 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14407 if (!RegisterVariables) 14408 break; 14409 } 14410 } 14411 } 14412 if (RegisterVariables) 14413 continue; 14414 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14415 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14416 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14417 FD->setInvalidDecl(); 14418 break; 14419 } 14420 } 14421 } 14422 14423 assert(ExprCleanupObjects.size() == 14424 ExprEvalContexts.back().NumCleanupObjects && 14425 "Leftover temporaries in function"); 14426 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14427 assert(MaybeODRUseExprs.empty() && 14428 "Leftover expressions for odr-use checking"); 14429 } 14430 14431 if (!IsInstantiation) 14432 PopDeclContext(); 14433 14434 PopFunctionScopeInfo(ActivePolicy, dcl); 14435 // If any errors have occurred, clear out any temporaries that may have 14436 // been leftover. This ensures that these temporaries won't be picked up for 14437 // deletion in some later function. 14438 if (getDiagnostics().hasErrorOccurred()) { 14439 DiscardCleanupsInEvaluationContext(); 14440 } 14441 14442 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14443 auto ES = getEmissionStatus(FD); 14444 if (ES == Sema::FunctionEmissionStatus::Emitted || 14445 ES == Sema::FunctionEmissionStatus::Unknown) 14446 DeclsToCheckForDeferredDiags.push_back(FD); 14447 } 14448 14449 return dcl; 14450 } 14451 14452 /// When we finish delayed parsing of an attribute, we must attach it to the 14453 /// relevant Decl. 14454 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14455 ParsedAttributes &Attrs) { 14456 // Always attach attributes to the underlying decl. 14457 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14458 D = TD->getTemplatedDecl(); 14459 ProcessDeclAttributeList(S, D, Attrs); 14460 14461 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14462 if (Method->isStatic()) 14463 checkThisInStaticMemberFunctionAttributes(Method); 14464 } 14465 14466 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14467 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14468 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14469 IdentifierInfo &II, Scope *S) { 14470 // Find the scope in which the identifier is injected and the corresponding 14471 // DeclContext. 14472 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14473 // In that case, we inject the declaration into the translation unit scope 14474 // instead. 14475 Scope *BlockScope = S; 14476 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14477 BlockScope = BlockScope->getParent(); 14478 14479 Scope *ContextScope = BlockScope; 14480 while (!ContextScope->getEntity()) 14481 ContextScope = ContextScope->getParent(); 14482 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14483 14484 // Before we produce a declaration for an implicitly defined 14485 // function, see whether there was a locally-scoped declaration of 14486 // this name as a function or variable. If so, use that 14487 // (non-visible) declaration, and complain about it. 14488 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14489 if (ExternCPrev) { 14490 // We still need to inject the function into the enclosing block scope so 14491 // that later (non-call) uses can see it. 14492 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14493 14494 // C89 footnote 38: 14495 // If in fact it is not defined as having type "function returning int", 14496 // the behavior is undefined. 14497 if (!isa<FunctionDecl>(ExternCPrev) || 14498 !Context.typesAreCompatible( 14499 cast<FunctionDecl>(ExternCPrev)->getType(), 14500 Context.getFunctionNoProtoType(Context.IntTy))) { 14501 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14502 << ExternCPrev << !getLangOpts().C99; 14503 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14504 return ExternCPrev; 14505 } 14506 } 14507 14508 // Extension in C99. Legal in C90, but warn about it. 14509 unsigned diag_id; 14510 if (II.getName().startswith("__builtin_")) 14511 diag_id = diag::warn_builtin_unknown; 14512 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14513 else if (getLangOpts().OpenCL) 14514 diag_id = diag::err_opencl_implicit_function_decl; 14515 else if (getLangOpts().C99) 14516 diag_id = diag::ext_implicit_function_decl; 14517 else 14518 diag_id = diag::warn_implicit_function_decl; 14519 Diag(Loc, diag_id) << &II; 14520 14521 // If we found a prior declaration of this function, don't bother building 14522 // another one. We've already pushed that one into scope, so there's nothing 14523 // more to do. 14524 if (ExternCPrev) 14525 return ExternCPrev; 14526 14527 // Because typo correction is expensive, only do it if the implicit 14528 // function declaration is going to be treated as an error. 14529 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14530 TypoCorrection Corrected; 14531 DeclFilterCCC<FunctionDecl> CCC{}; 14532 if (S && (Corrected = 14533 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14534 S, nullptr, CCC, CTK_NonError))) 14535 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14536 /*ErrorRecovery*/false); 14537 } 14538 14539 // Set a Declarator for the implicit definition: int foo(); 14540 const char *Dummy; 14541 AttributeFactory attrFactory; 14542 DeclSpec DS(attrFactory); 14543 unsigned DiagID; 14544 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14545 Context.getPrintingPolicy()); 14546 (void)Error; // Silence warning. 14547 assert(!Error && "Error setting up implicit decl!"); 14548 SourceLocation NoLoc; 14549 Declarator D(DS, DeclaratorContext::BlockContext); 14550 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14551 /*IsAmbiguous=*/false, 14552 /*LParenLoc=*/NoLoc, 14553 /*Params=*/nullptr, 14554 /*NumParams=*/0, 14555 /*EllipsisLoc=*/NoLoc, 14556 /*RParenLoc=*/NoLoc, 14557 /*RefQualifierIsLvalueRef=*/true, 14558 /*RefQualifierLoc=*/NoLoc, 14559 /*MutableLoc=*/NoLoc, EST_None, 14560 /*ESpecRange=*/SourceRange(), 14561 /*Exceptions=*/nullptr, 14562 /*ExceptionRanges=*/nullptr, 14563 /*NumExceptions=*/0, 14564 /*NoexceptExpr=*/nullptr, 14565 /*ExceptionSpecTokens=*/nullptr, 14566 /*DeclsInPrototype=*/None, Loc, 14567 Loc, D), 14568 std::move(DS.getAttributes()), SourceLocation()); 14569 D.SetIdentifier(&II, Loc); 14570 14571 // Insert this function into the enclosing block scope. 14572 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14573 FD->setImplicit(); 14574 14575 AddKnownFunctionAttributes(FD); 14576 14577 return FD; 14578 } 14579 14580 /// If this function is a C++ replaceable global allocation function 14581 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14582 /// adds any function attributes that we know a priori based on the standard. 14583 /// 14584 /// We need to check for duplicate attributes both here and where user-written 14585 /// attributes are applied to declarations. 14586 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14587 FunctionDecl *FD) { 14588 if (FD->isInvalidDecl()) 14589 return; 14590 14591 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14592 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14593 return; 14594 14595 Optional<unsigned> AlignmentParam; 14596 bool IsNothrow = false; 14597 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14598 return; 14599 14600 // C++2a [basic.stc.dynamic.allocation]p4: 14601 // An allocation function that has a non-throwing exception specification 14602 // indicates failure by returning a null pointer value. Any other allocation 14603 // function never returns a null pointer value and indicates failure only by 14604 // throwing an exception [...] 14605 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14606 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14607 14608 // C++2a [basic.stc.dynamic.allocation]p2: 14609 // An allocation function attempts to allocate the requested amount of 14610 // storage. [...] If the request succeeds, the value returned by a 14611 // replaceable allocation function is a [...] pointer value p0 different 14612 // from any previously returned value p1 [...] 14613 // 14614 // However, this particular information is being added in codegen, 14615 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14616 14617 // C++2a [basic.stc.dynamic.allocation]p2: 14618 // An allocation function attempts to allocate the requested amount of 14619 // storage. If it is successful, it returns the address of the start of a 14620 // block of storage whose length in bytes is at least as large as the 14621 // requested size. 14622 if (!FD->hasAttr<AllocSizeAttr>()) { 14623 FD->addAttr(AllocSizeAttr::CreateImplicit( 14624 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14625 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14626 } 14627 14628 // C++2a [basic.stc.dynamic.allocation]p3: 14629 // For an allocation function [...], the pointer returned on a successful 14630 // call shall represent the address of storage that is aligned as follows: 14631 // (3.1) If the allocation function takes an argument of type 14632 // std::align_val_t, the storage will have the alignment 14633 // specified by the value of this argument. 14634 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14635 FD->addAttr(AllocAlignAttr::CreateImplicit( 14636 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14637 } 14638 14639 // FIXME: 14640 // C++2a [basic.stc.dynamic.allocation]p3: 14641 // For an allocation function [...], the pointer returned on a successful 14642 // call shall represent the address of storage that is aligned as follows: 14643 // (3.2) Otherwise, if the allocation function is named operator new[], 14644 // the storage is aligned for any object that does not have 14645 // new-extended alignment ([basic.align]) and is no larger than the 14646 // requested size. 14647 // (3.3) Otherwise, the storage is aligned for any object that does not 14648 // have new-extended alignment and is of the requested size. 14649 } 14650 14651 /// Adds any function attributes that we know a priori based on 14652 /// the declaration of this function. 14653 /// 14654 /// These attributes can apply both to implicitly-declared builtins 14655 /// (like __builtin___printf_chk) or to library-declared functions 14656 /// like NSLog or printf. 14657 /// 14658 /// We need to check for duplicate attributes both here and where user-written 14659 /// attributes are applied to declarations. 14660 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14661 if (FD->isInvalidDecl()) 14662 return; 14663 14664 // If this is a built-in function, map its builtin attributes to 14665 // actual attributes. 14666 if (unsigned BuiltinID = FD->getBuiltinID()) { 14667 // Handle printf-formatting attributes. 14668 unsigned FormatIdx; 14669 bool HasVAListArg; 14670 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14671 if (!FD->hasAttr<FormatAttr>()) { 14672 const char *fmt = "printf"; 14673 unsigned int NumParams = FD->getNumParams(); 14674 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14675 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14676 fmt = "NSString"; 14677 FD->addAttr(FormatAttr::CreateImplicit(Context, 14678 &Context.Idents.get(fmt), 14679 FormatIdx+1, 14680 HasVAListArg ? 0 : FormatIdx+2, 14681 FD->getLocation())); 14682 } 14683 } 14684 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14685 HasVAListArg)) { 14686 if (!FD->hasAttr<FormatAttr>()) 14687 FD->addAttr(FormatAttr::CreateImplicit(Context, 14688 &Context.Idents.get("scanf"), 14689 FormatIdx+1, 14690 HasVAListArg ? 0 : FormatIdx+2, 14691 FD->getLocation())); 14692 } 14693 14694 // Handle automatically recognized callbacks. 14695 SmallVector<int, 4> Encoding; 14696 if (!FD->hasAttr<CallbackAttr>() && 14697 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14698 FD->addAttr(CallbackAttr::CreateImplicit( 14699 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14700 14701 // Mark const if we don't care about errno and that is the only thing 14702 // preventing the function from being const. This allows IRgen to use LLVM 14703 // intrinsics for such functions. 14704 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14705 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14706 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14707 14708 // We make "fma" on some platforms const because we know it does not set 14709 // errno in those environments even though it could set errno based on the 14710 // C standard. 14711 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14712 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14713 !FD->hasAttr<ConstAttr>()) { 14714 switch (BuiltinID) { 14715 case Builtin::BI__builtin_fma: 14716 case Builtin::BI__builtin_fmaf: 14717 case Builtin::BI__builtin_fmal: 14718 case Builtin::BIfma: 14719 case Builtin::BIfmaf: 14720 case Builtin::BIfmal: 14721 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14722 break; 14723 default: 14724 break; 14725 } 14726 } 14727 14728 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14729 !FD->hasAttr<ReturnsTwiceAttr>()) 14730 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14731 FD->getLocation())); 14732 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14733 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14734 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14735 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14736 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14737 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14738 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14739 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14740 // Add the appropriate attribute, depending on the CUDA compilation mode 14741 // and which target the builtin belongs to. For example, during host 14742 // compilation, aux builtins are __device__, while the rest are __host__. 14743 if (getLangOpts().CUDAIsDevice != 14744 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14745 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14746 else 14747 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14748 } 14749 } 14750 14751 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14752 14753 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14754 // throw, add an implicit nothrow attribute to any extern "C" function we come 14755 // across. 14756 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14757 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14758 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14759 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14760 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14761 } 14762 14763 IdentifierInfo *Name = FD->getIdentifier(); 14764 if (!Name) 14765 return; 14766 if ((!getLangOpts().CPlusPlus && 14767 FD->getDeclContext()->isTranslationUnit()) || 14768 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14769 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14770 LinkageSpecDecl::lang_c)) { 14771 // Okay: this could be a libc/libm/Objective-C function we know 14772 // about. 14773 } else 14774 return; 14775 14776 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14777 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14778 // target-specific builtins, perhaps? 14779 if (!FD->hasAttr<FormatAttr>()) 14780 FD->addAttr(FormatAttr::CreateImplicit(Context, 14781 &Context.Idents.get("printf"), 2, 14782 Name->isStr("vasprintf") ? 0 : 3, 14783 FD->getLocation())); 14784 } 14785 14786 if (Name->isStr("__CFStringMakeConstantString")) { 14787 // We already have a __builtin___CFStringMakeConstantString, 14788 // but builds that use -fno-constant-cfstrings don't go through that. 14789 if (!FD->hasAttr<FormatArgAttr>()) 14790 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14791 FD->getLocation())); 14792 } 14793 } 14794 14795 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14796 TypeSourceInfo *TInfo) { 14797 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14798 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14799 14800 if (!TInfo) { 14801 assert(D.isInvalidType() && "no declarator info for valid type"); 14802 TInfo = Context.getTrivialTypeSourceInfo(T); 14803 } 14804 14805 // Scope manipulation handled by caller. 14806 TypedefDecl *NewTD = 14807 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14808 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14809 14810 // Bail out immediately if we have an invalid declaration. 14811 if (D.isInvalidType()) { 14812 NewTD->setInvalidDecl(); 14813 return NewTD; 14814 } 14815 14816 if (D.getDeclSpec().isModulePrivateSpecified()) { 14817 if (CurContext->isFunctionOrMethod()) 14818 Diag(NewTD->getLocation(), diag::err_module_private_local) 14819 << 2 << NewTD->getDeclName() 14820 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14821 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14822 else 14823 NewTD->setModulePrivate(); 14824 } 14825 14826 // C++ [dcl.typedef]p8: 14827 // If the typedef declaration defines an unnamed class (or 14828 // enum), the first typedef-name declared by the declaration 14829 // to be that class type (or enum type) is used to denote the 14830 // class type (or enum type) for linkage purposes only. 14831 // We need to check whether the type was declared in the declaration. 14832 switch (D.getDeclSpec().getTypeSpecType()) { 14833 case TST_enum: 14834 case TST_struct: 14835 case TST_interface: 14836 case TST_union: 14837 case TST_class: { 14838 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14839 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14840 break; 14841 } 14842 14843 default: 14844 break; 14845 } 14846 14847 return NewTD; 14848 } 14849 14850 /// Check that this is a valid underlying type for an enum declaration. 14851 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14852 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14853 QualType T = TI->getType(); 14854 14855 if (T->isDependentType()) 14856 return false; 14857 14858 // This doesn't use 'isIntegralType' despite the error message mentioning 14859 // integral type because isIntegralType would also allow enum types in C. 14860 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14861 if (BT->isInteger()) 14862 return false; 14863 14864 if (T->isExtIntType()) 14865 return false; 14866 14867 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14868 } 14869 14870 /// Check whether this is a valid redeclaration of a previous enumeration. 14871 /// \return true if the redeclaration was invalid. 14872 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14873 QualType EnumUnderlyingTy, bool IsFixed, 14874 const EnumDecl *Prev) { 14875 if (IsScoped != Prev->isScoped()) { 14876 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14877 << Prev->isScoped(); 14878 Diag(Prev->getLocation(), diag::note_previous_declaration); 14879 return true; 14880 } 14881 14882 if (IsFixed && Prev->isFixed()) { 14883 if (!EnumUnderlyingTy->isDependentType() && 14884 !Prev->getIntegerType()->isDependentType() && 14885 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14886 Prev->getIntegerType())) { 14887 // TODO: Highlight the underlying type of the redeclaration. 14888 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14889 << EnumUnderlyingTy << Prev->getIntegerType(); 14890 Diag(Prev->getLocation(), diag::note_previous_declaration) 14891 << Prev->getIntegerTypeRange(); 14892 return true; 14893 } 14894 } else if (IsFixed != Prev->isFixed()) { 14895 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14896 << Prev->isFixed(); 14897 Diag(Prev->getLocation(), diag::note_previous_declaration); 14898 return true; 14899 } 14900 14901 return false; 14902 } 14903 14904 /// Get diagnostic %select index for tag kind for 14905 /// redeclaration diagnostic message. 14906 /// WARNING: Indexes apply to particular diagnostics only! 14907 /// 14908 /// \returns diagnostic %select index. 14909 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14910 switch (Tag) { 14911 case TTK_Struct: return 0; 14912 case TTK_Interface: return 1; 14913 case TTK_Class: return 2; 14914 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14915 } 14916 } 14917 14918 /// Determine if tag kind is a class-key compatible with 14919 /// class for redeclaration (class, struct, or __interface). 14920 /// 14921 /// \returns true iff the tag kind is compatible. 14922 static bool isClassCompatTagKind(TagTypeKind Tag) 14923 { 14924 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14925 } 14926 14927 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14928 TagTypeKind TTK) { 14929 if (isa<TypedefDecl>(PrevDecl)) 14930 return NTK_Typedef; 14931 else if (isa<TypeAliasDecl>(PrevDecl)) 14932 return NTK_TypeAlias; 14933 else if (isa<ClassTemplateDecl>(PrevDecl)) 14934 return NTK_Template; 14935 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14936 return NTK_TypeAliasTemplate; 14937 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14938 return NTK_TemplateTemplateArgument; 14939 switch (TTK) { 14940 case TTK_Struct: 14941 case TTK_Interface: 14942 case TTK_Class: 14943 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14944 case TTK_Union: 14945 return NTK_NonUnion; 14946 case TTK_Enum: 14947 return NTK_NonEnum; 14948 } 14949 llvm_unreachable("invalid TTK"); 14950 } 14951 14952 /// Determine whether a tag with a given kind is acceptable 14953 /// as a redeclaration of the given tag declaration. 14954 /// 14955 /// \returns true if the new tag kind is acceptable, false otherwise. 14956 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14957 TagTypeKind NewTag, bool isDefinition, 14958 SourceLocation NewTagLoc, 14959 const IdentifierInfo *Name) { 14960 // C++ [dcl.type.elab]p3: 14961 // The class-key or enum keyword present in the 14962 // elaborated-type-specifier shall agree in kind with the 14963 // declaration to which the name in the elaborated-type-specifier 14964 // refers. This rule also applies to the form of 14965 // elaborated-type-specifier that declares a class-name or 14966 // friend class since it can be construed as referring to the 14967 // definition of the class. Thus, in any 14968 // elaborated-type-specifier, the enum keyword shall be used to 14969 // refer to an enumeration (7.2), the union class-key shall be 14970 // used to refer to a union (clause 9), and either the class or 14971 // struct class-key shall be used to refer to a class (clause 9) 14972 // declared using the class or struct class-key. 14973 TagTypeKind OldTag = Previous->getTagKind(); 14974 if (OldTag != NewTag && 14975 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14976 return false; 14977 14978 // Tags are compatible, but we might still want to warn on mismatched tags. 14979 // Non-class tags can't be mismatched at this point. 14980 if (!isClassCompatTagKind(NewTag)) 14981 return true; 14982 14983 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14984 // by our warning analysis. We don't want to warn about mismatches with (eg) 14985 // declarations in system headers that are designed to be specialized, but if 14986 // a user asks us to warn, we should warn if their code contains mismatched 14987 // declarations. 14988 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14989 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14990 Loc); 14991 }; 14992 if (IsIgnoredLoc(NewTagLoc)) 14993 return true; 14994 14995 auto IsIgnored = [&](const TagDecl *Tag) { 14996 return IsIgnoredLoc(Tag->getLocation()); 14997 }; 14998 while (IsIgnored(Previous)) { 14999 Previous = Previous->getPreviousDecl(); 15000 if (!Previous) 15001 return true; 15002 OldTag = Previous->getTagKind(); 15003 } 15004 15005 bool isTemplate = false; 15006 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15007 isTemplate = Record->getDescribedClassTemplate(); 15008 15009 if (inTemplateInstantiation()) { 15010 if (OldTag != NewTag) { 15011 // In a template instantiation, do not offer fix-its for tag mismatches 15012 // since they usually mess up the template instead of fixing the problem. 15013 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15014 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15015 << getRedeclDiagFromTagKind(OldTag); 15016 // FIXME: Note previous location? 15017 } 15018 return true; 15019 } 15020 15021 if (isDefinition) { 15022 // On definitions, check all previous tags and issue a fix-it for each 15023 // one that doesn't match the current tag. 15024 if (Previous->getDefinition()) { 15025 // Don't suggest fix-its for redefinitions. 15026 return true; 15027 } 15028 15029 bool previousMismatch = false; 15030 for (const TagDecl *I : Previous->redecls()) { 15031 if (I->getTagKind() != NewTag) { 15032 // Ignore previous declarations for which the warning was disabled. 15033 if (IsIgnored(I)) 15034 continue; 15035 15036 if (!previousMismatch) { 15037 previousMismatch = true; 15038 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15039 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15040 << getRedeclDiagFromTagKind(I->getTagKind()); 15041 } 15042 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15043 << getRedeclDiagFromTagKind(NewTag) 15044 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15045 TypeWithKeyword::getTagTypeKindName(NewTag)); 15046 } 15047 } 15048 return true; 15049 } 15050 15051 // Identify the prevailing tag kind: this is the kind of the definition (if 15052 // there is a non-ignored definition), or otherwise the kind of the prior 15053 // (non-ignored) declaration. 15054 const TagDecl *PrevDef = Previous->getDefinition(); 15055 if (PrevDef && IsIgnored(PrevDef)) 15056 PrevDef = nullptr; 15057 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15058 if (Redecl->getTagKind() != NewTag) { 15059 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15060 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15061 << getRedeclDiagFromTagKind(OldTag); 15062 Diag(Redecl->getLocation(), diag::note_previous_use); 15063 15064 // If there is a previous definition, suggest a fix-it. 15065 if (PrevDef) { 15066 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15067 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15068 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15069 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15070 } 15071 } 15072 15073 return true; 15074 } 15075 15076 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15077 /// from an outer enclosing namespace or file scope inside a friend declaration. 15078 /// This should provide the commented out code in the following snippet: 15079 /// namespace N { 15080 /// struct X; 15081 /// namespace M { 15082 /// struct Y { friend struct /*N::*/ X; }; 15083 /// } 15084 /// } 15085 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15086 SourceLocation NameLoc) { 15087 // While the decl is in a namespace, do repeated lookup of that name and see 15088 // if we get the same namespace back. If we do not, continue until 15089 // translation unit scope, at which point we have a fully qualified NNS. 15090 SmallVector<IdentifierInfo *, 4> Namespaces; 15091 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15092 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15093 // This tag should be declared in a namespace, which can only be enclosed by 15094 // other namespaces. Bail if there's an anonymous namespace in the chain. 15095 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15096 if (!Namespace || Namespace->isAnonymousNamespace()) 15097 return FixItHint(); 15098 IdentifierInfo *II = Namespace->getIdentifier(); 15099 Namespaces.push_back(II); 15100 NamedDecl *Lookup = SemaRef.LookupSingleName( 15101 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15102 if (Lookup == Namespace) 15103 break; 15104 } 15105 15106 // Once we have all the namespaces, reverse them to go outermost first, and 15107 // build an NNS. 15108 SmallString<64> Insertion; 15109 llvm::raw_svector_ostream OS(Insertion); 15110 if (DC->isTranslationUnit()) 15111 OS << "::"; 15112 std::reverse(Namespaces.begin(), Namespaces.end()); 15113 for (auto *II : Namespaces) 15114 OS << II->getName() << "::"; 15115 return FixItHint::CreateInsertion(NameLoc, Insertion); 15116 } 15117 15118 /// Determine whether a tag originally declared in context \p OldDC can 15119 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15120 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15121 /// using-declaration). 15122 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15123 DeclContext *NewDC) { 15124 OldDC = OldDC->getRedeclContext(); 15125 NewDC = NewDC->getRedeclContext(); 15126 15127 if (OldDC->Equals(NewDC)) 15128 return true; 15129 15130 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15131 // encloses the other). 15132 if (S.getLangOpts().MSVCCompat && 15133 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15134 return true; 15135 15136 return false; 15137 } 15138 15139 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15140 /// former case, Name will be non-null. In the later case, Name will be null. 15141 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15142 /// reference/declaration/definition of a tag. 15143 /// 15144 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15145 /// trailing-type-specifier) other than one in an alias-declaration. 15146 /// 15147 /// \param SkipBody If non-null, will be set to indicate if the caller should 15148 /// skip the definition of this tag and treat it as if it were a declaration. 15149 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15150 SourceLocation KWLoc, CXXScopeSpec &SS, 15151 IdentifierInfo *Name, SourceLocation NameLoc, 15152 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15153 SourceLocation ModulePrivateLoc, 15154 MultiTemplateParamsArg TemplateParameterLists, 15155 bool &OwnedDecl, bool &IsDependent, 15156 SourceLocation ScopedEnumKWLoc, 15157 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15158 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15159 SkipBodyInfo *SkipBody) { 15160 // If this is not a definition, it must have a name. 15161 IdentifierInfo *OrigName = Name; 15162 assert((Name != nullptr || TUK == TUK_Definition) && 15163 "Nameless record must be a definition!"); 15164 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15165 15166 OwnedDecl = false; 15167 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15168 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15169 15170 // FIXME: Check member specializations more carefully. 15171 bool isMemberSpecialization = false; 15172 bool Invalid = false; 15173 15174 // We only need to do this matching if we have template parameters 15175 // or a scope specifier, which also conveniently avoids this work 15176 // for non-C++ cases. 15177 if (TemplateParameterLists.size() > 0 || 15178 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15179 if (TemplateParameterList *TemplateParams = 15180 MatchTemplateParametersToScopeSpecifier( 15181 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15182 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15183 if (Kind == TTK_Enum) { 15184 Diag(KWLoc, diag::err_enum_template); 15185 return nullptr; 15186 } 15187 15188 if (TemplateParams->size() > 0) { 15189 // This is a declaration or definition of a class template (which may 15190 // be a member of another template). 15191 15192 if (Invalid) 15193 return nullptr; 15194 15195 OwnedDecl = false; 15196 DeclResult Result = CheckClassTemplate( 15197 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15198 AS, ModulePrivateLoc, 15199 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15200 TemplateParameterLists.data(), SkipBody); 15201 return Result.get(); 15202 } else { 15203 // The "template<>" header is extraneous. 15204 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15205 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15206 isMemberSpecialization = true; 15207 } 15208 } 15209 } 15210 15211 // Figure out the underlying type if this a enum declaration. We need to do 15212 // this early, because it's needed to detect if this is an incompatible 15213 // redeclaration. 15214 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15215 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15216 15217 if (Kind == TTK_Enum) { 15218 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15219 // No underlying type explicitly specified, or we failed to parse the 15220 // type, default to int. 15221 EnumUnderlying = Context.IntTy.getTypePtr(); 15222 } else if (UnderlyingType.get()) { 15223 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15224 // integral type; any cv-qualification is ignored. 15225 TypeSourceInfo *TI = nullptr; 15226 GetTypeFromParser(UnderlyingType.get(), &TI); 15227 EnumUnderlying = TI; 15228 15229 if (CheckEnumUnderlyingType(TI)) 15230 // Recover by falling back to int. 15231 EnumUnderlying = Context.IntTy.getTypePtr(); 15232 15233 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15234 UPPC_FixedUnderlyingType)) 15235 EnumUnderlying = Context.IntTy.getTypePtr(); 15236 15237 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15238 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15239 // of 'int'. However, if this is an unfixed forward declaration, don't set 15240 // the underlying type unless the user enables -fms-compatibility. This 15241 // makes unfixed forward declared enums incomplete and is more conforming. 15242 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15243 EnumUnderlying = Context.IntTy.getTypePtr(); 15244 } 15245 } 15246 15247 DeclContext *SearchDC = CurContext; 15248 DeclContext *DC = CurContext; 15249 bool isStdBadAlloc = false; 15250 bool isStdAlignValT = false; 15251 15252 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15253 if (TUK == TUK_Friend || TUK == TUK_Reference) 15254 Redecl = NotForRedeclaration; 15255 15256 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15257 /// implemented asks for structural equivalence checking, the returned decl 15258 /// here is passed back to the parser, allowing the tag body to be parsed. 15259 auto createTagFromNewDecl = [&]() -> TagDecl * { 15260 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15261 // If there is an identifier, use the location of the identifier as the 15262 // location of the decl, otherwise use the location of the struct/union 15263 // keyword. 15264 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15265 TagDecl *New = nullptr; 15266 15267 if (Kind == TTK_Enum) { 15268 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15269 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15270 // If this is an undefined enum, bail. 15271 if (TUK != TUK_Definition && !Invalid) 15272 return nullptr; 15273 if (EnumUnderlying) { 15274 EnumDecl *ED = cast<EnumDecl>(New); 15275 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15276 ED->setIntegerTypeSourceInfo(TI); 15277 else 15278 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15279 ED->setPromotionType(ED->getIntegerType()); 15280 } 15281 } else { // struct/union 15282 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15283 nullptr); 15284 } 15285 15286 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15287 // Add alignment attributes if necessary; these attributes are checked 15288 // when the ASTContext lays out the structure. 15289 // 15290 // It is important for implementing the correct semantics that this 15291 // happen here (in ActOnTag). The #pragma pack stack is 15292 // maintained as a result of parser callbacks which can occur at 15293 // many points during the parsing of a struct declaration (because 15294 // the #pragma tokens are effectively skipped over during the 15295 // parsing of the struct). 15296 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15297 AddAlignmentAttributesForRecord(RD); 15298 AddMsStructLayoutForRecord(RD); 15299 } 15300 } 15301 New->setLexicalDeclContext(CurContext); 15302 return New; 15303 }; 15304 15305 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15306 if (Name && SS.isNotEmpty()) { 15307 // We have a nested-name tag ('struct foo::bar'). 15308 15309 // Check for invalid 'foo::'. 15310 if (SS.isInvalid()) { 15311 Name = nullptr; 15312 goto CreateNewDecl; 15313 } 15314 15315 // If this is a friend or a reference to a class in a dependent 15316 // context, don't try to make a decl for it. 15317 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15318 DC = computeDeclContext(SS, false); 15319 if (!DC) { 15320 IsDependent = true; 15321 return nullptr; 15322 } 15323 } else { 15324 DC = computeDeclContext(SS, true); 15325 if (!DC) { 15326 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15327 << SS.getRange(); 15328 return nullptr; 15329 } 15330 } 15331 15332 if (RequireCompleteDeclContext(SS, DC)) 15333 return nullptr; 15334 15335 SearchDC = DC; 15336 // Look-up name inside 'foo::'. 15337 LookupQualifiedName(Previous, DC); 15338 15339 if (Previous.isAmbiguous()) 15340 return nullptr; 15341 15342 if (Previous.empty()) { 15343 // Name lookup did not find anything. However, if the 15344 // nested-name-specifier refers to the current instantiation, 15345 // and that current instantiation has any dependent base 15346 // classes, we might find something at instantiation time: treat 15347 // this as a dependent elaborated-type-specifier. 15348 // But this only makes any sense for reference-like lookups. 15349 if (Previous.wasNotFoundInCurrentInstantiation() && 15350 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15351 IsDependent = true; 15352 return nullptr; 15353 } 15354 15355 // A tag 'foo::bar' must already exist. 15356 Diag(NameLoc, diag::err_not_tag_in_scope) 15357 << Kind << Name << DC << SS.getRange(); 15358 Name = nullptr; 15359 Invalid = true; 15360 goto CreateNewDecl; 15361 } 15362 } else if (Name) { 15363 // C++14 [class.mem]p14: 15364 // If T is the name of a class, then each of the following shall have a 15365 // name different from T: 15366 // -- every member of class T that is itself a type 15367 if (TUK != TUK_Reference && TUK != TUK_Friend && 15368 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15369 return nullptr; 15370 15371 // If this is a named struct, check to see if there was a previous forward 15372 // declaration or definition. 15373 // FIXME: We're looking into outer scopes here, even when we 15374 // shouldn't be. Doing so can result in ambiguities that we 15375 // shouldn't be diagnosing. 15376 LookupName(Previous, S); 15377 15378 // When declaring or defining a tag, ignore ambiguities introduced 15379 // by types using'ed into this scope. 15380 if (Previous.isAmbiguous() && 15381 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15382 LookupResult::Filter F = Previous.makeFilter(); 15383 while (F.hasNext()) { 15384 NamedDecl *ND = F.next(); 15385 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15386 SearchDC->getRedeclContext())) 15387 F.erase(); 15388 } 15389 F.done(); 15390 } 15391 15392 // C++11 [namespace.memdef]p3: 15393 // If the name in a friend declaration is neither qualified nor 15394 // a template-id and the declaration is a function or an 15395 // elaborated-type-specifier, the lookup to determine whether 15396 // the entity has been previously declared shall not consider 15397 // any scopes outside the innermost enclosing namespace. 15398 // 15399 // MSVC doesn't implement the above rule for types, so a friend tag 15400 // declaration may be a redeclaration of a type declared in an enclosing 15401 // scope. They do implement this rule for friend functions. 15402 // 15403 // Does it matter that this should be by scope instead of by 15404 // semantic context? 15405 if (!Previous.empty() && TUK == TUK_Friend) { 15406 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15407 LookupResult::Filter F = Previous.makeFilter(); 15408 bool FriendSawTagOutsideEnclosingNamespace = false; 15409 while (F.hasNext()) { 15410 NamedDecl *ND = F.next(); 15411 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15412 if (DC->isFileContext() && 15413 !EnclosingNS->Encloses(ND->getDeclContext())) { 15414 if (getLangOpts().MSVCCompat) 15415 FriendSawTagOutsideEnclosingNamespace = true; 15416 else 15417 F.erase(); 15418 } 15419 } 15420 F.done(); 15421 15422 // Diagnose this MSVC extension in the easy case where lookup would have 15423 // unambiguously found something outside the enclosing namespace. 15424 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15425 NamedDecl *ND = Previous.getFoundDecl(); 15426 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15427 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15428 } 15429 } 15430 15431 // Note: there used to be some attempt at recovery here. 15432 if (Previous.isAmbiguous()) 15433 return nullptr; 15434 15435 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15436 // FIXME: This makes sure that we ignore the contexts associated 15437 // with C structs, unions, and enums when looking for a matching 15438 // tag declaration or definition. See the similar lookup tweak 15439 // in Sema::LookupName; is there a better way to deal with this? 15440 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15441 SearchDC = SearchDC->getParent(); 15442 } 15443 } 15444 15445 if (Previous.isSingleResult() && 15446 Previous.getFoundDecl()->isTemplateParameter()) { 15447 // Maybe we will complain about the shadowed template parameter. 15448 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15449 // Just pretend that we didn't see the previous declaration. 15450 Previous.clear(); 15451 } 15452 15453 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15454 DC->Equals(getStdNamespace())) { 15455 if (Name->isStr("bad_alloc")) { 15456 // This is a declaration of or a reference to "std::bad_alloc". 15457 isStdBadAlloc = true; 15458 15459 // If std::bad_alloc has been implicitly declared (but made invisible to 15460 // name lookup), fill in this implicit declaration as the previous 15461 // declaration, so that the declarations get chained appropriately. 15462 if (Previous.empty() && StdBadAlloc) 15463 Previous.addDecl(getStdBadAlloc()); 15464 } else if (Name->isStr("align_val_t")) { 15465 isStdAlignValT = true; 15466 if (Previous.empty() && StdAlignValT) 15467 Previous.addDecl(getStdAlignValT()); 15468 } 15469 } 15470 15471 // If we didn't find a previous declaration, and this is a reference 15472 // (or friend reference), move to the correct scope. In C++, we 15473 // also need to do a redeclaration lookup there, just in case 15474 // there's a shadow friend decl. 15475 if (Name && Previous.empty() && 15476 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15477 if (Invalid) goto CreateNewDecl; 15478 assert(SS.isEmpty()); 15479 15480 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15481 // C++ [basic.scope.pdecl]p5: 15482 // -- for an elaborated-type-specifier of the form 15483 // 15484 // class-key identifier 15485 // 15486 // if the elaborated-type-specifier is used in the 15487 // decl-specifier-seq or parameter-declaration-clause of a 15488 // function defined in namespace scope, the identifier is 15489 // declared as a class-name in the namespace that contains 15490 // the declaration; otherwise, except as a friend 15491 // declaration, the identifier is declared in the smallest 15492 // non-class, non-function-prototype scope that contains the 15493 // declaration. 15494 // 15495 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15496 // C structs and unions. 15497 // 15498 // It is an error in C++ to declare (rather than define) an enum 15499 // type, including via an elaborated type specifier. We'll 15500 // diagnose that later; for now, declare the enum in the same 15501 // scope as we would have picked for any other tag type. 15502 // 15503 // GNU C also supports this behavior as part of its incomplete 15504 // enum types extension, while GNU C++ does not. 15505 // 15506 // Find the context where we'll be declaring the tag. 15507 // FIXME: We would like to maintain the current DeclContext as the 15508 // lexical context, 15509 SearchDC = getTagInjectionContext(SearchDC); 15510 15511 // Find the scope where we'll be declaring the tag. 15512 S = getTagInjectionScope(S, getLangOpts()); 15513 } else { 15514 assert(TUK == TUK_Friend); 15515 // C++ [namespace.memdef]p3: 15516 // If a friend declaration in a non-local class first declares a 15517 // class or function, the friend class or function is a member of 15518 // the innermost enclosing namespace. 15519 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15520 } 15521 15522 // In C++, we need to do a redeclaration lookup to properly 15523 // diagnose some problems. 15524 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15525 // hidden declaration so that we don't get ambiguity errors when using a 15526 // type declared by an elaborated-type-specifier. In C that is not correct 15527 // and we should instead merge compatible types found by lookup. 15528 if (getLangOpts().CPlusPlus) { 15529 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15530 LookupQualifiedName(Previous, SearchDC); 15531 } else { 15532 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15533 LookupName(Previous, S); 15534 } 15535 } 15536 15537 // If we have a known previous declaration to use, then use it. 15538 if (Previous.empty() && SkipBody && SkipBody->Previous) 15539 Previous.addDecl(SkipBody->Previous); 15540 15541 if (!Previous.empty()) { 15542 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15543 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15544 15545 // It's okay to have a tag decl in the same scope as a typedef 15546 // which hides a tag decl in the same scope. Finding this 15547 // insanity with a redeclaration lookup can only actually happen 15548 // in C++. 15549 // 15550 // This is also okay for elaborated-type-specifiers, which is 15551 // technically forbidden by the current standard but which is 15552 // okay according to the likely resolution of an open issue; 15553 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15554 if (getLangOpts().CPlusPlus) { 15555 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15556 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15557 TagDecl *Tag = TT->getDecl(); 15558 if (Tag->getDeclName() == Name && 15559 Tag->getDeclContext()->getRedeclContext() 15560 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15561 PrevDecl = Tag; 15562 Previous.clear(); 15563 Previous.addDecl(Tag); 15564 Previous.resolveKind(); 15565 } 15566 } 15567 } 15568 } 15569 15570 // If this is a redeclaration of a using shadow declaration, it must 15571 // declare a tag in the same context. In MSVC mode, we allow a 15572 // redefinition if either context is within the other. 15573 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15574 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15575 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15576 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15577 !(OldTag && isAcceptableTagRedeclContext( 15578 *this, OldTag->getDeclContext(), SearchDC))) { 15579 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15580 Diag(Shadow->getTargetDecl()->getLocation(), 15581 diag::note_using_decl_target); 15582 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15583 << 0; 15584 // Recover by ignoring the old declaration. 15585 Previous.clear(); 15586 goto CreateNewDecl; 15587 } 15588 } 15589 15590 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15591 // If this is a use of a previous tag, or if the tag is already declared 15592 // in the same scope (so that the definition/declaration completes or 15593 // rementions the tag), reuse the decl. 15594 if (TUK == TUK_Reference || TUK == TUK_Friend || 15595 isDeclInScope(DirectPrevDecl, SearchDC, S, 15596 SS.isNotEmpty() || isMemberSpecialization)) { 15597 // Make sure that this wasn't declared as an enum and now used as a 15598 // struct or something similar. 15599 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15600 TUK == TUK_Definition, KWLoc, 15601 Name)) { 15602 bool SafeToContinue 15603 = (PrevTagDecl->getTagKind() != TTK_Enum && 15604 Kind != TTK_Enum); 15605 if (SafeToContinue) 15606 Diag(KWLoc, diag::err_use_with_wrong_tag) 15607 << Name 15608 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15609 PrevTagDecl->getKindName()); 15610 else 15611 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15612 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15613 15614 if (SafeToContinue) 15615 Kind = PrevTagDecl->getTagKind(); 15616 else { 15617 // Recover by making this an anonymous redefinition. 15618 Name = nullptr; 15619 Previous.clear(); 15620 Invalid = true; 15621 } 15622 } 15623 15624 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15625 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15626 if (TUK == TUK_Reference || TUK == TUK_Friend) 15627 return PrevTagDecl; 15628 15629 QualType EnumUnderlyingTy; 15630 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15631 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15632 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15633 EnumUnderlyingTy = QualType(T, 0); 15634 15635 // All conflicts with previous declarations are recovered by 15636 // returning the previous declaration, unless this is a definition, 15637 // in which case we want the caller to bail out. 15638 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15639 ScopedEnum, EnumUnderlyingTy, 15640 IsFixed, PrevEnum)) 15641 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15642 } 15643 15644 // C++11 [class.mem]p1: 15645 // A member shall not be declared twice in the member-specification, 15646 // except that a nested class or member class template can be declared 15647 // and then later defined. 15648 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15649 S->isDeclScope(PrevDecl)) { 15650 Diag(NameLoc, diag::ext_member_redeclared); 15651 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15652 } 15653 15654 if (!Invalid) { 15655 // If this is a use, just return the declaration we found, unless 15656 // we have attributes. 15657 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15658 if (!Attrs.empty()) { 15659 // FIXME: Diagnose these attributes. For now, we create a new 15660 // declaration to hold them. 15661 } else if (TUK == TUK_Reference && 15662 (PrevTagDecl->getFriendObjectKind() == 15663 Decl::FOK_Undeclared || 15664 PrevDecl->getOwningModule() != getCurrentModule()) && 15665 SS.isEmpty()) { 15666 // This declaration is a reference to an existing entity, but 15667 // has different visibility from that entity: it either makes 15668 // a friend visible or it makes a type visible in a new module. 15669 // In either case, create a new declaration. We only do this if 15670 // the declaration would have meant the same thing if no prior 15671 // declaration were found, that is, if it was found in the same 15672 // scope where we would have injected a declaration. 15673 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15674 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15675 return PrevTagDecl; 15676 // This is in the injected scope, create a new declaration in 15677 // that scope. 15678 S = getTagInjectionScope(S, getLangOpts()); 15679 } else { 15680 return PrevTagDecl; 15681 } 15682 } 15683 15684 // Diagnose attempts to redefine a tag. 15685 if (TUK == TUK_Definition) { 15686 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15687 // If we're defining a specialization and the previous definition 15688 // is from an implicit instantiation, don't emit an error 15689 // here; we'll catch this in the general case below. 15690 bool IsExplicitSpecializationAfterInstantiation = false; 15691 if (isMemberSpecialization) { 15692 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15693 IsExplicitSpecializationAfterInstantiation = 15694 RD->getTemplateSpecializationKind() != 15695 TSK_ExplicitSpecialization; 15696 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15697 IsExplicitSpecializationAfterInstantiation = 15698 ED->getTemplateSpecializationKind() != 15699 TSK_ExplicitSpecialization; 15700 } 15701 15702 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15703 // not keep more that one definition around (merge them). However, 15704 // ensure the decl passes the structural compatibility check in 15705 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15706 NamedDecl *Hidden = nullptr; 15707 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15708 // There is a definition of this tag, but it is not visible. We 15709 // explicitly make use of C++'s one definition rule here, and 15710 // assume that this definition is identical to the hidden one 15711 // we already have. Make the existing definition visible and 15712 // use it in place of this one. 15713 if (!getLangOpts().CPlusPlus) { 15714 // Postpone making the old definition visible until after we 15715 // complete parsing the new one and do the structural 15716 // comparison. 15717 SkipBody->CheckSameAsPrevious = true; 15718 SkipBody->New = createTagFromNewDecl(); 15719 SkipBody->Previous = Def; 15720 return Def; 15721 } else { 15722 SkipBody->ShouldSkip = true; 15723 SkipBody->Previous = Def; 15724 makeMergedDefinitionVisible(Hidden); 15725 // Carry on and handle it like a normal definition. We'll 15726 // skip starting the definitiion later. 15727 } 15728 } else if (!IsExplicitSpecializationAfterInstantiation) { 15729 // A redeclaration in function prototype scope in C isn't 15730 // visible elsewhere, so merely issue a warning. 15731 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15732 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15733 else 15734 Diag(NameLoc, diag::err_redefinition) << Name; 15735 notePreviousDefinition(Def, 15736 NameLoc.isValid() ? NameLoc : KWLoc); 15737 // If this is a redefinition, recover by making this 15738 // struct be anonymous, which will make any later 15739 // references get the previous definition. 15740 Name = nullptr; 15741 Previous.clear(); 15742 Invalid = true; 15743 } 15744 } else { 15745 // If the type is currently being defined, complain 15746 // about a nested redefinition. 15747 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15748 if (TD->isBeingDefined()) { 15749 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15750 Diag(PrevTagDecl->getLocation(), 15751 diag::note_previous_definition); 15752 Name = nullptr; 15753 Previous.clear(); 15754 Invalid = true; 15755 } 15756 } 15757 15758 // Okay, this is definition of a previously declared or referenced 15759 // tag. We're going to create a new Decl for it. 15760 } 15761 15762 // Okay, we're going to make a redeclaration. If this is some kind 15763 // of reference, make sure we build the redeclaration in the same DC 15764 // as the original, and ignore the current access specifier. 15765 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15766 SearchDC = PrevTagDecl->getDeclContext(); 15767 AS = AS_none; 15768 } 15769 } 15770 // If we get here we have (another) forward declaration or we 15771 // have a definition. Just create a new decl. 15772 15773 } else { 15774 // If we get here, this is a definition of a new tag type in a nested 15775 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15776 // new decl/type. We set PrevDecl to NULL so that the entities 15777 // have distinct types. 15778 Previous.clear(); 15779 } 15780 // If we get here, we're going to create a new Decl. If PrevDecl 15781 // is non-NULL, it's a definition of the tag declared by 15782 // PrevDecl. If it's NULL, we have a new definition. 15783 15784 // Otherwise, PrevDecl is not a tag, but was found with tag 15785 // lookup. This is only actually possible in C++, where a few 15786 // things like templates still live in the tag namespace. 15787 } else { 15788 // Use a better diagnostic if an elaborated-type-specifier 15789 // found the wrong kind of type on the first 15790 // (non-redeclaration) lookup. 15791 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15792 !Previous.isForRedeclaration()) { 15793 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15794 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15795 << Kind; 15796 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15797 Invalid = true; 15798 15799 // Otherwise, only diagnose if the declaration is in scope. 15800 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15801 SS.isNotEmpty() || isMemberSpecialization)) { 15802 // do nothing 15803 15804 // Diagnose implicit declarations introduced by elaborated types. 15805 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15806 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15807 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15808 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15809 Invalid = true; 15810 15811 // Otherwise it's a declaration. Call out a particularly common 15812 // case here. 15813 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15814 unsigned Kind = 0; 15815 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15816 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15817 << Name << Kind << TND->getUnderlyingType(); 15818 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15819 Invalid = true; 15820 15821 // Otherwise, diagnose. 15822 } else { 15823 // The tag name clashes with something else in the target scope, 15824 // issue an error and recover by making this tag be anonymous. 15825 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15826 notePreviousDefinition(PrevDecl, NameLoc); 15827 Name = nullptr; 15828 Invalid = true; 15829 } 15830 15831 // The existing declaration isn't relevant to us; we're in a 15832 // new scope, so clear out the previous declaration. 15833 Previous.clear(); 15834 } 15835 } 15836 15837 CreateNewDecl: 15838 15839 TagDecl *PrevDecl = nullptr; 15840 if (Previous.isSingleResult()) 15841 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15842 15843 // If there is an identifier, use the location of the identifier as the 15844 // location of the decl, otherwise use the location of the struct/union 15845 // keyword. 15846 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15847 15848 // Otherwise, create a new declaration. If there is a previous 15849 // declaration of the same entity, the two will be linked via 15850 // PrevDecl. 15851 TagDecl *New; 15852 15853 if (Kind == TTK_Enum) { 15854 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15855 // enum X { A, B, C } D; D should chain to X. 15856 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15857 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15858 ScopedEnumUsesClassTag, IsFixed); 15859 15860 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15861 StdAlignValT = cast<EnumDecl>(New); 15862 15863 // If this is an undefined enum, warn. 15864 if (TUK != TUK_Definition && !Invalid) { 15865 TagDecl *Def; 15866 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15867 // C++0x: 7.2p2: opaque-enum-declaration. 15868 // Conflicts are diagnosed above. Do nothing. 15869 } 15870 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15871 Diag(Loc, diag::ext_forward_ref_enum_def) 15872 << New; 15873 Diag(Def->getLocation(), diag::note_previous_definition); 15874 } else { 15875 unsigned DiagID = diag::ext_forward_ref_enum; 15876 if (getLangOpts().MSVCCompat) 15877 DiagID = diag::ext_ms_forward_ref_enum; 15878 else if (getLangOpts().CPlusPlus) 15879 DiagID = diag::err_forward_ref_enum; 15880 Diag(Loc, DiagID); 15881 } 15882 } 15883 15884 if (EnumUnderlying) { 15885 EnumDecl *ED = cast<EnumDecl>(New); 15886 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15887 ED->setIntegerTypeSourceInfo(TI); 15888 else 15889 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15890 ED->setPromotionType(ED->getIntegerType()); 15891 assert(ED->isComplete() && "enum with type should be complete"); 15892 } 15893 } else { 15894 // struct/union/class 15895 15896 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15897 // struct X { int A; } D; D should chain to X. 15898 if (getLangOpts().CPlusPlus) { 15899 // FIXME: Look for a way to use RecordDecl for simple structs. 15900 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15901 cast_or_null<CXXRecordDecl>(PrevDecl)); 15902 15903 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15904 StdBadAlloc = cast<CXXRecordDecl>(New); 15905 } else 15906 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15907 cast_or_null<RecordDecl>(PrevDecl)); 15908 } 15909 15910 // C++11 [dcl.type]p3: 15911 // A type-specifier-seq shall not define a class or enumeration [...]. 15912 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15913 TUK == TUK_Definition) { 15914 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15915 << Context.getTagDeclType(New); 15916 Invalid = true; 15917 } 15918 15919 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15920 DC->getDeclKind() == Decl::Enum) { 15921 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15922 << Context.getTagDeclType(New); 15923 Invalid = true; 15924 } 15925 15926 // Maybe add qualifier info. 15927 if (SS.isNotEmpty()) { 15928 if (SS.isSet()) { 15929 // If this is either a declaration or a definition, check the 15930 // nested-name-specifier against the current context. 15931 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15932 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15933 isMemberSpecialization)) 15934 Invalid = true; 15935 15936 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15937 if (TemplateParameterLists.size() > 0) { 15938 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15939 } 15940 } 15941 else 15942 Invalid = true; 15943 } 15944 15945 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15946 // Add alignment attributes if necessary; these attributes are checked when 15947 // the ASTContext lays out the structure. 15948 // 15949 // It is important for implementing the correct semantics that this 15950 // happen here (in ActOnTag). The #pragma pack stack is 15951 // maintained as a result of parser callbacks which can occur at 15952 // many points during the parsing of a struct declaration (because 15953 // the #pragma tokens are effectively skipped over during the 15954 // parsing of the struct). 15955 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15956 AddAlignmentAttributesForRecord(RD); 15957 AddMsStructLayoutForRecord(RD); 15958 } 15959 } 15960 15961 if (ModulePrivateLoc.isValid()) { 15962 if (isMemberSpecialization) 15963 Diag(New->getLocation(), diag::err_module_private_specialization) 15964 << 2 15965 << FixItHint::CreateRemoval(ModulePrivateLoc); 15966 // __module_private__ does not apply to local classes. However, we only 15967 // diagnose this as an error when the declaration specifiers are 15968 // freestanding. Here, we just ignore the __module_private__. 15969 else if (!SearchDC->isFunctionOrMethod()) 15970 New->setModulePrivate(); 15971 } 15972 15973 // If this is a specialization of a member class (of a class template), 15974 // check the specialization. 15975 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15976 Invalid = true; 15977 15978 // If we're declaring or defining a tag in function prototype scope in C, 15979 // note that this type can only be used within the function and add it to 15980 // the list of decls to inject into the function definition scope. 15981 if ((Name || Kind == TTK_Enum) && 15982 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15983 if (getLangOpts().CPlusPlus) { 15984 // C++ [dcl.fct]p6: 15985 // Types shall not be defined in return or parameter types. 15986 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15987 Diag(Loc, diag::err_type_defined_in_param_type) 15988 << Name; 15989 Invalid = true; 15990 } 15991 } else if (!PrevDecl) { 15992 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15993 } 15994 } 15995 15996 if (Invalid) 15997 New->setInvalidDecl(); 15998 15999 // Set the lexical context. If the tag has a C++ scope specifier, the 16000 // lexical context will be different from the semantic context. 16001 New->setLexicalDeclContext(CurContext); 16002 16003 // Mark this as a friend decl if applicable. 16004 // In Microsoft mode, a friend declaration also acts as a forward 16005 // declaration so we always pass true to setObjectOfFriendDecl to make 16006 // the tag name visible. 16007 if (TUK == TUK_Friend) 16008 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16009 16010 // Set the access specifier. 16011 if (!Invalid && SearchDC->isRecord()) 16012 SetMemberAccessSpecifier(New, PrevDecl, AS); 16013 16014 if (PrevDecl) 16015 CheckRedeclarationModuleOwnership(New, PrevDecl); 16016 16017 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16018 New->startDefinition(); 16019 16020 ProcessDeclAttributeList(S, New, Attrs); 16021 AddPragmaAttributes(S, New); 16022 16023 // If this has an identifier, add it to the scope stack. 16024 if (TUK == TUK_Friend) { 16025 // We might be replacing an existing declaration in the lookup tables; 16026 // if so, borrow its access specifier. 16027 if (PrevDecl) 16028 New->setAccess(PrevDecl->getAccess()); 16029 16030 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16031 DC->makeDeclVisibleInContext(New); 16032 if (Name) // can be null along some error paths 16033 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16034 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16035 } else if (Name) { 16036 S = getNonFieldDeclScope(S); 16037 PushOnScopeChains(New, S, true); 16038 } else { 16039 CurContext->addDecl(New); 16040 } 16041 16042 // If this is the C FILE type, notify the AST context. 16043 if (IdentifierInfo *II = New->getIdentifier()) 16044 if (!New->isInvalidDecl() && 16045 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16046 II->isStr("FILE")) 16047 Context.setFILEDecl(New); 16048 16049 if (PrevDecl) 16050 mergeDeclAttributes(New, PrevDecl); 16051 16052 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16053 inferGslOwnerPointerAttribute(CXXRD); 16054 16055 // If there's a #pragma GCC visibility in scope, set the visibility of this 16056 // record. 16057 AddPushedVisibilityAttribute(New); 16058 16059 if (isMemberSpecialization && !New->isInvalidDecl()) 16060 CompleteMemberSpecialization(New, Previous); 16061 16062 OwnedDecl = true; 16063 // In C++, don't return an invalid declaration. We can't recover well from 16064 // the cases where we make the type anonymous. 16065 if (Invalid && getLangOpts().CPlusPlus) { 16066 if (New->isBeingDefined()) 16067 if (auto RD = dyn_cast<RecordDecl>(New)) 16068 RD->completeDefinition(); 16069 return nullptr; 16070 } else if (SkipBody && SkipBody->ShouldSkip) { 16071 return SkipBody->Previous; 16072 } else { 16073 return New; 16074 } 16075 } 16076 16077 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16078 AdjustDeclIfTemplate(TagD); 16079 TagDecl *Tag = cast<TagDecl>(TagD); 16080 16081 // Enter the tag context. 16082 PushDeclContext(S, Tag); 16083 16084 ActOnDocumentableDecl(TagD); 16085 16086 // If there's a #pragma GCC visibility in scope, set the visibility of this 16087 // record. 16088 AddPushedVisibilityAttribute(Tag); 16089 } 16090 16091 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16092 SkipBodyInfo &SkipBody) { 16093 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16094 return false; 16095 16096 // Make the previous decl visible. 16097 makeMergedDefinitionVisible(SkipBody.Previous); 16098 return true; 16099 } 16100 16101 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16102 assert(isa<ObjCContainerDecl>(IDecl) && 16103 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16104 DeclContext *OCD = cast<DeclContext>(IDecl); 16105 assert(getContainingDC(OCD) == CurContext && 16106 "The next DeclContext should be lexically contained in the current one."); 16107 CurContext = OCD; 16108 return IDecl; 16109 } 16110 16111 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16112 SourceLocation FinalLoc, 16113 bool IsFinalSpelledSealed, 16114 SourceLocation LBraceLoc) { 16115 AdjustDeclIfTemplate(TagD); 16116 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16117 16118 FieldCollector->StartClass(); 16119 16120 if (!Record->getIdentifier()) 16121 return; 16122 16123 if (FinalLoc.isValid()) 16124 Record->addAttr(FinalAttr::Create( 16125 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16126 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16127 16128 // C++ [class]p2: 16129 // [...] The class-name is also inserted into the scope of the 16130 // class itself; this is known as the injected-class-name. For 16131 // purposes of access checking, the injected-class-name is treated 16132 // as if it were a public member name. 16133 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16134 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16135 Record->getLocation(), Record->getIdentifier(), 16136 /*PrevDecl=*/nullptr, 16137 /*DelayTypeCreation=*/true); 16138 Context.getTypeDeclType(InjectedClassName, Record); 16139 InjectedClassName->setImplicit(); 16140 InjectedClassName->setAccess(AS_public); 16141 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16142 InjectedClassName->setDescribedClassTemplate(Template); 16143 PushOnScopeChains(InjectedClassName, S); 16144 assert(InjectedClassName->isInjectedClassName() && 16145 "Broken injected-class-name"); 16146 } 16147 16148 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16149 SourceRange BraceRange) { 16150 AdjustDeclIfTemplate(TagD); 16151 TagDecl *Tag = cast<TagDecl>(TagD); 16152 Tag->setBraceRange(BraceRange); 16153 16154 // Make sure we "complete" the definition even it is invalid. 16155 if (Tag->isBeingDefined()) { 16156 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16157 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16158 RD->completeDefinition(); 16159 } 16160 16161 if (isa<CXXRecordDecl>(Tag)) { 16162 FieldCollector->FinishClass(); 16163 } 16164 16165 // Exit this scope of this tag's definition. 16166 PopDeclContext(); 16167 16168 if (getCurLexicalContext()->isObjCContainer() && 16169 Tag->getDeclContext()->isFileContext()) 16170 Tag->setTopLevelDeclInObjCContainer(); 16171 16172 // Notify the consumer that we've defined a tag. 16173 if (!Tag->isInvalidDecl()) 16174 Consumer.HandleTagDeclDefinition(Tag); 16175 } 16176 16177 void Sema::ActOnObjCContainerFinishDefinition() { 16178 // Exit this scope of this interface definition. 16179 PopDeclContext(); 16180 } 16181 16182 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16183 assert(DC == CurContext && "Mismatch of container contexts"); 16184 OriginalLexicalContext = DC; 16185 ActOnObjCContainerFinishDefinition(); 16186 } 16187 16188 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16189 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16190 OriginalLexicalContext = nullptr; 16191 } 16192 16193 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16194 AdjustDeclIfTemplate(TagD); 16195 TagDecl *Tag = cast<TagDecl>(TagD); 16196 Tag->setInvalidDecl(); 16197 16198 // Make sure we "complete" the definition even it is invalid. 16199 if (Tag->isBeingDefined()) { 16200 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16201 RD->completeDefinition(); 16202 } 16203 16204 // We're undoing ActOnTagStartDefinition here, not 16205 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16206 // the FieldCollector. 16207 16208 PopDeclContext(); 16209 } 16210 16211 // Note that FieldName may be null for anonymous bitfields. 16212 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16213 IdentifierInfo *FieldName, 16214 QualType FieldTy, bool IsMsStruct, 16215 Expr *BitWidth, bool *ZeroWidth) { 16216 assert(BitWidth); 16217 if (BitWidth->containsErrors()) 16218 return ExprError(); 16219 16220 // Default to true; that shouldn't confuse checks for emptiness 16221 if (ZeroWidth) 16222 *ZeroWidth = true; 16223 16224 // C99 6.7.2.1p4 - verify the field type. 16225 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16226 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16227 // Handle incomplete and sizeless types with a specific error. 16228 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16229 diag::err_field_incomplete_or_sizeless)) 16230 return ExprError(); 16231 if (FieldName) 16232 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16233 << FieldName << FieldTy << BitWidth->getSourceRange(); 16234 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16235 << FieldTy << BitWidth->getSourceRange(); 16236 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16237 UPPC_BitFieldWidth)) 16238 return ExprError(); 16239 16240 // If the bit-width is type- or value-dependent, don't try to check 16241 // it now. 16242 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16243 return BitWidth; 16244 16245 llvm::APSInt Value; 16246 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16247 if (ICE.isInvalid()) 16248 return ICE; 16249 BitWidth = ICE.get(); 16250 16251 if (Value != 0 && ZeroWidth) 16252 *ZeroWidth = false; 16253 16254 // Zero-width bitfield is ok for anonymous field. 16255 if (Value == 0 && FieldName) 16256 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16257 16258 if (Value.isSigned() && Value.isNegative()) { 16259 if (FieldName) 16260 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16261 << FieldName << Value.toString(10); 16262 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16263 << Value.toString(10); 16264 } 16265 16266 if (!FieldTy->isDependentType()) { 16267 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16268 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16269 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16270 16271 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16272 // ABI. 16273 bool CStdConstraintViolation = 16274 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16275 bool MSBitfieldViolation = 16276 Value.ugt(TypeStorageSize) && 16277 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16278 if (CStdConstraintViolation || MSBitfieldViolation) { 16279 unsigned DiagWidth = 16280 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16281 if (FieldName) 16282 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16283 << FieldName << (unsigned)Value.getZExtValue() 16284 << !CStdConstraintViolation << DiagWidth; 16285 16286 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16287 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16288 << DiagWidth; 16289 } 16290 16291 // Warn on types where the user might conceivably expect to get all 16292 // specified bits as value bits: that's all integral types other than 16293 // 'bool'. 16294 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16295 if (FieldName) 16296 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16297 << FieldName << (unsigned)Value.getZExtValue() 16298 << (unsigned)TypeWidth; 16299 else 16300 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16301 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16302 } 16303 } 16304 16305 return BitWidth; 16306 } 16307 16308 /// ActOnField - Each field of a C struct/union is passed into this in order 16309 /// to create a FieldDecl object for it. 16310 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16311 Declarator &D, Expr *BitfieldWidth) { 16312 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16313 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16314 /*InitStyle=*/ICIS_NoInit, AS_public); 16315 return Res; 16316 } 16317 16318 /// HandleField - Analyze a field of a C struct or a C++ data member. 16319 /// 16320 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16321 SourceLocation DeclStart, 16322 Declarator &D, Expr *BitWidth, 16323 InClassInitStyle InitStyle, 16324 AccessSpecifier AS) { 16325 if (D.isDecompositionDeclarator()) { 16326 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16327 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16328 << Decomp.getSourceRange(); 16329 return nullptr; 16330 } 16331 16332 IdentifierInfo *II = D.getIdentifier(); 16333 SourceLocation Loc = DeclStart; 16334 if (II) Loc = D.getIdentifierLoc(); 16335 16336 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16337 QualType T = TInfo->getType(); 16338 if (getLangOpts().CPlusPlus) { 16339 CheckExtraCXXDefaultArguments(D); 16340 16341 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16342 UPPC_DataMemberType)) { 16343 D.setInvalidType(); 16344 T = Context.IntTy; 16345 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16346 } 16347 } 16348 16349 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16350 16351 if (D.getDeclSpec().isInlineSpecified()) 16352 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16353 << getLangOpts().CPlusPlus17; 16354 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16355 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16356 diag::err_invalid_thread) 16357 << DeclSpec::getSpecifierName(TSCS); 16358 16359 // Check to see if this name was declared as a member previously 16360 NamedDecl *PrevDecl = nullptr; 16361 LookupResult Previous(*this, II, Loc, LookupMemberName, 16362 ForVisibleRedeclaration); 16363 LookupName(Previous, S); 16364 switch (Previous.getResultKind()) { 16365 case LookupResult::Found: 16366 case LookupResult::FoundUnresolvedValue: 16367 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16368 break; 16369 16370 case LookupResult::FoundOverloaded: 16371 PrevDecl = Previous.getRepresentativeDecl(); 16372 break; 16373 16374 case LookupResult::NotFound: 16375 case LookupResult::NotFoundInCurrentInstantiation: 16376 case LookupResult::Ambiguous: 16377 break; 16378 } 16379 Previous.suppressDiagnostics(); 16380 16381 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16382 // Maybe we will complain about the shadowed template parameter. 16383 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16384 // Just pretend that we didn't see the previous declaration. 16385 PrevDecl = nullptr; 16386 } 16387 16388 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16389 PrevDecl = nullptr; 16390 16391 bool Mutable 16392 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16393 SourceLocation TSSL = D.getBeginLoc(); 16394 FieldDecl *NewFD 16395 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16396 TSSL, AS, PrevDecl, &D); 16397 16398 if (NewFD->isInvalidDecl()) 16399 Record->setInvalidDecl(); 16400 16401 if (D.getDeclSpec().isModulePrivateSpecified()) 16402 NewFD->setModulePrivate(); 16403 16404 if (NewFD->isInvalidDecl() && PrevDecl) { 16405 // Don't introduce NewFD into scope; there's already something 16406 // with the same name in the same scope. 16407 } else if (II) { 16408 PushOnScopeChains(NewFD, S); 16409 } else 16410 Record->addDecl(NewFD); 16411 16412 return NewFD; 16413 } 16414 16415 /// Build a new FieldDecl and check its well-formedness. 16416 /// 16417 /// This routine builds a new FieldDecl given the fields name, type, 16418 /// record, etc. \p PrevDecl should refer to any previous declaration 16419 /// with the same name and in the same scope as the field to be 16420 /// created. 16421 /// 16422 /// \returns a new FieldDecl. 16423 /// 16424 /// \todo The Declarator argument is a hack. It will be removed once 16425 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16426 TypeSourceInfo *TInfo, 16427 RecordDecl *Record, SourceLocation Loc, 16428 bool Mutable, Expr *BitWidth, 16429 InClassInitStyle InitStyle, 16430 SourceLocation TSSL, 16431 AccessSpecifier AS, NamedDecl *PrevDecl, 16432 Declarator *D) { 16433 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16434 bool InvalidDecl = false; 16435 if (D) InvalidDecl = D->isInvalidType(); 16436 16437 // If we receive a broken type, recover by assuming 'int' and 16438 // marking this declaration as invalid. 16439 if (T.isNull()) { 16440 InvalidDecl = true; 16441 T = Context.IntTy; 16442 } 16443 16444 QualType EltTy = Context.getBaseElementType(T); 16445 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16446 if (RequireCompleteSizedType(Loc, EltTy, 16447 diag::err_field_incomplete_or_sizeless)) { 16448 // Fields of incomplete type force their record to be invalid. 16449 Record->setInvalidDecl(); 16450 InvalidDecl = true; 16451 } else { 16452 NamedDecl *Def; 16453 EltTy->isIncompleteType(&Def); 16454 if (Def && Def->isInvalidDecl()) { 16455 Record->setInvalidDecl(); 16456 InvalidDecl = true; 16457 } 16458 } 16459 } 16460 16461 // TR 18037 does not allow fields to be declared with address space 16462 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16463 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16464 Diag(Loc, diag::err_field_with_address_space); 16465 Record->setInvalidDecl(); 16466 InvalidDecl = true; 16467 } 16468 16469 if (LangOpts.OpenCL) { 16470 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16471 // used as structure or union field: image, sampler, event or block types. 16472 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16473 T->isBlockPointerType()) { 16474 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16475 Record->setInvalidDecl(); 16476 InvalidDecl = true; 16477 } 16478 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16479 if (BitWidth) { 16480 Diag(Loc, diag::err_opencl_bitfields); 16481 InvalidDecl = true; 16482 } 16483 } 16484 16485 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16486 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16487 T.hasQualifiers()) { 16488 InvalidDecl = true; 16489 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16490 } 16491 16492 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16493 // than a variably modified type. 16494 if (!InvalidDecl && T->isVariablyModifiedType()) { 16495 bool SizeIsNegative; 16496 llvm::APSInt Oversized; 16497 16498 TypeSourceInfo *FixedTInfo = 16499 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16500 SizeIsNegative, 16501 Oversized); 16502 if (FixedTInfo) { 16503 Diag(Loc, diag::warn_illegal_constant_array_size); 16504 TInfo = FixedTInfo; 16505 T = FixedTInfo->getType(); 16506 } else { 16507 if (SizeIsNegative) 16508 Diag(Loc, diag::err_typecheck_negative_array_size); 16509 else if (Oversized.getBoolValue()) 16510 Diag(Loc, diag::err_array_too_large) 16511 << Oversized.toString(10); 16512 else 16513 Diag(Loc, diag::err_typecheck_field_variable_size); 16514 InvalidDecl = true; 16515 } 16516 } 16517 16518 // Fields can not have abstract class types 16519 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16520 diag::err_abstract_type_in_decl, 16521 AbstractFieldType)) 16522 InvalidDecl = true; 16523 16524 bool ZeroWidth = false; 16525 if (InvalidDecl) 16526 BitWidth = nullptr; 16527 // If this is declared as a bit-field, check the bit-field. 16528 if (BitWidth) { 16529 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16530 &ZeroWidth).get(); 16531 if (!BitWidth) { 16532 InvalidDecl = true; 16533 BitWidth = nullptr; 16534 ZeroWidth = false; 16535 } 16536 16537 // Only data members can have in-class initializers. 16538 if (BitWidth && !II && InitStyle) { 16539 Diag(Loc, diag::err_anon_bitfield_init); 16540 InvalidDecl = true; 16541 BitWidth = nullptr; 16542 ZeroWidth = false; 16543 } 16544 } 16545 16546 // Check that 'mutable' is consistent with the type of the declaration. 16547 if (!InvalidDecl && Mutable) { 16548 unsigned DiagID = 0; 16549 if (T->isReferenceType()) 16550 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16551 : diag::err_mutable_reference; 16552 else if (T.isConstQualified()) 16553 DiagID = diag::err_mutable_const; 16554 16555 if (DiagID) { 16556 SourceLocation ErrLoc = Loc; 16557 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16558 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16559 Diag(ErrLoc, DiagID); 16560 if (DiagID != diag::ext_mutable_reference) { 16561 Mutable = false; 16562 InvalidDecl = true; 16563 } 16564 } 16565 } 16566 16567 // C++11 [class.union]p8 (DR1460): 16568 // At most one variant member of a union may have a 16569 // brace-or-equal-initializer. 16570 if (InitStyle != ICIS_NoInit) 16571 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16572 16573 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16574 BitWidth, Mutable, InitStyle); 16575 if (InvalidDecl) 16576 NewFD->setInvalidDecl(); 16577 16578 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16579 Diag(Loc, diag::err_duplicate_member) << II; 16580 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16581 NewFD->setInvalidDecl(); 16582 } 16583 16584 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16585 if (Record->isUnion()) { 16586 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16587 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16588 if (RDecl->getDefinition()) { 16589 // C++ [class.union]p1: An object of a class with a non-trivial 16590 // constructor, a non-trivial copy constructor, a non-trivial 16591 // destructor, or a non-trivial copy assignment operator 16592 // cannot be a member of a union, nor can an array of such 16593 // objects. 16594 if (CheckNontrivialField(NewFD)) 16595 NewFD->setInvalidDecl(); 16596 } 16597 } 16598 16599 // C++ [class.union]p1: If a union contains a member of reference type, 16600 // the program is ill-formed, except when compiling with MSVC extensions 16601 // enabled. 16602 if (EltTy->isReferenceType()) { 16603 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16604 diag::ext_union_member_of_reference_type : 16605 diag::err_union_member_of_reference_type) 16606 << NewFD->getDeclName() << EltTy; 16607 if (!getLangOpts().MicrosoftExt) 16608 NewFD->setInvalidDecl(); 16609 } 16610 } 16611 } 16612 16613 // FIXME: We need to pass in the attributes given an AST 16614 // representation, not a parser representation. 16615 if (D) { 16616 // FIXME: The current scope is almost... but not entirely... correct here. 16617 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16618 16619 if (NewFD->hasAttrs()) 16620 CheckAlignasUnderalignment(NewFD); 16621 } 16622 16623 // In auto-retain/release, infer strong retension for fields of 16624 // retainable type. 16625 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16626 NewFD->setInvalidDecl(); 16627 16628 if (T.isObjCGCWeak()) 16629 Diag(Loc, diag::warn_attribute_weak_on_field); 16630 16631 NewFD->setAccess(AS); 16632 return NewFD; 16633 } 16634 16635 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16636 assert(FD); 16637 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16638 16639 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16640 return false; 16641 16642 QualType EltTy = Context.getBaseElementType(FD->getType()); 16643 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16644 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16645 if (RDecl->getDefinition()) { 16646 // We check for copy constructors before constructors 16647 // because otherwise we'll never get complaints about 16648 // copy constructors. 16649 16650 CXXSpecialMember member = CXXInvalid; 16651 // We're required to check for any non-trivial constructors. Since the 16652 // implicit default constructor is suppressed if there are any 16653 // user-declared constructors, we just need to check that there is a 16654 // trivial default constructor and a trivial copy constructor. (We don't 16655 // worry about move constructors here, since this is a C++98 check.) 16656 if (RDecl->hasNonTrivialCopyConstructor()) 16657 member = CXXCopyConstructor; 16658 else if (!RDecl->hasTrivialDefaultConstructor()) 16659 member = CXXDefaultConstructor; 16660 else if (RDecl->hasNonTrivialCopyAssignment()) 16661 member = CXXCopyAssignment; 16662 else if (RDecl->hasNonTrivialDestructor()) 16663 member = CXXDestructor; 16664 16665 if (member != CXXInvalid) { 16666 if (!getLangOpts().CPlusPlus11 && 16667 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16668 // Objective-C++ ARC: it is an error to have a non-trivial field of 16669 // a union. However, system headers in Objective-C programs 16670 // occasionally have Objective-C lifetime objects within unions, 16671 // and rather than cause the program to fail, we make those 16672 // members unavailable. 16673 SourceLocation Loc = FD->getLocation(); 16674 if (getSourceManager().isInSystemHeader(Loc)) { 16675 if (!FD->hasAttr<UnavailableAttr>()) 16676 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16677 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16678 return false; 16679 } 16680 } 16681 16682 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16683 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16684 diag::err_illegal_union_or_anon_struct_member) 16685 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16686 DiagnoseNontrivial(RDecl, member); 16687 return !getLangOpts().CPlusPlus11; 16688 } 16689 } 16690 } 16691 16692 return false; 16693 } 16694 16695 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16696 /// AST enum value. 16697 static ObjCIvarDecl::AccessControl 16698 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16699 switch (ivarVisibility) { 16700 default: llvm_unreachable("Unknown visitibility kind"); 16701 case tok::objc_private: return ObjCIvarDecl::Private; 16702 case tok::objc_public: return ObjCIvarDecl::Public; 16703 case tok::objc_protected: return ObjCIvarDecl::Protected; 16704 case tok::objc_package: return ObjCIvarDecl::Package; 16705 } 16706 } 16707 16708 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16709 /// in order to create an IvarDecl object for it. 16710 Decl *Sema::ActOnIvar(Scope *S, 16711 SourceLocation DeclStart, 16712 Declarator &D, Expr *BitfieldWidth, 16713 tok::ObjCKeywordKind Visibility) { 16714 16715 IdentifierInfo *II = D.getIdentifier(); 16716 Expr *BitWidth = (Expr*)BitfieldWidth; 16717 SourceLocation Loc = DeclStart; 16718 if (II) Loc = D.getIdentifierLoc(); 16719 16720 // FIXME: Unnamed fields can be handled in various different ways, for 16721 // example, unnamed unions inject all members into the struct namespace! 16722 16723 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16724 QualType T = TInfo->getType(); 16725 16726 if (BitWidth) { 16727 // 6.7.2.1p3, 6.7.2.1p4 16728 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16729 if (!BitWidth) 16730 D.setInvalidType(); 16731 } else { 16732 // Not a bitfield. 16733 16734 // validate II. 16735 16736 } 16737 if (T->isReferenceType()) { 16738 Diag(Loc, diag::err_ivar_reference_type); 16739 D.setInvalidType(); 16740 } 16741 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16742 // than a variably modified type. 16743 else if (T->isVariablyModifiedType()) { 16744 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16745 D.setInvalidType(); 16746 } 16747 16748 // Get the visibility (access control) for this ivar. 16749 ObjCIvarDecl::AccessControl ac = 16750 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16751 : ObjCIvarDecl::None; 16752 // Must set ivar's DeclContext to its enclosing interface. 16753 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16754 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16755 return nullptr; 16756 ObjCContainerDecl *EnclosingContext; 16757 if (ObjCImplementationDecl *IMPDecl = 16758 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16759 if (LangOpts.ObjCRuntime.isFragile()) { 16760 // Case of ivar declared in an implementation. Context is that of its class. 16761 EnclosingContext = IMPDecl->getClassInterface(); 16762 assert(EnclosingContext && "Implementation has no class interface!"); 16763 } 16764 else 16765 EnclosingContext = EnclosingDecl; 16766 } else { 16767 if (ObjCCategoryDecl *CDecl = 16768 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16769 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16770 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16771 return nullptr; 16772 } 16773 } 16774 EnclosingContext = EnclosingDecl; 16775 } 16776 16777 // Construct the decl. 16778 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16779 DeclStart, Loc, II, T, 16780 TInfo, ac, (Expr *)BitfieldWidth); 16781 16782 if (II) { 16783 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16784 ForVisibleRedeclaration); 16785 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16786 && !isa<TagDecl>(PrevDecl)) { 16787 Diag(Loc, diag::err_duplicate_member) << II; 16788 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16789 NewID->setInvalidDecl(); 16790 } 16791 } 16792 16793 // Process attributes attached to the ivar. 16794 ProcessDeclAttributes(S, NewID, D); 16795 16796 if (D.isInvalidType()) 16797 NewID->setInvalidDecl(); 16798 16799 // In ARC, infer 'retaining' for ivars of retainable type. 16800 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16801 NewID->setInvalidDecl(); 16802 16803 if (D.getDeclSpec().isModulePrivateSpecified()) 16804 NewID->setModulePrivate(); 16805 16806 if (II) { 16807 // FIXME: When interfaces are DeclContexts, we'll need to add 16808 // these to the interface. 16809 S->AddDecl(NewID); 16810 IdResolver.AddDecl(NewID); 16811 } 16812 16813 if (LangOpts.ObjCRuntime.isNonFragile() && 16814 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16815 Diag(Loc, diag::warn_ivars_in_interface); 16816 16817 return NewID; 16818 } 16819 16820 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16821 /// class and class extensions. For every class \@interface and class 16822 /// extension \@interface, if the last ivar is a bitfield of any type, 16823 /// then add an implicit `char :0` ivar to the end of that interface. 16824 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16825 SmallVectorImpl<Decl *> &AllIvarDecls) { 16826 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16827 return; 16828 16829 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16830 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16831 16832 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16833 return; 16834 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16835 if (!ID) { 16836 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16837 if (!CD->IsClassExtension()) 16838 return; 16839 } 16840 // No need to add this to end of @implementation. 16841 else 16842 return; 16843 } 16844 // All conditions are met. Add a new bitfield to the tail end of ivars. 16845 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16846 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16847 16848 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16849 DeclLoc, DeclLoc, nullptr, 16850 Context.CharTy, 16851 Context.getTrivialTypeSourceInfo(Context.CharTy, 16852 DeclLoc), 16853 ObjCIvarDecl::Private, BW, 16854 true); 16855 AllIvarDecls.push_back(Ivar); 16856 } 16857 16858 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16859 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16860 SourceLocation RBrac, 16861 const ParsedAttributesView &Attrs) { 16862 assert(EnclosingDecl && "missing record or interface decl"); 16863 16864 // If this is an Objective-C @implementation or category and we have 16865 // new fields here we should reset the layout of the interface since 16866 // it will now change. 16867 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16868 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16869 switch (DC->getKind()) { 16870 default: break; 16871 case Decl::ObjCCategory: 16872 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16873 break; 16874 case Decl::ObjCImplementation: 16875 Context. 16876 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16877 break; 16878 } 16879 } 16880 16881 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16882 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16883 16884 // Start counting up the number of named members; make sure to include 16885 // members of anonymous structs and unions in the total. 16886 unsigned NumNamedMembers = 0; 16887 if (Record) { 16888 for (const auto *I : Record->decls()) { 16889 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16890 if (IFD->getDeclName()) 16891 ++NumNamedMembers; 16892 } 16893 } 16894 16895 // Verify that all the fields are okay. 16896 SmallVector<FieldDecl*, 32> RecFields; 16897 16898 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16899 i != end; ++i) { 16900 FieldDecl *FD = cast<FieldDecl>(*i); 16901 16902 // Get the type for the field. 16903 const Type *FDTy = FD->getType().getTypePtr(); 16904 16905 if (!FD->isAnonymousStructOrUnion()) { 16906 // Remember all fields written by the user. 16907 RecFields.push_back(FD); 16908 } 16909 16910 // If the field is already invalid for some reason, don't emit more 16911 // diagnostics about it. 16912 if (FD->isInvalidDecl()) { 16913 EnclosingDecl->setInvalidDecl(); 16914 continue; 16915 } 16916 16917 // C99 6.7.2.1p2: 16918 // A structure or union shall not contain a member with 16919 // incomplete or function type (hence, a structure shall not 16920 // contain an instance of itself, but may contain a pointer to 16921 // an instance of itself), except that the last member of a 16922 // structure with more than one named member may have incomplete 16923 // array type; such a structure (and any union containing, 16924 // possibly recursively, a member that is such a structure) 16925 // shall not be a member of a structure or an element of an 16926 // array. 16927 bool IsLastField = (i + 1 == Fields.end()); 16928 if (FDTy->isFunctionType()) { 16929 // Field declared as a function. 16930 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16931 << FD->getDeclName(); 16932 FD->setInvalidDecl(); 16933 EnclosingDecl->setInvalidDecl(); 16934 continue; 16935 } else if (FDTy->isIncompleteArrayType() && 16936 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16937 if (Record) { 16938 // Flexible array member. 16939 // Microsoft and g++ is more permissive regarding flexible array. 16940 // It will accept flexible array in union and also 16941 // as the sole element of a struct/class. 16942 unsigned DiagID = 0; 16943 if (!Record->isUnion() && !IsLastField) { 16944 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16945 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16946 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16947 FD->setInvalidDecl(); 16948 EnclosingDecl->setInvalidDecl(); 16949 continue; 16950 } else if (Record->isUnion()) 16951 DiagID = getLangOpts().MicrosoftExt 16952 ? diag::ext_flexible_array_union_ms 16953 : getLangOpts().CPlusPlus 16954 ? diag::ext_flexible_array_union_gnu 16955 : diag::err_flexible_array_union; 16956 else if (NumNamedMembers < 1) 16957 DiagID = getLangOpts().MicrosoftExt 16958 ? diag::ext_flexible_array_empty_aggregate_ms 16959 : getLangOpts().CPlusPlus 16960 ? diag::ext_flexible_array_empty_aggregate_gnu 16961 : diag::err_flexible_array_empty_aggregate; 16962 16963 if (DiagID) 16964 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16965 << Record->getTagKind(); 16966 // While the layout of types that contain virtual bases is not specified 16967 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16968 // virtual bases after the derived members. This would make a flexible 16969 // array member declared at the end of an object not adjacent to the end 16970 // of the type. 16971 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16972 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16973 << FD->getDeclName() << Record->getTagKind(); 16974 if (!getLangOpts().C99) 16975 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16976 << FD->getDeclName() << Record->getTagKind(); 16977 16978 // If the element type has a non-trivial destructor, we would not 16979 // implicitly destroy the elements, so disallow it for now. 16980 // 16981 // FIXME: GCC allows this. We should probably either implicitly delete 16982 // the destructor of the containing class, or just allow this. 16983 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16984 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16985 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16986 << FD->getDeclName() << FD->getType(); 16987 FD->setInvalidDecl(); 16988 EnclosingDecl->setInvalidDecl(); 16989 continue; 16990 } 16991 // Okay, we have a legal flexible array member at the end of the struct. 16992 Record->setHasFlexibleArrayMember(true); 16993 } else { 16994 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16995 // unless they are followed by another ivar. That check is done 16996 // elsewhere, after synthesized ivars are known. 16997 } 16998 } else if (!FDTy->isDependentType() && 16999 RequireCompleteSizedType( 17000 FD->getLocation(), FD->getType(), 17001 diag::err_field_incomplete_or_sizeless)) { 17002 // Incomplete type 17003 FD->setInvalidDecl(); 17004 EnclosingDecl->setInvalidDecl(); 17005 continue; 17006 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17007 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17008 // A type which contains a flexible array member is considered to be a 17009 // flexible array member. 17010 Record->setHasFlexibleArrayMember(true); 17011 if (!Record->isUnion()) { 17012 // If this is a struct/class and this is not the last element, reject 17013 // it. Note that GCC supports variable sized arrays in the middle of 17014 // structures. 17015 if (!IsLastField) 17016 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17017 << FD->getDeclName() << FD->getType(); 17018 else { 17019 // We support flexible arrays at the end of structs in 17020 // other structs as an extension. 17021 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17022 << FD->getDeclName(); 17023 } 17024 } 17025 } 17026 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17027 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17028 diag::err_abstract_type_in_decl, 17029 AbstractIvarType)) { 17030 // Ivars can not have abstract class types 17031 FD->setInvalidDecl(); 17032 } 17033 if (Record && FDTTy->getDecl()->hasObjectMember()) 17034 Record->setHasObjectMember(true); 17035 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17036 Record->setHasVolatileMember(true); 17037 } else if (FDTy->isObjCObjectType()) { 17038 /// A field cannot be an Objective-c object 17039 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17040 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17041 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17042 FD->setType(T); 17043 } else if (Record && Record->isUnion() && 17044 FD->getType().hasNonTrivialObjCLifetime() && 17045 getSourceManager().isInSystemHeader(FD->getLocation()) && 17046 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17047 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17048 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17049 // For backward compatibility, fields of C unions declared in system 17050 // headers that have non-trivial ObjC ownership qualifications are marked 17051 // as unavailable unless the qualifier is explicit and __strong. This can 17052 // break ABI compatibility between programs compiled with ARC and MRR, but 17053 // is a better option than rejecting programs using those unions under 17054 // ARC. 17055 FD->addAttr(UnavailableAttr::CreateImplicit( 17056 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17057 FD->getLocation())); 17058 } else if (getLangOpts().ObjC && 17059 getLangOpts().getGC() != LangOptions::NonGC && Record && 17060 !Record->hasObjectMember()) { 17061 if (FD->getType()->isObjCObjectPointerType() || 17062 FD->getType().isObjCGCStrong()) 17063 Record->setHasObjectMember(true); 17064 else if (Context.getAsArrayType(FD->getType())) { 17065 QualType BaseType = Context.getBaseElementType(FD->getType()); 17066 if (BaseType->isRecordType() && 17067 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17068 Record->setHasObjectMember(true); 17069 else if (BaseType->isObjCObjectPointerType() || 17070 BaseType.isObjCGCStrong()) 17071 Record->setHasObjectMember(true); 17072 } 17073 } 17074 17075 if (Record && !getLangOpts().CPlusPlus && 17076 !shouldIgnoreForRecordTriviality(FD)) { 17077 QualType FT = FD->getType(); 17078 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17079 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17080 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17081 Record->isUnion()) 17082 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17083 } 17084 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17085 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17086 Record->setNonTrivialToPrimitiveCopy(true); 17087 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17088 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17089 } 17090 if (FT.isDestructedType()) { 17091 Record->setNonTrivialToPrimitiveDestroy(true); 17092 Record->setParamDestroyedInCallee(true); 17093 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17094 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17095 } 17096 17097 if (const auto *RT = FT->getAs<RecordType>()) { 17098 if (RT->getDecl()->getArgPassingRestrictions() == 17099 RecordDecl::APK_CanNeverPassInRegs) 17100 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17101 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17102 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17103 } 17104 17105 if (Record && FD->getType().isVolatileQualified()) 17106 Record->setHasVolatileMember(true); 17107 // Keep track of the number of named members. 17108 if (FD->getIdentifier()) 17109 ++NumNamedMembers; 17110 } 17111 17112 // Okay, we successfully defined 'Record'. 17113 if (Record) { 17114 bool Completed = false; 17115 if (CXXRecord) { 17116 if (!CXXRecord->isInvalidDecl()) { 17117 // Set access bits correctly on the directly-declared conversions. 17118 for (CXXRecordDecl::conversion_iterator 17119 I = CXXRecord->conversion_begin(), 17120 E = CXXRecord->conversion_end(); I != E; ++I) 17121 I.setAccess((*I)->getAccess()); 17122 } 17123 17124 if (!CXXRecord->isDependentType()) { 17125 // Add any implicitly-declared members to this class. 17126 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17127 17128 if (!CXXRecord->isInvalidDecl()) { 17129 // If we have virtual base classes, we may end up finding multiple 17130 // final overriders for a given virtual function. Check for this 17131 // problem now. 17132 if (CXXRecord->getNumVBases()) { 17133 CXXFinalOverriderMap FinalOverriders; 17134 CXXRecord->getFinalOverriders(FinalOverriders); 17135 17136 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17137 MEnd = FinalOverriders.end(); 17138 M != MEnd; ++M) { 17139 for (OverridingMethods::iterator SO = M->second.begin(), 17140 SOEnd = M->second.end(); 17141 SO != SOEnd; ++SO) { 17142 assert(SO->second.size() > 0 && 17143 "Virtual function without overriding functions?"); 17144 if (SO->second.size() == 1) 17145 continue; 17146 17147 // C++ [class.virtual]p2: 17148 // In a derived class, if a virtual member function of a base 17149 // class subobject has more than one final overrider the 17150 // program is ill-formed. 17151 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17152 << (const NamedDecl *)M->first << Record; 17153 Diag(M->first->getLocation(), 17154 diag::note_overridden_virtual_function); 17155 for (OverridingMethods::overriding_iterator 17156 OM = SO->second.begin(), 17157 OMEnd = SO->second.end(); 17158 OM != OMEnd; ++OM) 17159 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17160 << (const NamedDecl *)M->first << OM->Method->getParent(); 17161 17162 Record->setInvalidDecl(); 17163 } 17164 } 17165 CXXRecord->completeDefinition(&FinalOverriders); 17166 Completed = true; 17167 } 17168 } 17169 } 17170 } 17171 17172 if (!Completed) 17173 Record->completeDefinition(); 17174 17175 // Handle attributes before checking the layout. 17176 ProcessDeclAttributeList(S, Record, Attrs); 17177 17178 // We may have deferred checking for a deleted destructor. Check now. 17179 if (CXXRecord) { 17180 auto *Dtor = CXXRecord->getDestructor(); 17181 if (Dtor && Dtor->isImplicit() && 17182 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17183 CXXRecord->setImplicitDestructorIsDeleted(); 17184 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17185 } 17186 } 17187 17188 if (Record->hasAttrs()) { 17189 CheckAlignasUnderalignment(Record); 17190 17191 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17192 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17193 IA->getRange(), IA->getBestCase(), 17194 IA->getInheritanceModel()); 17195 } 17196 17197 // Check if the structure/union declaration is a type that can have zero 17198 // size in C. For C this is a language extension, for C++ it may cause 17199 // compatibility problems. 17200 bool CheckForZeroSize; 17201 if (!getLangOpts().CPlusPlus) { 17202 CheckForZeroSize = true; 17203 } else { 17204 // For C++ filter out types that cannot be referenced in C code. 17205 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17206 CheckForZeroSize = 17207 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17208 !CXXRecord->isDependentType() && 17209 CXXRecord->isCLike(); 17210 } 17211 if (CheckForZeroSize) { 17212 bool ZeroSize = true; 17213 bool IsEmpty = true; 17214 unsigned NonBitFields = 0; 17215 for (RecordDecl::field_iterator I = Record->field_begin(), 17216 E = Record->field_end(); 17217 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17218 IsEmpty = false; 17219 if (I->isUnnamedBitfield()) { 17220 if (!I->isZeroLengthBitField(Context)) 17221 ZeroSize = false; 17222 } else { 17223 ++NonBitFields; 17224 QualType FieldType = I->getType(); 17225 if (FieldType->isIncompleteType() || 17226 !Context.getTypeSizeInChars(FieldType).isZero()) 17227 ZeroSize = false; 17228 } 17229 } 17230 17231 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17232 // allowed in C++, but warn if its declaration is inside 17233 // extern "C" block. 17234 if (ZeroSize) { 17235 Diag(RecLoc, getLangOpts().CPlusPlus ? 17236 diag::warn_zero_size_struct_union_in_extern_c : 17237 diag::warn_zero_size_struct_union_compat) 17238 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17239 } 17240 17241 // Structs without named members are extension in C (C99 6.7.2.1p7), 17242 // but are accepted by GCC. 17243 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17244 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17245 diag::ext_no_named_members_in_struct_union) 17246 << Record->isUnion(); 17247 } 17248 } 17249 } else { 17250 ObjCIvarDecl **ClsFields = 17251 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17252 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17253 ID->setEndOfDefinitionLoc(RBrac); 17254 // Add ivar's to class's DeclContext. 17255 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17256 ClsFields[i]->setLexicalDeclContext(ID); 17257 ID->addDecl(ClsFields[i]); 17258 } 17259 // Must enforce the rule that ivars in the base classes may not be 17260 // duplicates. 17261 if (ID->getSuperClass()) 17262 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17263 } else if (ObjCImplementationDecl *IMPDecl = 17264 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17265 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17266 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17267 // Ivar declared in @implementation never belongs to the implementation. 17268 // Only it is in implementation's lexical context. 17269 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17270 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17271 IMPDecl->setIvarLBraceLoc(LBrac); 17272 IMPDecl->setIvarRBraceLoc(RBrac); 17273 } else if (ObjCCategoryDecl *CDecl = 17274 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17275 // case of ivars in class extension; all other cases have been 17276 // reported as errors elsewhere. 17277 // FIXME. Class extension does not have a LocEnd field. 17278 // CDecl->setLocEnd(RBrac); 17279 // Add ivar's to class extension's DeclContext. 17280 // Diagnose redeclaration of private ivars. 17281 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17282 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17283 if (IDecl) { 17284 if (const ObjCIvarDecl *ClsIvar = 17285 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17286 Diag(ClsFields[i]->getLocation(), 17287 diag::err_duplicate_ivar_declaration); 17288 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17289 continue; 17290 } 17291 for (const auto *Ext : IDecl->known_extensions()) { 17292 if (const ObjCIvarDecl *ClsExtIvar 17293 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17294 Diag(ClsFields[i]->getLocation(), 17295 diag::err_duplicate_ivar_declaration); 17296 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17297 continue; 17298 } 17299 } 17300 } 17301 ClsFields[i]->setLexicalDeclContext(CDecl); 17302 CDecl->addDecl(ClsFields[i]); 17303 } 17304 CDecl->setIvarLBraceLoc(LBrac); 17305 CDecl->setIvarRBraceLoc(RBrac); 17306 } 17307 } 17308 } 17309 17310 /// Determine whether the given integral value is representable within 17311 /// the given type T. 17312 static bool isRepresentableIntegerValue(ASTContext &Context, 17313 llvm::APSInt &Value, 17314 QualType T) { 17315 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17316 "Integral type required!"); 17317 unsigned BitWidth = Context.getIntWidth(T); 17318 17319 if (Value.isUnsigned() || Value.isNonNegative()) { 17320 if (T->isSignedIntegerOrEnumerationType()) 17321 --BitWidth; 17322 return Value.getActiveBits() <= BitWidth; 17323 } 17324 return Value.getMinSignedBits() <= BitWidth; 17325 } 17326 17327 // Given an integral type, return the next larger integral type 17328 // (or a NULL type of no such type exists). 17329 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17330 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17331 // enum checking below. 17332 assert((T->isIntegralType(Context) || 17333 T->isEnumeralType()) && "Integral type required!"); 17334 const unsigned NumTypes = 4; 17335 QualType SignedIntegralTypes[NumTypes] = { 17336 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17337 }; 17338 QualType UnsignedIntegralTypes[NumTypes] = { 17339 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17340 Context.UnsignedLongLongTy 17341 }; 17342 17343 unsigned BitWidth = Context.getTypeSize(T); 17344 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17345 : UnsignedIntegralTypes; 17346 for (unsigned I = 0; I != NumTypes; ++I) 17347 if (Context.getTypeSize(Types[I]) > BitWidth) 17348 return Types[I]; 17349 17350 return QualType(); 17351 } 17352 17353 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17354 EnumConstantDecl *LastEnumConst, 17355 SourceLocation IdLoc, 17356 IdentifierInfo *Id, 17357 Expr *Val) { 17358 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17359 llvm::APSInt EnumVal(IntWidth); 17360 QualType EltTy; 17361 17362 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17363 Val = nullptr; 17364 17365 if (Val) 17366 Val = DefaultLvalueConversion(Val).get(); 17367 17368 if (Val) { 17369 if (Enum->isDependentType() || Val->isTypeDependent()) 17370 EltTy = Context.DependentTy; 17371 else { 17372 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17373 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17374 // constant-expression in the enumerator-definition shall be a converted 17375 // constant expression of the underlying type. 17376 EltTy = Enum->getIntegerType(); 17377 ExprResult Converted = 17378 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17379 CCEK_Enumerator); 17380 if (Converted.isInvalid()) 17381 Val = nullptr; 17382 else 17383 Val = Converted.get(); 17384 } else if (!Val->isValueDependent() && 17385 !(Val = VerifyIntegerConstantExpression(Val, 17386 &EnumVal).get())) { 17387 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17388 } else { 17389 if (Enum->isComplete()) { 17390 EltTy = Enum->getIntegerType(); 17391 17392 // In Obj-C and Microsoft mode, require the enumeration value to be 17393 // representable in the underlying type of the enumeration. In C++11, 17394 // we perform a non-narrowing conversion as part of converted constant 17395 // expression checking. 17396 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17397 if (Context.getTargetInfo() 17398 .getTriple() 17399 .isWindowsMSVCEnvironment()) { 17400 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17401 } else { 17402 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17403 } 17404 } 17405 17406 // Cast to the underlying type. 17407 Val = ImpCastExprToType(Val, EltTy, 17408 EltTy->isBooleanType() ? CK_IntegralToBoolean 17409 : CK_IntegralCast) 17410 .get(); 17411 } else if (getLangOpts().CPlusPlus) { 17412 // C++11 [dcl.enum]p5: 17413 // If the underlying type is not fixed, the type of each enumerator 17414 // is the type of its initializing value: 17415 // - If an initializer is specified for an enumerator, the 17416 // initializing value has the same type as the expression. 17417 EltTy = Val->getType(); 17418 } else { 17419 // C99 6.7.2.2p2: 17420 // The expression that defines the value of an enumeration constant 17421 // shall be an integer constant expression that has a value 17422 // representable as an int. 17423 17424 // Complain if the value is not representable in an int. 17425 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17426 Diag(IdLoc, diag::ext_enum_value_not_int) 17427 << EnumVal.toString(10) << Val->getSourceRange() 17428 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17429 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17430 // Force the type of the expression to 'int'. 17431 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17432 } 17433 EltTy = Val->getType(); 17434 } 17435 } 17436 } 17437 } 17438 17439 if (!Val) { 17440 if (Enum->isDependentType()) 17441 EltTy = Context.DependentTy; 17442 else if (!LastEnumConst) { 17443 // C++0x [dcl.enum]p5: 17444 // If the underlying type is not fixed, the type of each enumerator 17445 // is the type of its initializing value: 17446 // - If no initializer is specified for the first enumerator, the 17447 // initializing value has an unspecified integral type. 17448 // 17449 // GCC uses 'int' for its unspecified integral type, as does 17450 // C99 6.7.2.2p3. 17451 if (Enum->isFixed()) { 17452 EltTy = Enum->getIntegerType(); 17453 } 17454 else { 17455 EltTy = Context.IntTy; 17456 } 17457 } else { 17458 // Assign the last value + 1. 17459 EnumVal = LastEnumConst->getInitVal(); 17460 ++EnumVal; 17461 EltTy = LastEnumConst->getType(); 17462 17463 // Check for overflow on increment. 17464 if (EnumVal < LastEnumConst->getInitVal()) { 17465 // C++0x [dcl.enum]p5: 17466 // If the underlying type is not fixed, the type of each enumerator 17467 // is the type of its initializing value: 17468 // 17469 // - Otherwise the type of the initializing value is the same as 17470 // the type of the initializing value of the preceding enumerator 17471 // unless the incremented value is not representable in that type, 17472 // in which case the type is an unspecified integral type 17473 // sufficient to contain the incremented value. If no such type 17474 // exists, the program is ill-formed. 17475 QualType T = getNextLargerIntegralType(Context, EltTy); 17476 if (T.isNull() || Enum->isFixed()) { 17477 // There is no integral type larger enough to represent this 17478 // value. Complain, then allow the value to wrap around. 17479 EnumVal = LastEnumConst->getInitVal(); 17480 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17481 ++EnumVal; 17482 if (Enum->isFixed()) 17483 // When the underlying type is fixed, this is ill-formed. 17484 Diag(IdLoc, diag::err_enumerator_wrapped) 17485 << EnumVal.toString(10) 17486 << EltTy; 17487 else 17488 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17489 << EnumVal.toString(10); 17490 } else { 17491 EltTy = T; 17492 } 17493 17494 // Retrieve the last enumerator's value, extent that type to the 17495 // type that is supposed to be large enough to represent the incremented 17496 // value, then increment. 17497 EnumVal = LastEnumConst->getInitVal(); 17498 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17499 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17500 ++EnumVal; 17501 17502 // If we're not in C++, diagnose the overflow of enumerator values, 17503 // which in C99 means that the enumerator value is not representable in 17504 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17505 // permits enumerator values that are representable in some larger 17506 // integral type. 17507 if (!getLangOpts().CPlusPlus && !T.isNull()) 17508 Diag(IdLoc, diag::warn_enum_value_overflow); 17509 } else if (!getLangOpts().CPlusPlus && 17510 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17511 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17512 Diag(IdLoc, diag::ext_enum_value_not_int) 17513 << EnumVal.toString(10) << 1; 17514 } 17515 } 17516 } 17517 17518 if (!EltTy->isDependentType()) { 17519 // Make the enumerator value match the signedness and size of the 17520 // enumerator's type. 17521 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17522 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17523 } 17524 17525 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17526 Val, EnumVal); 17527 } 17528 17529 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17530 SourceLocation IILoc) { 17531 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17532 !getLangOpts().CPlusPlus) 17533 return SkipBodyInfo(); 17534 17535 // We have an anonymous enum definition. Look up the first enumerator to 17536 // determine if we should merge the definition with an existing one and 17537 // skip the body. 17538 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17539 forRedeclarationInCurContext()); 17540 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17541 if (!PrevECD) 17542 return SkipBodyInfo(); 17543 17544 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17545 NamedDecl *Hidden; 17546 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17547 SkipBodyInfo Skip; 17548 Skip.Previous = Hidden; 17549 return Skip; 17550 } 17551 17552 return SkipBodyInfo(); 17553 } 17554 17555 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17556 SourceLocation IdLoc, IdentifierInfo *Id, 17557 const ParsedAttributesView &Attrs, 17558 SourceLocation EqualLoc, Expr *Val) { 17559 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17560 EnumConstantDecl *LastEnumConst = 17561 cast_or_null<EnumConstantDecl>(lastEnumConst); 17562 17563 // The scope passed in may not be a decl scope. Zip up the scope tree until 17564 // we find one that is. 17565 S = getNonFieldDeclScope(S); 17566 17567 // Verify that there isn't already something declared with this name in this 17568 // scope. 17569 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17570 LookupName(R, S); 17571 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17572 17573 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17574 // Maybe we will complain about the shadowed template parameter. 17575 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17576 // Just pretend that we didn't see the previous declaration. 17577 PrevDecl = nullptr; 17578 } 17579 17580 // C++ [class.mem]p15: 17581 // If T is the name of a class, then each of the following shall have a name 17582 // different from T: 17583 // - every enumerator of every member of class T that is an unscoped 17584 // enumerated type 17585 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17586 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17587 DeclarationNameInfo(Id, IdLoc)); 17588 17589 EnumConstantDecl *New = 17590 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17591 if (!New) 17592 return nullptr; 17593 17594 if (PrevDecl) { 17595 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17596 // Check for other kinds of shadowing not already handled. 17597 CheckShadow(New, PrevDecl, R); 17598 } 17599 17600 // When in C++, we may get a TagDecl with the same name; in this case the 17601 // enum constant will 'hide' the tag. 17602 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17603 "Received TagDecl when not in C++!"); 17604 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17605 if (isa<EnumConstantDecl>(PrevDecl)) 17606 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17607 else 17608 Diag(IdLoc, diag::err_redefinition) << Id; 17609 notePreviousDefinition(PrevDecl, IdLoc); 17610 return nullptr; 17611 } 17612 } 17613 17614 // Process attributes. 17615 ProcessDeclAttributeList(S, New, Attrs); 17616 AddPragmaAttributes(S, New); 17617 17618 // Register this decl in the current scope stack. 17619 New->setAccess(TheEnumDecl->getAccess()); 17620 PushOnScopeChains(New, S); 17621 17622 ActOnDocumentableDecl(New); 17623 17624 return New; 17625 } 17626 17627 // Returns true when the enum initial expression does not trigger the 17628 // duplicate enum warning. A few common cases are exempted as follows: 17629 // Element2 = Element1 17630 // Element2 = Element1 + 1 17631 // Element2 = Element1 - 1 17632 // Where Element2 and Element1 are from the same enum. 17633 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17634 Expr *InitExpr = ECD->getInitExpr(); 17635 if (!InitExpr) 17636 return true; 17637 InitExpr = InitExpr->IgnoreImpCasts(); 17638 17639 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17640 if (!BO->isAdditiveOp()) 17641 return true; 17642 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17643 if (!IL) 17644 return true; 17645 if (IL->getValue() != 1) 17646 return true; 17647 17648 InitExpr = BO->getLHS(); 17649 } 17650 17651 // This checks if the elements are from the same enum. 17652 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17653 if (!DRE) 17654 return true; 17655 17656 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17657 if (!EnumConstant) 17658 return true; 17659 17660 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17661 Enum) 17662 return true; 17663 17664 return false; 17665 } 17666 17667 // Emits a warning when an element is implicitly set a value that 17668 // a previous element has already been set to. 17669 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17670 EnumDecl *Enum, QualType EnumType) { 17671 // Avoid anonymous enums 17672 if (!Enum->getIdentifier()) 17673 return; 17674 17675 // Only check for small enums. 17676 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17677 return; 17678 17679 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17680 return; 17681 17682 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17683 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17684 17685 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17686 17687 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17688 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17689 17690 // Use int64_t as a key to avoid needing special handling for map keys. 17691 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17692 llvm::APSInt Val = D->getInitVal(); 17693 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17694 }; 17695 17696 DuplicatesVector DupVector; 17697 ValueToVectorMap EnumMap; 17698 17699 // Populate the EnumMap with all values represented by enum constants without 17700 // an initializer. 17701 for (auto *Element : Elements) { 17702 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17703 17704 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17705 // this constant. Skip this enum since it may be ill-formed. 17706 if (!ECD) { 17707 return; 17708 } 17709 17710 // Constants with initalizers are handled in the next loop. 17711 if (ECD->getInitExpr()) 17712 continue; 17713 17714 // Duplicate values are handled in the next loop. 17715 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17716 } 17717 17718 if (EnumMap.size() == 0) 17719 return; 17720 17721 // Create vectors for any values that has duplicates. 17722 for (auto *Element : Elements) { 17723 // The last loop returned if any constant was null. 17724 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17725 if (!ValidDuplicateEnum(ECD, Enum)) 17726 continue; 17727 17728 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17729 if (Iter == EnumMap.end()) 17730 continue; 17731 17732 DeclOrVector& Entry = Iter->second; 17733 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17734 // Ensure constants are different. 17735 if (D == ECD) 17736 continue; 17737 17738 // Create new vector and push values onto it. 17739 auto Vec = std::make_unique<ECDVector>(); 17740 Vec->push_back(D); 17741 Vec->push_back(ECD); 17742 17743 // Update entry to point to the duplicates vector. 17744 Entry = Vec.get(); 17745 17746 // Store the vector somewhere we can consult later for quick emission of 17747 // diagnostics. 17748 DupVector.emplace_back(std::move(Vec)); 17749 continue; 17750 } 17751 17752 ECDVector *Vec = Entry.get<ECDVector*>(); 17753 // Make sure constants are not added more than once. 17754 if (*Vec->begin() == ECD) 17755 continue; 17756 17757 Vec->push_back(ECD); 17758 } 17759 17760 // Emit diagnostics. 17761 for (const auto &Vec : DupVector) { 17762 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17763 17764 // Emit warning for one enum constant. 17765 auto *FirstECD = Vec->front(); 17766 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17767 << FirstECD << FirstECD->getInitVal().toString(10) 17768 << FirstECD->getSourceRange(); 17769 17770 // Emit one note for each of the remaining enum constants with 17771 // the same value. 17772 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17773 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17774 << ECD << ECD->getInitVal().toString(10) 17775 << ECD->getSourceRange(); 17776 } 17777 } 17778 17779 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17780 bool AllowMask) const { 17781 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17782 assert(ED->isCompleteDefinition() && "expected enum definition"); 17783 17784 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17785 llvm::APInt &FlagBits = R.first->second; 17786 17787 if (R.second) { 17788 for (auto *E : ED->enumerators()) { 17789 const auto &EVal = E->getInitVal(); 17790 // Only single-bit enumerators introduce new flag values. 17791 if (EVal.isPowerOf2()) 17792 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17793 } 17794 } 17795 17796 // A value is in a flag enum if either its bits are a subset of the enum's 17797 // flag bits (the first condition) or we are allowing masks and the same is 17798 // true of its complement (the second condition). When masks are allowed, we 17799 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17800 // 17801 // While it's true that any value could be used as a mask, the assumption is 17802 // that a mask will have all of the insignificant bits set. Anything else is 17803 // likely a logic error. 17804 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17805 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17806 } 17807 17808 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17809 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17810 const ParsedAttributesView &Attrs) { 17811 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17812 QualType EnumType = Context.getTypeDeclType(Enum); 17813 17814 ProcessDeclAttributeList(S, Enum, Attrs); 17815 17816 if (Enum->isDependentType()) { 17817 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17818 EnumConstantDecl *ECD = 17819 cast_or_null<EnumConstantDecl>(Elements[i]); 17820 if (!ECD) continue; 17821 17822 ECD->setType(EnumType); 17823 } 17824 17825 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17826 return; 17827 } 17828 17829 // TODO: If the result value doesn't fit in an int, it must be a long or long 17830 // long value. ISO C does not support this, but GCC does as an extension, 17831 // emit a warning. 17832 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17833 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17834 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17835 17836 // Verify that all the values are okay, compute the size of the values, and 17837 // reverse the list. 17838 unsigned NumNegativeBits = 0; 17839 unsigned NumPositiveBits = 0; 17840 17841 // Keep track of whether all elements have type int. 17842 bool AllElementsInt = true; 17843 17844 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17845 EnumConstantDecl *ECD = 17846 cast_or_null<EnumConstantDecl>(Elements[i]); 17847 if (!ECD) continue; // Already issued a diagnostic. 17848 17849 const llvm::APSInt &InitVal = ECD->getInitVal(); 17850 17851 // Keep track of the size of positive and negative values. 17852 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17853 NumPositiveBits = std::max(NumPositiveBits, 17854 (unsigned)InitVal.getActiveBits()); 17855 else 17856 NumNegativeBits = std::max(NumNegativeBits, 17857 (unsigned)InitVal.getMinSignedBits()); 17858 17859 // Keep track of whether every enum element has type int (very common). 17860 if (AllElementsInt) 17861 AllElementsInt = ECD->getType() == Context.IntTy; 17862 } 17863 17864 // Figure out the type that should be used for this enum. 17865 QualType BestType; 17866 unsigned BestWidth; 17867 17868 // C++0x N3000 [conv.prom]p3: 17869 // An rvalue of an unscoped enumeration type whose underlying 17870 // type is not fixed can be converted to an rvalue of the first 17871 // of the following types that can represent all the values of 17872 // the enumeration: int, unsigned int, long int, unsigned long 17873 // int, long long int, or unsigned long long int. 17874 // C99 6.4.4.3p2: 17875 // An identifier declared as an enumeration constant has type int. 17876 // The C99 rule is modified by a gcc extension 17877 QualType BestPromotionType; 17878 17879 bool Packed = Enum->hasAttr<PackedAttr>(); 17880 // -fshort-enums is the equivalent to specifying the packed attribute on all 17881 // enum definitions. 17882 if (LangOpts.ShortEnums) 17883 Packed = true; 17884 17885 // If the enum already has a type because it is fixed or dictated by the 17886 // target, promote that type instead of analyzing the enumerators. 17887 if (Enum->isComplete()) { 17888 BestType = Enum->getIntegerType(); 17889 if (BestType->isPromotableIntegerType()) 17890 BestPromotionType = Context.getPromotedIntegerType(BestType); 17891 else 17892 BestPromotionType = BestType; 17893 17894 BestWidth = Context.getIntWidth(BestType); 17895 } 17896 else if (NumNegativeBits) { 17897 // If there is a negative value, figure out the smallest integer type (of 17898 // int/long/longlong) that fits. 17899 // If it's packed, check also if it fits a char or a short. 17900 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17901 BestType = Context.SignedCharTy; 17902 BestWidth = CharWidth; 17903 } else if (Packed && NumNegativeBits <= ShortWidth && 17904 NumPositiveBits < ShortWidth) { 17905 BestType = Context.ShortTy; 17906 BestWidth = ShortWidth; 17907 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17908 BestType = Context.IntTy; 17909 BestWidth = IntWidth; 17910 } else { 17911 BestWidth = Context.getTargetInfo().getLongWidth(); 17912 17913 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17914 BestType = Context.LongTy; 17915 } else { 17916 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17917 17918 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17919 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17920 BestType = Context.LongLongTy; 17921 } 17922 } 17923 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17924 } else { 17925 // If there is no negative value, figure out the smallest type that fits 17926 // all of the enumerator values. 17927 // If it's packed, check also if it fits a char or a short. 17928 if (Packed && NumPositiveBits <= CharWidth) { 17929 BestType = Context.UnsignedCharTy; 17930 BestPromotionType = Context.IntTy; 17931 BestWidth = CharWidth; 17932 } else if (Packed && NumPositiveBits <= ShortWidth) { 17933 BestType = Context.UnsignedShortTy; 17934 BestPromotionType = Context.IntTy; 17935 BestWidth = ShortWidth; 17936 } else if (NumPositiveBits <= IntWidth) { 17937 BestType = Context.UnsignedIntTy; 17938 BestWidth = IntWidth; 17939 BestPromotionType 17940 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17941 ? Context.UnsignedIntTy : Context.IntTy; 17942 } else if (NumPositiveBits <= 17943 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17944 BestType = Context.UnsignedLongTy; 17945 BestPromotionType 17946 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17947 ? Context.UnsignedLongTy : Context.LongTy; 17948 } else { 17949 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17950 assert(NumPositiveBits <= BestWidth && 17951 "How could an initializer get larger than ULL?"); 17952 BestType = Context.UnsignedLongLongTy; 17953 BestPromotionType 17954 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17955 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17956 } 17957 } 17958 17959 // Loop over all of the enumerator constants, changing their types to match 17960 // the type of the enum if needed. 17961 for (auto *D : Elements) { 17962 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17963 if (!ECD) continue; // Already issued a diagnostic. 17964 17965 // Standard C says the enumerators have int type, but we allow, as an 17966 // extension, the enumerators to be larger than int size. If each 17967 // enumerator value fits in an int, type it as an int, otherwise type it the 17968 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17969 // that X has type 'int', not 'unsigned'. 17970 17971 // Determine whether the value fits into an int. 17972 llvm::APSInt InitVal = ECD->getInitVal(); 17973 17974 // If it fits into an integer type, force it. Otherwise force it to match 17975 // the enum decl type. 17976 QualType NewTy; 17977 unsigned NewWidth; 17978 bool NewSign; 17979 if (!getLangOpts().CPlusPlus && 17980 !Enum->isFixed() && 17981 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17982 NewTy = Context.IntTy; 17983 NewWidth = IntWidth; 17984 NewSign = true; 17985 } else if (ECD->getType() == BestType) { 17986 // Already the right type! 17987 if (getLangOpts().CPlusPlus) 17988 // C++ [dcl.enum]p4: Following the closing brace of an 17989 // enum-specifier, each enumerator has the type of its 17990 // enumeration. 17991 ECD->setType(EnumType); 17992 continue; 17993 } else { 17994 NewTy = BestType; 17995 NewWidth = BestWidth; 17996 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17997 } 17998 17999 // Adjust the APSInt value. 18000 InitVal = InitVal.extOrTrunc(NewWidth); 18001 InitVal.setIsSigned(NewSign); 18002 ECD->setInitVal(InitVal); 18003 18004 // Adjust the Expr initializer and type. 18005 if (ECD->getInitExpr() && 18006 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18007 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18008 CK_IntegralCast, 18009 ECD->getInitExpr(), 18010 /*base paths*/ nullptr, 18011 VK_RValue)); 18012 if (getLangOpts().CPlusPlus) 18013 // C++ [dcl.enum]p4: Following the closing brace of an 18014 // enum-specifier, each enumerator has the type of its 18015 // enumeration. 18016 ECD->setType(EnumType); 18017 else 18018 ECD->setType(NewTy); 18019 } 18020 18021 Enum->completeDefinition(BestType, BestPromotionType, 18022 NumPositiveBits, NumNegativeBits); 18023 18024 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18025 18026 if (Enum->isClosedFlag()) { 18027 for (Decl *D : Elements) { 18028 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18029 if (!ECD) continue; // Already issued a diagnostic. 18030 18031 llvm::APSInt InitVal = ECD->getInitVal(); 18032 if (InitVal != 0 && !InitVal.isPowerOf2() && 18033 !IsValueInFlagEnum(Enum, InitVal, true)) 18034 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18035 << ECD << Enum; 18036 } 18037 } 18038 18039 // Now that the enum type is defined, ensure it's not been underaligned. 18040 if (Enum->hasAttrs()) 18041 CheckAlignasUnderalignment(Enum); 18042 } 18043 18044 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18045 SourceLocation StartLoc, 18046 SourceLocation EndLoc) { 18047 StringLiteral *AsmString = cast<StringLiteral>(expr); 18048 18049 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18050 AsmString, StartLoc, 18051 EndLoc); 18052 CurContext->addDecl(New); 18053 return New; 18054 } 18055 18056 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18057 IdentifierInfo* AliasName, 18058 SourceLocation PragmaLoc, 18059 SourceLocation NameLoc, 18060 SourceLocation AliasNameLoc) { 18061 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18062 LookupOrdinaryName); 18063 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18064 AttributeCommonInfo::AS_Pragma); 18065 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18066 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18067 18068 // If a declaration that: 18069 // 1) declares a function or a variable 18070 // 2) has external linkage 18071 // already exists, add a label attribute to it. 18072 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18073 if (isDeclExternC(PrevDecl)) 18074 PrevDecl->addAttr(Attr); 18075 else 18076 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18077 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18078 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18079 } else 18080 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18081 } 18082 18083 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18084 SourceLocation PragmaLoc, 18085 SourceLocation NameLoc) { 18086 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18087 18088 if (PrevDecl) { 18089 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18090 } else { 18091 (void)WeakUndeclaredIdentifiers.insert( 18092 std::pair<IdentifierInfo*,WeakInfo> 18093 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18094 } 18095 } 18096 18097 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18098 IdentifierInfo* AliasName, 18099 SourceLocation PragmaLoc, 18100 SourceLocation NameLoc, 18101 SourceLocation AliasNameLoc) { 18102 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18103 LookupOrdinaryName); 18104 WeakInfo W = WeakInfo(Name, NameLoc); 18105 18106 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18107 if (!PrevDecl->hasAttr<AliasAttr>()) 18108 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18109 DeclApplyPragmaWeak(TUScope, ND, W); 18110 } else { 18111 (void)WeakUndeclaredIdentifiers.insert( 18112 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18113 } 18114 } 18115 18116 Decl *Sema::getObjCDeclContext() const { 18117 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18118 } 18119 18120 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18121 bool Final) { 18122 // SYCL functions can be template, so we check if they have appropriate 18123 // attribute prior to checking if it is a template. 18124 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18125 return FunctionEmissionStatus::Emitted; 18126 18127 // Templates are emitted when they're instantiated. 18128 if (FD->isDependentContext()) 18129 return FunctionEmissionStatus::TemplateDiscarded; 18130 18131 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18132 if (LangOpts.OpenMPIsDevice) { 18133 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18134 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18135 if (DevTy.hasValue()) { 18136 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18137 OMPES = FunctionEmissionStatus::OMPDiscarded; 18138 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18139 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18140 OMPES = FunctionEmissionStatus::Emitted; 18141 } 18142 } 18143 } else if (LangOpts.OpenMP) { 18144 // In OpenMP 4.5 all the functions are host functions. 18145 if (LangOpts.OpenMP <= 45) { 18146 OMPES = FunctionEmissionStatus::Emitted; 18147 } else { 18148 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18149 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18150 // In OpenMP 5.0 or above, DevTy may be changed later by 18151 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18152 // having no value does not imply host. The emission status will be 18153 // checked again at the end of compilation unit. 18154 if (DevTy.hasValue()) { 18155 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18156 OMPES = FunctionEmissionStatus::OMPDiscarded; 18157 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18158 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18159 OMPES = FunctionEmissionStatus::Emitted; 18160 } else if (Final) 18161 OMPES = FunctionEmissionStatus::Emitted; 18162 } 18163 } 18164 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18165 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18166 return OMPES; 18167 18168 if (LangOpts.CUDA) { 18169 // When compiling for device, host functions are never emitted. Similarly, 18170 // when compiling for host, device and global functions are never emitted. 18171 // (Technically, we do emit a host-side stub for global functions, but this 18172 // doesn't count for our purposes here.) 18173 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18174 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18175 return FunctionEmissionStatus::CUDADiscarded; 18176 if (!LangOpts.CUDAIsDevice && 18177 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18178 return FunctionEmissionStatus::CUDADiscarded; 18179 18180 // Check whether this function is externally visible -- if so, it's 18181 // known-emitted. 18182 // 18183 // We have to check the GVA linkage of the function's *definition* -- if we 18184 // only have a declaration, we don't know whether or not the function will 18185 // be emitted, because (say) the definition could include "inline". 18186 FunctionDecl *Def = FD->getDefinition(); 18187 18188 if (Def && 18189 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18190 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18191 return FunctionEmissionStatus::Emitted; 18192 } 18193 18194 // Otherwise, the function is known-emitted if it's in our set of 18195 // known-emitted functions. 18196 return FunctionEmissionStatus::Unknown; 18197 } 18198 18199 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18200 // Host-side references to a __global__ function refer to the stub, so the 18201 // function itself is never emitted and therefore should not be marked. 18202 // If we have host fn calls kernel fn calls host+device, the HD function 18203 // does not get instantiated on the host. We model this by omitting at the 18204 // call to the kernel from the callgraph. This ensures that, when compiling 18205 // for host, only HD functions actually called from the host get marked as 18206 // known-emitted. 18207 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18208 IdentifyCUDATarget(Callee) == CFT_Global; 18209 } 18210