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/ExprCXX.h" 25 #include "clang/AST/NonTrivialTypeVisitor.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 std::unique_ptr<CorrectionCandidateCallback> clone() override { 110 return std::make_unique<TypeNameValidatorCCC>(*this); 111 } 112 113 private: 114 bool AllowInvalidDecl; 115 bool WantClassName; 116 bool AllowTemplates; 117 bool AllowNonTemplates; 118 }; 119 120 } // end anonymous namespace 121 122 /// Determine whether the token kind starts a simple-type-specifier. 123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 124 switch (Kind) { 125 // FIXME: Take into account the current language when deciding whether a 126 // token kind is a valid type specifier 127 case tok::kw_short: 128 case tok::kw_long: 129 case tok::kw___int64: 130 case tok::kw___int128: 131 case tok::kw_signed: 132 case tok::kw_unsigned: 133 case tok::kw_void: 134 case tok::kw_char: 135 case tok::kw_int: 136 case tok::kw_half: 137 case tok::kw_float: 138 case tok::kw_double: 139 case tok::kw__Float16: 140 case tok::kw___float128: 141 case tok::kw_wchar_t: 142 case tok::kw_bool: 143 case tok::kw___underlying_type: 144 case tok::kw___auto_type: 145 return true; 146 147 case tok::annot_typename: 148 case tok::kw_char16_t: 149 case tok::kw_char32_t: 150 case tok::kw_typeof: 151 case tok::annot_decltype: 152 case tok::kw_decltype: 153 return getLangOpts().CPlusPlus; 154 155 case tok::kw_char8_t: 156 return getLangOpts().Char8; 157 158 default: 159 break; 160 } 161 162 return false; 163 } 164 165 namespace { 166 enum class UnqualifiedTypeNameLookupResult { 167 NotFound, 168 FoundNonType, 169 FoundType 170 }; 171 } // end anonymous namespace 172 173 /// Tries to perform unqualified lookup of the type decls in bases for 174 /// dependent class. 175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 176 /// type decl, \a FoundType if only type decls are found. 177 static UnqualifiedTypeNameLookupResult 178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 179 SourceLocation NameLoc, 180 const CXXRecordDecl *RD) { 181 if (!RD->hasDefinition()) 182 return UnqualifiedTypeNameLookupResult::NotFound; 183 // Look for type decls in base classes. 184 UnqualifiedTypeNameLookupResult FoundTypeDecl = 185 UnqualifiedTypeNameLookupResult::NotFound; 186 for (const auto &Base : RD->bases()) { 187 const CXXRecordDecl *BaseRD = nullptr; 188 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 189 BaseRD = BaseTT->getAsCXXRecordDecl(); 190 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 191 // Look for type decls in dependent base classes that have known primary 192 // templates. 193 if (!TST || !TST->isDependentType()) 194 continue; 195 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 196 if (!TD) 197 continue; 198 if (auto *BasePrimaryTemplate = 199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 201 BaseRD = BasePrimaryTemplate; 202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 203 if (const ClassTemplatePartialSpecializationDecl *PS = 204 CTD->findPartialSpecialization(Base.getType())) 205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = PS; 207 } 208 } 209 } 210 if (BaseRD) { 211 for (NamedDecl *ND : BaseRD->lookup(&II)) { 212 if (!isa<TypeDecl>(ND)) 213 return UnqualifiedTypeNameLookupResult::FoundNonType; 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 } 216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 218 case UnqualifiedTypeNameLookupResult::FoundNonType: 219 return UnqualifiedTypeNameLookupResult::FoundNonType; 220 case UnqualifiedTypeNameLookupResult::FoundType: 221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 222 break; 223 case UnqualifiedTypeNameLookupResult::NotFound: 224 break; 225 } 226 } 227 } 228 } 229 230 return FoundTypeDecl; 231 } 232 233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 234 const IdentifierInfo &II, 235 SourceLocation NameLoc) { 236 // Lookup in the parent class template context, if any. 237 const CXXRecordDecl *RD = nullptr; 238 UnqualifiedTypeNameLookupResult FoundTypeDecl = 239 UnqualifiedTypeNameLookupResult::NotFound; 240 for (DeclContext *DC = S.CurContext; 241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 242 DC = DC->getParent()) { 243 // Look for type decls in dependent base classes that have known primary 244 // templates. 245 RD = dyn_cast<CXXRecordDecl>(DC); 246 if (RD && RD->getDescribedClassTemplate()) 247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 248 } 249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 250 return nullptr; 251 252 // We found some types in dependent base classes. Recover as if the user 253 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 254 // lookup during template instantiation. 255 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 256 257 ASTContext &Context = S.Context; 258 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 259 cast<Type>(Context.getRecordType(RD))); 260 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 261 262 CXXScopeSpec SS; 263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 264 265 TypeLocBuilder Builder; 266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 267 DepTL.setNameLoc(NameLoc); 268 DepTL.setElaboratedKeywordLoc(SourceLocation()); 269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 271 } 272 273 /// If the identifier refers to a type name within this scope, 274 /// return the declaration of that type. 275 /// 276 /// This routine performs ordinary name lookup of the identifier II 277 /// within the given scope, with optional C++ scope specifier SS, to 278 /// determine whether the name refers to a type. If so, returns an 279 /// opaque pointer (actually a QualType) corresponding to that 280 /// type. Otherwise, returns NULL. 281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 282 Scope *S, CXXScopeSpec *SS, 283 bool isClassName, bool HasTrailingDot, 284 ParsedType ObjectTypePtr, 285 bool IsCtorOrDtorName, 286 bool WantNontrivialTypeSourceInfo, 287 bool IsClassTemplateDeductionContext, 288 IdentifierInfo **CorrectedII) { 289 // FIXME: Consider allowing this outside C++1z mode as an extension. 290 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 291 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 292 !isClassName && !HasTrailingDot; 293 294 // Determine where we will perform name lookup. 295 DeclContext *LookupCtx = nullptr; 296 if (ObjectTypePtr) { 297 QualType ObjectType = ObjectTypePtr.get(); 298 if (ObjectType->isRecordType()) 299 LookupCtx = computeDeclContext(ObjectType); 300 } else if (SS && SS->isNotEmpty()) { 301 LookupCtx = computeDeclContext(*SS, false); 302 303 if (!LookupCtx) { 304 if (isDependentScopeSpecifier(*SS)) { 305 // C++ [temp.res]p3: 306 // A qualified-id that refers to a type and in which the 307 // nested-name-specifier depends on a template-parameter (14.6.2) 308 // shall be prefixed by the keyword typename to indicate that the 309 // qualified-id denotes a type, forming an 310 // elaborated-type-specifier (7.1.5.3). 311 // 312 // We therefore do not perform any name lookup if the result would 313 // refer to a member of an unknown specialization. 314 if (!isClassName && !IsCtorOrDtorName) 315 return nullptr; 316 317 // We know from the grammar that this name refers to a type, 318 // so build a dependent node to describe the type. 319 if (WantNontrivialTypeSourceInfo) 320 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 321 322 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 323 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 324 II, NameLoc); 325 return ParsedType::make(T); 326 } 327 328 return nullptr; 329 } 330 331 if (!LookupCtx->isDependentContext() && 332 RequireCompleteDeclContext(*SS, LookupCtx)) 333 return nullptr; 334 } 335 336 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 337 // lookup for class-names. 338 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 339 LookupOrdinaryName; 340 LookupResult Result(*this, &II, NameLoc, Kind); 341 if (LookupCtx) { 342 // Perform "qualified" name lookup into the declaration context we 343 // computed, which is either the type of the base of a member access 344 // expression or the declaration context associated with a prior 345 // nested-name-specifier. 346 LookupQualifiedName(Result, LookupCtx); 347 348 if (ObjectTypePtr && Result.empty()) { 349 // C++ [basic.lookup.classref]p3: 350 // If the unqualified-id is ~type-name, the type-name is looked up 351 // in the context of the entire postfix-expression. If the type T of 352 // the object expression is of a class type C, the type-name is also 353 // looked up in the scope of class C. At least one of the lookups shall 354 // find a name that refers to (possibly cv-qualified) T. 355 LookupName(Result, S); 356 } 357 } else { 358 // Perform unqualified name lookup. 359 LookupName(Result, S); 360 361 // For unqualified lookup in a class template in MSVC mode, look into 362 // dependent base classes where the primary class template is known. 363 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 364 if (ParsedType TypeInBase = 365 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 366 return TypeInBase; 367 } 368 } 369 370 NamedDecl *IIDecl = nullptr; 371 switch (Result.getResultKind()) { 372 case LookupResult::NotFound: 373 case LookupResult::NotFoundInCurrentInstantiation: 374 if (CorrectedII) { 375 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 376 AllowDeducedTemplate); 377 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 378 S, SS, CCC, CTK_ErrorRecovery); 379 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 380 TemplateTy Template; 381 bool MemberOfUnknownSpecialization; 382 UnqualifiedId TemplateName; 383 TemplateName.setIdentifier(NewII, NameLoc); 384 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 385 CXXScopeSpec NewSS, *NewSSPtr = SS; 386 if (SS && NNS) { 387 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 388 NewSSPtr = &NewSS; 389 } 390 if (Correction && (NNS || NewII != &II) && 391 // Ignore a correction to a template type as the to-be-corrected 392 // identifier is not a template (typo correction for template names 393 // is handled elsewhere). 394 !(getLangOpts().CPlusPlus && NewSSPtr && 395 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 396 Template, MemberOfUnknownSpecialization))) { 397 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 398 isClassName, HasTrailingDot, ObjectTypePtr, 399 IsCtorOrDtorName, 400 WantNontrivialTypeSourceInfo, 401 IsClassTemplateDeductionContext); 402 if (Ty) { 403 diagnoseTypo(Correction, 404 PDiag(diag::err_unknown_type_or_class_name_suggest) 405 << Result.getLookupName() << isClassName); 406 if (SS && NNS) 407 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 408 *CorrectedII = NewII; 409 return Ty; 410 } 411 } 412 } 413 // If typo correction failed or was not performed, fall through 414 LLVM_FALLTHROUGH; 415 case LookupResult::FoundOverloaded: 416 case LookupResult::FoundUnresolvedValue: 417 Result.suppressDiagnostics(); 418 return nullptr; 419 420 case LookupResult::Ambiguous: 421 // Recover from type-hiding ambiguities by hiding the type. We'll 422 // do the lookup again when looking for an object, and we can 423 // diagnose the error then. If we don't do this, then the error 424 // about hiding the type will be immediately followed by an error 425 // that only makes sense if the identifier was treated like a type. 426 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 427 Result.suppressDiagnostics(); 428 return nullptr; 429 } 430 431 // Look to see if we have a type anywhere in the list of results. 432 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 433 Res != ResEnd; ++Res) { 434 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 435 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 436 if (!IIDecl || 437 (*Res)->getLocation().getRawEncoding() < 438 IIDecl->getLocation().getRawEncoding()) 439 IIDecl = *Res; 440 } 441 } 442 443 if (!IIDecl) { 444 // None of the entities we found is a type, so there is no way 445 // to even assume that the result is a type. In this case, don't 446 // complain about the ambiguity. The parser will either try to 447 // perform this lookup again (e.g., as an object name), which 448 // will produce the ambiguity, or will complain that it expected 449 // a type name. 450 Result.suppressDiagnostics(); 451 return nullptr; 452 } 453 454 // We found a type within the ambiguous lookup; diagnose the 455 // ambiguity and then return that type. This might be the right 456 // answer, or it might not be, but it suppresses any attempt to 457 // perform the name lookup again. 458 break; 459 460 case LookupResult::Found: 461 IIDecl = Result.getFoundDecl(); 462 break; 463 } 464 465 assert(IIDecl && "Didn't find decl"); 466 467 QualType T; 468 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 469 // C++ [class.qual]p2: A lookup that would find the injected-class-name 470 // instead names the constructors of the class, except when naming a class. 471 // This is ill-formed when we're not actually forming a ctor or dtor name. 472 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 473 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 474 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 475 FoundRD->isInjectedClassName() && 476 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 477 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 478 << &II << /*Type*/1; 479 480 DiagnoseUseOfDecl(IIDecl, NameLoc); 481 482 T = Context.getTypeDeclType(TD); 483 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 484 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 485 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 486 if (!HasTrailingDot) 487 T = Context.getObjCInterfaceType(IDecl); 488 } else if (AllowDeducedTemplate) { 489 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 490 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 491 QualType(), false); 492 } 493 494 if (T.isNull()) { 495 // If it's not plausibly a type, suppress diagnostics. 496 Result.suppressDiagnostics(); 497 return nullptr; 498 } 499 500 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 501 // constructor or destructor name (in such a case, the scope specifier 502 // will be attached to the enclosing Expr or Decl node). 503 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 504 !isa<ObjCInterfaceDecl>(IIDecl)) { 505 if (WantNontrivialTypeSourceInfo) { 506 // Construct a type with type-source information. 507 TypeLocBuilder Builder; 508 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 509 510 T = getElaboratedType(ETK_None, *SS, T); 511 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 512 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 513 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 514 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 515 } else { 516 T = getElaboratedType(ETK_None, *SS, T); 517 } 518 } 519 520 return ParsedType::make(T); 521 } 522 523 // Builds a fake NNS for the given decl context. 524 static NestedNameSpecifier * 525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 526 for (;; DC = DC->getLookupParent()) { 527 DC = DC->getPrimaryContext(); 528 auto *ND = dyn_cast<NamespaceDecl>(DC); 529 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 530 return NestedNameSpecifier::Create(Context, nullptr, ND); 531 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 532 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 533 RD->getTypeForDecl()); 534 else if (isa<TranslationUnitDecl>(DC)) 535 return NestedNameSpecifier::GlobalSpecifier(Context); 536 } 537 llvm_unreachable("something isn't in TU scope?"); 538 } 539 540 /// Find the parent class with dependent bases of the innermost enclosing method 541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 542 /// up allowing unqualified dependent type names at class-level, which MSVC 543 /// correctly rejects. 544 static const CXXRecordDecl * 545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 546 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 547 DC = DC->getPrimaryContext(); 548 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 549 if (MD->getParent()->hasAnyDependentBases()) 550 return MD->getParent(); 551 } 552 return nullptr; 553 } 554 555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 556 SourceLocation NameLoc, 557 bool IsTemplateTypeArg) { 558 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 559 560 NestedNameSpecifier *NNS = nullptr; 561 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 562 // If we weren't able to parse a default template argument, delay lookup 563 // until instantiation time by making a non-dependent DependentTypeName. We 564 // pretend we saw a NestedNameSpecifier referring to the current scope, and 565 // lookup is retried. 566 // FIXME: This hurts our diagnostic quality, since we get errors like "no 567 // type named 'Foo' in 'current_namespace'" when the user didn't write any 568 // name specifiers. 569 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 570 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 571 } else if (const CXXRecordDecl *RD = 572 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 573 // Build a DependentNameType that will perform lookup into RD at 574 // instantiation time. 575 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 576 RD->getTypeForDecl()); 577 578 // Diagnose that this identifier was undeclared, and retry the lookup during 579 // template instantiation. 580 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 581 << RD; 582 } else { 583 // This is not a situation that we should recover from. 584 return ParsedType(); 585 } 586 587 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 588 589 // Build type location information. We synthesized the qualifier, so we have 590 // to build a fake NestedNameSpecifierLoc. 591 NestedNameSpecifierLocBuilder NNSLocBuilder; 592 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 593 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 594 595 TypeLocBuilder Builder; 596 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 597 DepTL.setNameLoc(NameLoc); 598 DepTL.setElaboratedKeywordLoc(SourceLocation()); 599 DepTL.setQualifierLoc(QualifierLoc); 600 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 601 } 602 603 /// isTagName() - This method is called *for error recovery purposes only* 604 /// to determine if the specified name is a valid tag name ("struct foo"). If 605 /// so, this returns the TST for the tag corresponding to it (TST_enum, 606 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 607 /// cases in C where the user forgot to specify the tag. 608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 609 // Do a tag name lookup in this scope. 610 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 611 LookupName(R, S, false); 612 R.suppressDiagnostics(); 613 if (R.getResultKind() == LookupResult::Found) 614 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 615 switch (TD->getTagKind()) { 616 case TTK_Struct: return DeclSpec::TST_struct; 617 case TTK_Interface: return DeclSpec::TST_interface; 618 case TTK_Union: return DeclSpec::TST_union; 619 case TTK_Class: return DeclSpec::TST_class; 620 case TTK_Enum: return DeclSpec::TST_enum; 621 } 622 } 623 624 return DeclSpec::TST_unspecified; 625 } 626 627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 629 /// then downgrade the missing typename error to a warning. 630 /// This is needed for MSVC compatibility; Example: 631 /// @code 632 /// template<class T> class A { 633 /// public: 634 /// typedef int TYPE; 635 /// }; 636 /// template<class T> class B : public A<T> { 637 /// public: 638 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 639 /// }; 640 /// @endcode 641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 642 if (CurContext->isRecord()) { 643 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 644 return true; 645 646 const Type *Ty = SS->getScopeRep()->getAsType(); 647 648 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 649 for (const auto &Base : RD->bases()) 650 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 651 return true; 652 return S->isFunctionPrototypeScope(); 653 } 654 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 655 } 656 657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 658 SourceLocation IILoc, 659 Scope *S, 660 CXXScopeSpec *SS, 661 ParsedType &SuggestedType, 662 bool IsTemplateName) { 663 // Don't report typename errors for editor placeholders. 664 if (II->isEditorPlaceholder()) 665 return; 666 // We don't have anything to suggest (yet). 667 SuggestedType = nullptr; 668 669 // There may have been a typo in the name of the type. Look up typo 670 // results, in case we have something that we can suggest. 671 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 672 /*AllowTemplates=*/IsTemplateName, 673 /*AllowNonTemplates=*/!IsTemplateName); 674 if (TypoCorrection Corrected = 675 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 676 CCC, CTK_ErrorRecovery)) { 677 // FIXME: Support error recovery for the template-name case. 678 bool CanRecover = !IsTemplateName; 679 if (Corrected.isKeyword()) { 680 // We corrected to a keyword. 681 diagnoseTypo(Corrected, 682 PDiag(IsTemplateName ? diag::err_no_template_suggest 683 : diag::err_unknown_typename_suggest) 684 << II); 685 II = Corrected.getCorrectionAsIdentifierInfo(); 686 } else { 687 // We found a similarly-named type or interface; suggest that. 688 if (!SS || !SS->isSet()) { 689 diagnoseTypo(Corrected, 690 PDiag(IsTemplateName ? diag::err_no_template_suggest 691 : diag::err_unknown_typename_suggest) 692 << II, CanRecover); 693 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 694 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 695 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 696 II->getName().equals(CorrectedStr); 697 diagnoseTypo(Corrected, 698 PDiag(IsTemplateName 699 ? diag::err_no_member_template_suggest 700 : diag::err_unknown_nested_typename_suggest) 701 << II << DC << DroppedSpecifier << SS->getRange(), 702 CanRecover); 703 } else { 704 llvm_unreachable("could not have corrected a typo here"); 705 } 706 707 if (!CanRecover) 708 return; 709 710 CXXScopeSpec tmpSS; 711 if (Corrected.getCorrectionSpecifier()) 712 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 713 SourceRange(IILoc)); 714 // FIXME: Support class template argument deduction here. 715 SuggestedType = 716 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 717 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 718 /*IsCtorOrDtorName=*/false, 719 /*WantNontrivialTypeSourceInfo=*/true); 720 } 721 return; 722 } 723 724 if (getLangOpts().CPlusPlus && !IsTemplateName) { 725 // See if II is a class template that the user forgot to pass arguments to. 726 UnqualifiedId Name; 727 Name.setIdentifier(II, IILoc); 728 CXXScopeSpec EmptySS; 729 TemplateTy TemplateResult; 730 bool MemberOfUnknownSpecialization; 731 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 732 Name, nullptr, true, TemplateResult, 733 MemberOfUnknownSpecialization) == TNK_Type_template) { 734 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 735 return; 736 } 737 } 738 739 // FIXME: Should we move the logic that tries to recover from a missing tag 740 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 741 742 if (!SS || (!SS->isSet() && !SS->isInvalid())) 743 Diag(IILoc, IsTemplateName ? diag::err_no_template 744 : diag::err_unknown_typename) 745 << II; 746 else if (DeclContext *DC = computeDeclContext(*SS, false)) 747 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 748 : diag::err_typename_nested_not_found) 749 << II << DC << SS->getRange(); 750 else if (isDependentScopeSpecifier(*SS)) { 751 unsigned DiagID = diag::err_typename_missing; 752 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 753 DiagID = diag::ext_typename_missing; 754 755 Diag(SS->getRange().getBegin(), DiagID) 756 << SS->getScopeRep() << II->getName() 757 << SourceRange(SS->getRange().getBegin(), IILoc) 758 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 759 SuggestedType = ActOnTypenameType(S, SourceLocation(), 760 *SS, *II, IILoc).get(); 761 } else { 762 assert(SS && SS->isInvalid() && 763 "Invalid scope specifier has already been diagnosed"); 764 } 765 } 766 767 /// Determine whether the given result set contains either a type name 768 /// or 769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 770 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 771 NextToken.is(tok::less); 772 773 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 774 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 775 return true; 776 777 if (CheckTemplate && isa<TemplateDecl>(*I)) 778 return true; 779 } 780 781 return false; 782 } 783 784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 785 Scope *S, CXXScopeSpec &SS, 786 IdentifierInfo *&Name, 787 SourceLocation NameLoc) { 788 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 789 SemaRef.LookupParsedName(R, S, &SS); 790 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 791 StringRef FixItTagName; 792 switch (Tag->getTagKind()) { 793 case TTK_Class: 794 FixItTagName = "class "; 795 break; 796 797 case TTK_Enum: 798 FixItTagName = "enum "; 799 break; 800 801 case TTK_Struct: 802 FixItTagName = "struct "; 803 break; 804 805 case TTK_Interface: 806 FixItTagName = "__interface "; 807 break; 808 809 case TTK_Union: 810 FixItTagName = "union "; 811 break; 812 } 813 814 StringRef TagName = FixItTagName.drop_back(); 815 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 816 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 817 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 818 819 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 820 I != IEnd; ++I) 821 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 822 << Name << TagName; 823 824 // Replace lookup results with just the tag decl. 825 Result.clear(Sema::LookupTagName); 826 SemaRef.LookupParsedName(Result, S, &SS); 827 return true; 828 } 829 830 return false; 831 } 832 833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 835 QualType T, SourceLocation NameLoc) { 836 ASTContext &Context = S.Context; 837 838 TypeLocBuilder Builder; 839 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 840 841 T = S.getElaboratedType(ETK_None, SS, T); 842 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 843 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 844 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 845 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 846 } 847 848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 849 IdentifierInfo *&Name, 850 SourceLocation NameLoc, 851 const Token &NextToken, 852 CorrectionCandidateCallback *CCC) { 853 DeclarationNameInfo NameInfo(Name, NameLoc); 854 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 855 856 assert(NextToken.isNot(tok::coloncolon) && 857 "parse nested name specifiers before calling ClassifyName"); 858 if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 // For unqualified lookup in a class template in MSVC mode, look into 871 // dependent base classes where the primary class template is known. 872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 873 if (ParsedType TypeInBase = 874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 875 return TypeInBase; 876 } 877 878 // Perform lookup for Objective-C instance variables (including automatically 879 // synthesized instance variables), if we're in an Objective-C method. 880 // FIXME: This lookup really, really needs to be folded in to the normal 881 // unqualified lookup mechanism. 882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 883 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 884 if (Ivar.isInvalid()) 885 return NameClassification::Error(); 886 if (Ivar.isUsable()) 887 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 888 889 // We defer builtin creation until after ivar lookup inside ObjC methods. 890 if (Result.empty()) 891 LookupBuiltin(Result); 892 } 893 894 bool SecondTry = false; 895 bool IsFilteredTemplateName = false; 896 897 Corrected: 898 switch (Result.getResultKind()) { 899 case LookupResult::NotFound: 900 // If an unqualified-id is followed by a '(', then we have a function 901 // call. 902 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 903 // In C++, this is an ADL-only call. 904 // FIXME: Reference? 905 if (getLangOpts().CPlusPlus) 906 return NameClassification::UndeclaredNonType(); 907 908 // C90 6.3.2.2: 909 // If the expression that precedes the parenthesized argument list in a 910 // function call consists solely of an identifier, and if no 911 // declaration is visible for this identifier, the identifier is 912 // implicitly declared exactly as if, in the innermost block containing 913 // the function call, the declaration 914 // 915 // extern int identifier (); 916 // 917 // appeared. 918 // 919 // We also allow this in C99 as an extension. 920 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 921 return NameClassification::NonType(D); 922 } 923 924 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { 925 // In C++20 onwards, this could be an ADL-only call to a function 926 // template, and we're required to assume that this is a template name. 927 // 928 // FIXME: Find a way to still do typo correction in this case. 929 TemplateName Template = 930 Context.getAssumedTemplateName(NameInfo.getName()); 931 return NameClassification::UndeclaredTemplate(Template); 932 } 933 934 // In C, we first see whether there is a tag type by the same name, in 935 // which case it's likely that the user just forgot to write "enum", 936 // "struct", or "union". 937 if (!getLangOpts().CPlusPlus && !SecondTry && 938 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 939 break; 940 } 941 942 // Perform typo correction to determine if there is another name that is 943 // close to this name. 944 if (!SecondTry && CCC) { 945 SecondTry = true; 946 if (TypoCorrection Corrected = 947 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 948 &SS, *CCC, CTK_ErrorRecovery)) { 949 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 950 unsigned QualifiedDiag = diag::err_no_member_suggest; 951 952 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 953 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 954 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 955 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 956 UnqualifiedDiag = diag::err_no_template_suggest; 957 QualifiedDiag = diag::err_no_member_template_suggest; 958 } else if (UnderlyingFirstDecl && 959 (isa<TypeDecl>(UnderlyingFirstDecl) || 960 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 961 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 962 UnqualifiedDiag = diag::err_unknown_typename_suggest; 963 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 964 } 965 966 if (SS.isEmpty()) { 967 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 968 } else {// FIXME: is this even reachable? Test it. 969 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 970 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 971 Name->getName().equals(CorrectedStr); 972 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 973 << Name << computeDeclContext(SS, false) 974 << DroppedSpecifier << SS.getRange()); 975 } 976 977 // Update the name, so that the caller has the new name. 978 Name = Corrected.getCorrectionAsIdentifierInfo(); 979 980 // Typo correction corrected to a keyword. 981 if (Corrected.isKeyword()) 982 return Name; 983 984 // Also update the LookupResult... 985 // FIXME: This should probably go away at some point 986 Result.clear(); 987 Result.setLookupName(Corrected.getCorrection()); 988 if (FirstDecl) 989 Result.addDecl(FirstDecl); 990 991 // If we found an Objective-C instance variable, let 992 // LookupInObjCMethod build the appropriate expression to 993 // reference the ivar. 994 // FIXME: This is a gross hack. 995 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 996 DeclResult R = 997 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 998 if (R.isInvalid()) 999 return NameClassification::Error(); 1000 if (R.isUsable()) 1001 return NameClassification::NonType(Ivar); 1002 } 1003 1004 goto Corrected; 1005 } 1006 } 1007 1008 // We failed to correct; just fall through and let the parser deal with it. 1009 Result.suppressDiagnostics(); 1010 return NameClassification::Unknown(); 1011 1012 case LookupResult::NotFoundInCurrentInstantiation: { 1013 // We performed name lookup into the current instantiation, and there were 1014 // dependent bases, so we treat this result the same way as any other 1015 // dependent nested-name-specifier. 1016 1017 // C++ [temp.res]p2: 1018 // A name used in a template declaration or definition and that is 1019 // dependent on a template-parameter is assumed not to name a type 1020 // unless the applicable name lookup finds a type name or the name is 1021 // qualified by the keyword typename. 1022 // 1023 // FIXME: If the next token is '<', we might want to ask the parser to 1024 // perform some heroics to see if we actually have a 1025 // template-argument-list, which would indicate a missing 'template' 1026 // keyword here. 1027 return NameClassification::DependentNonType(); 1028 } 1029 1030 case LookupResult::Found: 1031 case LookupResult::FoundOverloaded: 1032 case LookupResult::FoundUnresolvedValue: 1033 break; 1034 1035 case LookupResult::Ambiguous: 1036 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1037 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1038 /*AllowDependent=*/false)) { 1039 // C++ [temp.local]p3: 1040 // A lookup that finds an injected-class-name (10.2) can result in an 1041 // ambiguity in certain cases (for example, if it is found in more than 1042 // one base class). If all of the injected-class-names that are found 1043 // refer to specializations of the same class template, and if the name 1044 // is followed by a template-argument-list, the reference refers to the 1045 // class template itself and not a specialization thereof, and is not 1046 // ambiguous. 1047 // 1048 // This filtering can make an ambiguous result into an unambiguous one, 1049 // so try again after filtering out template names. 1050 FilterAcceptableTemplateNames(Result); 1051 if (!Result.isAmbiguous()) { 1052 IsFilteredTemplateName = true; 1053 break; 1054 } 1055 } 1056 1057 // Diagnose the ambiguity and return an error. 1058 return NameClassification::Error(); 1059 } 1060 1061 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1062 (IsFilteredTemplateName || 1063 hasAnyAcceptableTemplateNames( 1064 Result, /*AllowFunctionTemplates=*/true, 1065 /*AllowDependent=*/false, 1066 /*AllowNonTemplateFunctions*/ !SS.isSet() && 1067 getLangOpts().CPlusPlus2a))) { 1068 // C++ [temp.names]p3: 1069 // After name lookup (3.4) finds that a name is a template-name or that 1070 // an operator-function-id or a literal- operator-id refers to a set of 1071 // overloaded functions any member of which is a function template if 1072 // this is followed by a <, the < is always taken as the delimiter of a 1073 // template-argument-list and never as the less-than operator. 1074 // C++2a [temp.names]p2: 1075 // A name is also considered to refer to a template if it is an 1076 // unqualified-id followed by a < and name lookup finds either one 1077 // or more functions or finds nothing. 1078 if (!IsFilteredTemplateName) 1079 FilterAcceptableTemplateNames(Result); 1080 1081 bool IsFunctionTemplate; 1082 bool IsVarTemplate; 1083 TemplateName Template; 1084 if (Result.end() - Result.begin() > 1) { 1085 IsFunctionTemplate = true; 1086 Template = Context.getOverloadedTemplateName(Result.begin(), 1087 Result.end()); 1088 } else if (!Result.empty()) { 1089 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1090 *Result.begin(), /*AllowFunctionTemplates=*/true, 1091 /*AllowDependent=*/false)); 1092 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1093 IsVarTemplate = isa<VarTemplateDecl>(TD); 1094 1095 if (SS.isSet() && !SS.isInvalid()) 1096 Template = 1097 Context.getQualifiedTemplateName(SS.getScopeRep(), 1098 /*TemplateKeyword=*/false, TD); 1099 else 1100 Template = TemplateName(TD); 1101 } else { 1102 // All results were non-template functions. This is a function template 1103 // name. 1104 IsFunctionTemplate = true; 1105 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1106 } 1107 1108 if (IsFunctionTemplate) { 1109 // Function templates always go through overload resolution, at which 1110 // point we'll perform the various checks (e.g., accessibility) we need 1111 // to based on which function we selected. 1112 Result.suppressDiagnostics(); 1113 1114 return NameClassification::FunctionTemplate(Template); 1115 } 1116 1117 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1118 : NameClassification::TypeTemplate(Template); 1119 } 1120 1121 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1122 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1123 DiagnoseUseOfDecl(Type, NameLoc); 1124 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1125 QualType T = Context.getTypeDeclType(Type); 1126 if (SS.isNotEmpty()) 1127 return buildNestedType(*this, SS, T, NameLoc); 1128 return ParsedType::make(T); 1129 } 1130 1131 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1132 if (!Class) { 1133 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1134 if (ObjCCompatibleAliasDecl *Alias = 1135 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1136 Class = Alias->getClassInterface(); 1137 } 1138 1139 if (Class) { 1140 DiagnoseUseOfDecl(Class, NameLoc); 1141 1142 if (NextToken.is(tok::period)) { 1143 // Interface. <something> is parsed as a property reference expression. 1144 // Just return "unknown" as a fall-through for now. 1145 Result.suppressDiagnostics(); 1146 return NameClassification::Unknown(); 1147 } 1148 1149 QualType T = Context.getObjCInterfaceType(Class); 1150 return ParsedType::make(T); 1151 } 1152 1153 // We can have a type template here if we're classifying a template argument. 1154 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1155 !isa<VarTemplateDecl>(FirstDecl)) 1156 return NameClassification::TypeTemplate( 1157 TemplateName(cast<TemplateDecl>(FirstDecl))); 1158 1159 // Check for a tag type hidden by a non-type decl in a few cases where it 1160 // seems likely a type is wanted instead of the non-type that was found. 1161 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1162 if ((NextToken.is(tok::identifier) || 1163 (NextIsOp && 1164 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1165 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1166 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1167 DiagnoseUseOfDecl(Type, NameLoc); 1168 QualType T = Context.getTypeDeclType(Type); 1169 if (SS.isNotEmpty()) 1170 return buildNestedType(*this, SS, T, NameLoc); 1171 return ParsedType::make(T); 1172 } 1173 1174 // FIXME: This is context-dependent. We need to defer building the member 1175 // expression until the classification is consumed. 1176 if (FirstDecl->isCXXClassMember()) 1177 return NameClassification::ContextIndependentExpr( 1178 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1179 S)); 1180 1181 // If we already know which single declaration is referenced, just annotate 1182 // that declaration directly. 1183 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1184 if (Result.isSingleResult() && !ADL) 1185 return NameClassification::NonType(Result.getRepresentativeDecl()); 1186 1187 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1188 // context in which we performed classification, so it's safe to do now. 1189 return NameClassification::ContextIndependentExpr( 1190 BuildDeclarationNameExpr(SS, Result, ADL)); 1191 } 1192 1193 ExprResult 1194 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1195 SourceLocation NameLoc) { 1196 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1197 CXXScopeSpec SS; 1198 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1199 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1200 } 1201 1202 ExprResult 1203 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1204 IdentifierInfo *Name, 1205 SourceLocation NameLoc, 1206 bool IsAddressOfOperand) { 1207 DeclarationNameInfo NameInfo(Name, NameLoc); 1208 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1209 NameInfo, IsAddressOfOperand, 1210 /*TemplateArgs=*/nullptr); 1211 } 1212 1213 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1214 NamedDecl *Found, 1215 SourceLocation NameLoc, 1216 const Token &NextToken) { 1217 if (getCurMethodDecl() && SS.isEmpty()) 1218 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1219 return BuildIvarRefExpr(S, NameLoc, Ivar); 1220 1221 // Reconstruct the lookup result. 1222 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1223 Result.addDecl(Found); 1224 Result.resolveKind(); 1225 1226 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1227 return BuildDeclarationNameExpr(SS, Result, ADL); 1228 } 1229 1230 Sema::TemplateNameKindForDiagnostics 1231 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1232 auto *TD = Name.getAsTemplateDecl(); 1233 if (!TD) 1234 return TemplateNameKindForDiagnostics::DependentTemplate; 1235 if (isa<ClassTemplateDecl>(TD)) 1236 return TemplateNameKindForDiagnostics::ClassTemplate; 1237 if (isa<FunctionTemplateDecl>(TD)) 1238 return TemplateNameKindForDiagnostics::FunctionTemplate; 1239 if (isa<VarTemplateDecl>(TD)) 1240 return TemplateNameKindForDiagnostics::VarTemplate; 1241 if (isa<TypeAliasTemplateDecl>(TD)) 1242 return TemplateNameKindForDiagnostics::AliasTemplate; 1243 if (isa<TemplateTemplateParmDecl>(TD)) 1244 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1245 if (isa<ConceptDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::Concept; 1247 return TemplateNameKindForDiagnostics::DependentTemplate; 1248 } 1249 1250 // Determines the context to return to after temporarily entering a 1251 // context. This depends in an unnecessarily complicated way on the 1252 // exact ordering of callbacks from the parser. 1253 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1254 1255 // Functions defined inline within classes aren't parsed until we've 1256 // finished parsing the top-level class, so the top-level class is 1257 // the context we'll need to return to. 1258 // A Lambda call operator whose parent is a class must not be treated 1259 // as an inline member function. A Lambda can be used legally 1260 // either as an in-class member initializer or a default argument. These 1261 // are parsed once the class has been marked complete and so the containing 1262 // context would be the nested class (when the lambda is defined in one); 1263 // If the class is not complete, then the lambda is being used in an 1264 // ill-formed fashion (such as to specify the width of a bit-field, or 1265 // in an array-bound) - in which case we still want to return the 1266 // lexically containing DC (which could be a nested class). 1267 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1268 DC = DC->getLexicalParent(); 1269 1270 // A function not defined within a class will always return to its 1271 // lexical context. 1272 if (!isa<CXXRecordDecl>(DC)) 1273 return DC; 1274 1275 // A C++ inline method/friend is parsed *after* the topmost class 1276 // it was declared in is fully parsed ("complete"); the topmost 1277 // class is the context we need to return to. 1278 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1279 DC = RD; 1280 1281 // Return the declaration context of the topmost class the inline method is 1282 // declared in. 1283 return DC; 1284 } 1285 1286 return DC->getLexicalParent(); 1287 } 1288 1289 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1290 assert(getContainingDC(DC) == CurContext && 1291 "The next DeclContext should be lexically contained in the current one."); 1292 CurContext = DC; 1293 S->setEntity(DC); 1294 } 1295 1296 void Sema::PopDeclContext() { 1297 assert(CurContext && "DeclContext imbalance!"); 1298 1299 CurContext = getContainingDC(CurContext); 1300 assert(CurContext && "Popped translation unit!"); 1301 } 1302 1303 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1304 Decl *D) { 1305 // Unlike PushDeclContext, the context to which we return is not necessarily 1306 // the containing DC of TD, because the new context will be some pre-existing 1307 // TagDecl definition instead of a fresh one. 1308 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1309 CurContext = cast<TagDecl>(D)->getDefinition(); 1310 assert(CurContext && "skipping definition of undefined tag"); 1311 // Start lookups from the parent of the current context; we don't want to look 1312 // into the pre-existing complete definition. 1313 S->setEntity(CurContext->getLookupParent()); 1314 return Result; 1315 } 1316 1317 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1318 CurContext = static_cast<decltype(CurContext)>(Context); 1319 } 1320 1321 /// EnterDeclaratorContext - Used when we must lookup names in the context 1322 /// of a declarator's nested name specifier. 1323 /// 1324 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1325 // C++0x [basic.lookup.unqual]p13: 1326 // A name used in the definition of a static data member of class 1327 // X (after the qualified-id of the static member) is looked up as 1328 // if the name was used in a member function of X. 1329 // C++0x [basic.lookup.unqual]p14: 1330 // If a variable member of a namespace is defined outside of the 1331 // scope of its namespace then any name used in the definition of 1332 // the variable member (after the declarator-id) is looked up as 1333 // if the definition of the variable member occurred in its 1334 // namespace. 1335 // Both of these imply that we should push a scope whose context 1336 // is the semantic context of the declaration. We can't use 1337 // PushDeclContext here because that context is not necessarily 1338 // lexically contained in the current context. Fortunately, 1339 // the containing scope should have the appropriate information. 1340 1341 assert(!S->getEntity() && "scope already has entity"); 1342 1343 #ifndef NDEBUG 1344 Scope *Ancestor = S->getParent(); 1345 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1346 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1347 #endif 1348 1349 CurContext = DC; 1350 S->setEntity(DC); 1351 } 1352 1353 void Sema::ExitDeclaratorContext(Scope *S) { 1354 assert(S->getEntity() == CurContext && "Context imbalance!"); 1355 1356 // Switch back to the lexical context. The safety of this is 1357 // enforced by an assert in EnterDeclaratorContext. 1358 Scope *Ancestor = S->getParent(); 1359 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1360 CurContext = Ancestor->getEntity(); 1361 1362 // We don't need to do anything with the scope, which is going to 1363 // disappear. 1364 } 1365 1366 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1367 // We assume that the caller has already called 1368 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1369 FunctionDecl *FD = D->getAsFunction(); 1370 if (!FD) 1371 return; 1372 1373 // Same implementation as PushDeclContext, but enters the context 1374 // from the lexical parent, rather than the top-level class. 1375 assert(CurContext == FD->getLexicalParent() && 1376 "The next DeclContext should be lexically contained in the current one."); 1377 CurContext = FD; 1378 S->setEntity(CurContext); 1379 1380 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1381 ParmVarDecl *Param = FD->getParamDecl(P); 1382 // If the parameter has an identifier, then add it to the scope 1383 if (Param->getIdentifier()) { 1384 S->AddDecl(Param); 1385 IdResolver.AddDecl(Param); 1386 } 1387 } 1388 } 1389 1390 void Sema::ActOnExitFunctionContext() { 1391 // Same implementation as PopDeclContext, but returns to the lexical parent, 1392 // rather than the top-level class. 1393 assert(CurContext && "DeclContext imbalance!"); 1394 CurContext = CurContext->getLexicalParent(); 1395 assert(CurContext && "Popped translation unit!"); 1396 } 1397 1398 /// Determine whether we allow overloading of the function 1399 /// PrevDecl with another declaration. 1400 /// 1401 /// This routine determines whether overloading is possible, not 1402 /// whether some new function is actually an overload. It will return 1403 /// true in C++ (where we can always provide overloads) or, as an 1404 /// extension, in C when the previous function is already an 1405 /// overloaded function declaration or has the "overloadable" 1406 /// attribute. 1407 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1408 ASTContext &Context, 1409 const FunctionDecl *New) { 1410 if (Context.getLangOpts().CPlusPlus) 1411 return true; 1412 1413 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1414 return true; 1415 1416 return Previous.getResultKind() == LookupResult::Found && 1417 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1418 New->hasAttr<OverloadableAttr>()); 1419 } 1420 1421 /// Add this decl to the scope shadowed decl chains. 1422 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1423 // Move up the scope chain until we find the nearest enclosing 1424 // non-transparent context. The declaration will be introduced into this 1425 // scope. 1426 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1427 S = S->getParent(); 1428 1429 // Add scoped declarations into their context, so that they can be 1430 // found later. Declarations without a context won't be inserted 1431 // into any context. 1432 if (AddToContext) 1433 CurContext->addDecl(D); 1434 1435 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1436 // are function-local declarations. 1437 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1438 !D->getDeclContext()->getRedeclContext()->Equals( 1439 D->getLexicalDeclContext()->getRedeclContext()) && 1440 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1441 return; 1442 1443 // Template instantiations should also not be pushed into scope. 1444 if (isa<FunctionDecl>(D) && 1445 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1446 return; 1447 1448 // If this replaces anything in the current scope, 1449 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1450 IEnd = IdResolver.end(); 1451 for (; I != IEnd; ++I) { 1452 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1453 S->RemoveDecl(*I); 1454 IdResolver.RemoveDecl(*I); 1455 1456 // Should only need to replace one decl. 1457 break; 1458 } 1459 } 1460 1461 S->AddDecl(D); 1462 1463 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1464 // Implicitly-generated labels may end up getting generated in an order that 1465 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1466 // the label at the appropriate place in the identifier chain. 1467 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1468 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1469 if (IDC == CurContext) { 1470 if (!S->isDeclScope(*I)) 1471 continue; 1472 } else if (IDC->Encloses(CurContext)) 1473 break; 1474 } 1475 1476 IdResolver.InsertDeclAfter(I, D); 1477 } else { 1478 IdResolver.AddDecl(D); 1479 } 1480 } 1481 1482 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1483 bool AllowInlineNamespace) { 1484 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1485 } 1486 1487 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1488 DeclContext *TargetDC = DC->getPrimaryContext(); 1489 do { 1490 if (DeclContext *ScopeDC = S->getEntity()) 1491 if (ScopeDC->getPrimaryContext() == TargetDC) 1492 return S; 1493 } while ((S = S->getParent())); 1494 1495 return nullptr; 1496 } 1497 1498 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1499 DeclContext*, 1500 ASTContext&); 1501 1502 /// Filters out lookup results that don't fall within the given scope 1503 /// as determined by isDeclInScope. 1504 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1505 bool ConsiderLinkage, 1506 bool AllowInlineNamespace) { 1507 LookupResult::Filter F = R.makeFilter(); 1508 while (F.hasNext()) { 1509 NamedDecl *D = F.next(); 1510 1511 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1512 continue; 1513 1514 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1515 continue; 1516 1517 F.erase(); 1518 } 1519 1520 F.done(); 1521 } 1522 1523 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1524 /// have compatible owning modules. 1525 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1526 // FIXME: The Modules TS is not clear about how friend declarations are 1527 // to be treated. It's not meaningful to have different owning modules for 1528 // linkage in redeclarations of the same entity, so for now allow the 1529 // redeclaration and change the owning modules to match. 1530 if (New->getFriendObjectKind() && 1531 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1532 New->setLocalOwningModule(Old->getOwningModule()); 1533 makeMergedDefinitionVisible(New); 1534 return false; 1535 } 1536 1537 Module *NewM = New->getOwningModule(); 1538 Module *OldM = Old->getOwningModule(); 1539 1540 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1541 NewM = NewM->Parent; 1542 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1543 OldM = OldM->Parent; 1544 1545 if (NewM == OldM) 1546 return false; 1547 1548 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1549 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1550 if (NewIsModuleInterface || OldIsModuleInterface) { 1551 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1552 // if a declaration of D [...] appears in the purview of a module, all 1553 // other such declarations shall appear in the purview of the same module 1554 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1555 << New 1556 << NewIsModuleInterface 1557 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1558 << OldIsModuleInterface 1559 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1560 Diag(Old->getLocation(), diag::note_previous_declaration); 1561 New->setInvalidDecl(); 1562 return true; 1563 } 1564 1565 return false; 1566 } 1567 1568 static bool isUsingDecl(NamedDecl *D) { 1569 return isa<UsingShadowDecl>(D) || 1570 isa<UnresolvedUsingTypenameDecl>(D) || 1571 isa<UnresolvedUsingValueDecl>(D); 1572 } 1573 1574 /// Removes using shadow declarations from the lookup results. 1575 static void RemoveUsingDecls(LookupResult &R) { 1576 LookupResult::Filter F = R.makeFilter(); 1577 while (F.hasNext()) 1578 if (isUsingDecl(F.next())) 1579 F.erase(); 1580 1581 F.done(); 1582 } 1583 1584 /// Check for this common pattern: 1585 /// @code 1586 /// class S { 1587 /// S(const S&); // DO NOT IMPLEMENT 1588 /// void operator=(const S&); // DO NOT IMPLEMENT 1589 /// }; 1590 /// @endcode 1591 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1592 // FIXME: Should check for private access too but access is set after we get 1593 // the decl here. 1594 if (D->doesThisDeclarationHaveABody()) 1595 return false; 1596 1597 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1598 return CD->isCopyConstructor(); 1599 return D->isCopyAssignmentOperator(); 1600 } 1601 1602 // We need this to handle 1603 // 1604 // typedef struct { 1605 // void *foo() { return 0; } 1606 // } A; 1607 // 1608 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1609 // for example. If 'A', foo will have external linkage. If we have '*A', 1610 // foo will have no linkage. Since we can't know until we get to the end 1611 // of the typedef, this function finds out if D might have non-external linkage. 1612 // Callers should verify at the end of the TU if it D has external linkage or 1613 // not. 1614 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1615 const DeclContext *DC = D->getDeclContext(); 1616 while (!DC->isTranslationUnit()) { 1617 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1618 if (!RD->hasNameForLinkage()) 1619 return true; 1620 } 1621 DC = DC->getParent(); 1622 } 1623 1624 return !D->isExternallyVisible(); 1625 } 1626 1627 // FIXME: This needs to be refactored; some other isInMainFile users want 1628 // these semantics. 1629 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1630 if (S.TUKind != TU_Complete) 1631 return false; 1632 return S.SourceMgr.isInMainFile(Loc); 1633 } 1634 1635 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1636 assert(D); 1637 1638 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1639 return false; 1640 1641 // Ignore all entities declared within templates, and out-of-line definitions 1642 // of members of class templates. 1643 if (D->getDeclContext()->isDependentContext() || 1644 D->getLexicalDeclContext()->isDependentContext()) 1645 return false; 1646 1647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1648 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1649 return false; 1650 // A non-out-of-line declaration of a member specialization was implicitly 1651 // instantiated; it's the out-of-line declaration that we're interested in. 1652 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1653 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1654 return false; 1655 1656 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1657 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1658 return false; 1659 } else { 1660 // 'static inline' functions are defined in headers; don't warn. 1661 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1662 return false; 1663 } 1664 1665 if (FD->doesThisDeclarationHaveABody() && 1666 Context.DeclMustBeEmitted(FD)) 1667 return false; 1668 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1669 // Constants and utility variables are defined in headers with internal 1670 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1671 // like "inline".) 1672 if (!isMainFileLoc(*this, VD->getLocation())) 1673 return false; 1674 1675 if (Context.DeclMustBeEmitted(VD)) 1676 return false; 1677 1678 if (VD->isStaticDataMember() && 1679 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1680 return false; 1681 if (VD->isStaticDataMember() && 1682 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1683 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1684 return false; 1685 1686 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1687 return false; 1688 } else { 1689 return false; 1690 } 1691 1692 // Only warn for unused decls internal to the translation unit. 1693 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1694 // for inline functions defined in the main source file, for instance. 1695 return mightHaveNonExternalLinkage(D); 1696 } 1697 1698 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1699 if (!D) 1700 return; 1701 1702 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1703 const FunctionDecl *First = FD->getFirstDecl(); 1704 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1705 return; // First should already be in the vector. 1706 } 1707 1708 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1709 const VarDecl *First = VD->getFirstDecl(); 1710 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1711 return; // First should already be in the vector. 1712 } 1713 1714 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1715 UnusedFileScopedDecls.push_back(D); 1716 } 1717 1718 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1719 if (D->isInvalidDecl()) 1720 return false; 1721 1722 bool Referenced = false; 1723 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1724 // For a decomposition declaration, warn if none of the bindings are 1725 // referenced, instead of if the variable itself is referenced (which 1726 // it is, by the bindings' expressions). 1727 for (auto *BD : DD->bindings()) { 1728 if (BD->isReferenced()) { 1729 Referenced = true; 1730 break; 1731 } 1732 } 1733 } else if (!D->getDeclName()) { 1734 return false; 1735 } else if (D->isReferenced() || D->isUsed()) { 1736 Referenced = true; 1737 } 1738 1739 if (Referenced || D->hasAttr<UnusedAttr>() || 1740 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1741 return false; 1742 1743 if (isa<LabelDecl>(D)) 1744 return true; 1745 1746 // Except for labels, we only care about unused decls that are local to 1747 // functions. 1748 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1749 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1750 // For dependent types, the diagnostic is deferred. 1751 WithinFunction = 1752 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1753 if (!WithinFunction) 1754 return false; 1755 1756 if (isa<TypedefNameDecl>(D)) 1757 return true; 1758 1759 // White-list anything that isn't a local variable. 1760 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1761 return false; 1762 1763 // Types of valid local variables should be complete, so this should succeed. 1764 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1765 1766 // White-list anything with an __attribute__((unused)) type. 1767 const auto *Ty = VD->getType().getTypePtr(); 1768 1769 // Only look at the outermost level of typedef. 1770 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1771 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1772 return false; 1773 } 1774 1775 // If we failed to complete the type for some reason, or if the type is 1776 // dependent, don't diagnose the variable. 1777 if (Ty->isIncompleteType() || Ty->isDependentType()) 1778 return false; 1779 1780 // Look at the element type to ensure that the warning behaviour is 1781 // consistent for both scalars and arrays. 1782 Ty = Ty->getBaseElementTypeUnsafe(); 1783 1784 if (const TagType *TT = Ty->getAs<TagType>()) { 1785 const TagDecl *Tag = TT->getDecl(); 1786 if (Tag->hasAttr<UnusedAttr>()) 1787 return false; 1788 1789 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1790 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1791 return false; 1792 1793 if (const Expr *Init = VD->getInit()) { 1794 if (const ExprWithCleanups *Cleanups = 1795 dyn_cast<ExprWithCleanups>(Init)) 1796 Init = Cleanups->getSubExpr(); 1797 const CXXConstructExpr *Construct = 1798 dyn_cast<CXXConstructExpr>(Init); 1799 if (Construct && !Construct->isElidable()) { 1800 CXXConstructorDecl *CD = Construct->getConstructor(); 1801 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1802 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1803 return false; 1804 } 1805 } 1806 } 1807 } 1808 1809 // TODO: __attribute__((unused)) templates? 1810 } 1811 1812 return true; 1813 } 1814 1815 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1816 FixItHint &Hint) { 1817 if (isa<LabelDecl>(D)) { 1818 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1819 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1820 true); 1821 if (AfterColon.isInvalid()) 1822 return; 1823 Hint = FixItHint::CreateRemoval( 1824 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1825 } 1826 } 1827 1828 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1829 if (D->getTypeForDecl()->isDependentType()) 1830 return; 1831 1832 for (auto *TmpD : D->decls()) { 1833 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1834 DiagnoseUnusedDecl(T); 1835 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1836 DiagnoseUnusedNestedTypedefs(R); 1837 } 1838 } 1839 1840 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1841 /// unless they are marked attr(unused). 1842 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1843 if (!ShouldDiagnoseUnusedDecl(D)) 1844 return; 1845 1846 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1847 // typedefs can be referenced later on, so the diagnostics are emitted 1848 // at end-of-translation-unit. 1849 UnusedLocalTypedefNameCandidates.insert(TD); 1850 return; 1851 } 1852 1853 FixItHint Hint; 1854 GenerateFixForUnusedDecl(D, Context, Hint); 1855 1856 unsigned DiagID; 1857 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1858 DiagID = diag::warn_unused_exception_param; 1859 else if (isa<LabelDecl>(D)) 1860 DiagID = diag::warn_unused_label; 1861 else 1862 DiagID = diag::warn_unused_variable; 1863 1864 Diag(D->getLocation(), DiagID) << D << Hint; 1865 } 1866 1867 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1868 // Verify that we have no forward references left. If so, there was a goto 1869 // or address of a label taken, but no definition of it. Label fwd 1870 // definitions are indicated with a null substmt which is also not a resolved 1871 // MS inline assembly label name. 1872 bool Diagnose = false; 1873 if (L->isMSAsmLabel()) 1874 Diagnose = !L->isResolvedMSAsmLabel(); 1875 else 1876 Diagnose = L->getStmt() == nullptr; 1877 if (Diagnose) 1878 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1879 } 1880 1881 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1882 S->mergeNRVOIntoParent(); 1883 1884 if (S->decl_empty()) return; 1885 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1886 "Scope shouldn't contain decls!"); 1887 1888 for (auto *TmpD : S->decls()) { 1889 assert(TmpD && "This decl didn't get pushed??"); 1890 1891 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1892 NamedDecl *D = cast<NamedDecl>(TmpD); 1893 1894 // Diagnose unused variables in this scope. 1895 if (!S->hasUnrecoverableErrorOccurred()) { 1896 DiagnoseUnusedDecl(D); 1897 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1898 DiagnoseUnusedNestedTypedefs(RD); 1899 } 1900 1901 if (!D->getDeclName()) continue; 1902 1903 // If this was a forward reference to a label, verify it was defined. 1904 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1905 CheckPoppedLabel(LD, *this); 1906 1907 // Remove this name from our lexical scope, and warn on it if we haven't 1908 // already. 1909 IdResolver.RemoveDecl(D); 1910 auto ShadowI = ShadowingDecls.find(D); 1911 if (ShadowI != ShadowingDecls.end()) { 1912 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1913 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1914 << D << FD << FD->getParent(); 1915 Diag(FD->getLocation(), diag::note_previous_declaration); 1916 } 1917 ShadowingDecls.erase(ShadowI); 1918 } 1919 } 1920 } 1921 1922 /// Look for an Objective-C class in the translation unit. 1923 /// 1924 /// \param Id The name of the Objective-C class we're looking for. If 1925 /// typo-correction fixes this name, the Id will be updated 1926 /// to the fixed name. 1927 /// 1928 /// \param IdLoc The location of the name in the translation unit. 1929 /// 1930 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1931 /// if there is no class with the given name. 1932 /// 1933 /// \returns The declaration of the named Objective-C class, or NULL if the 1934 /// class could not be found. 1935 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1936 SourceLocation IdLoc, 1937 bool DoTypoCorrection) { 1938 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1939 // creation from this context. 1940 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1941 1942 if (!IDecl && DoTypoCorrection) { 1943 // Perform typo correction at the given location, but only if we 1944 // find an Objective-C class name. 1945 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1946 if (TypoCorrection C = 1947 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1948 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1949 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1950 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1951 Id = IDecl->getIdentifier(); 1952 } 1953 } 1954 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1955 // This routine must always return a class definition, if any. 1956 if (Def && Def->getDefinition()) 1957 Def = Def->getDefinition(); 1958 return Def; 1959 } 1960 1961 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1962 /// from S, where a non-field would be declared. This routine copes 1963 /// with the difference between C and C++ scoping rules in structs and 1964 /// unions. For example, the following code is well-formed in C but 1965 /// ill-formed in C++: 1966 /// @code 1967 /// struct S6 { 1968 /// enum { BAR } e; 1969 /// }; 1970 /// 1971 /// void test_S6() { 1972 /// struct S6 a; 1973 /// a.e = BAR; 1974 /// } 1975 /// @endcode 1976 /// For the declaration of BAR, this routine will return a different 1977 /// scope. The scope S will be the scope of the unnamed enumeration 1978 /// within S6. In C++, this routine will return the scope associated 1979 /// with S6, because the enumeration's scope is a transparent 1980 /// context but structures can contain non-field names. In C, this 1981 /// routine will return the translation unit scope, since the 1982 /// enumeration's scope is a transparent context and structures cannot 1983 /// contain non-field names. 1984 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1985 while (((S->getFlags() & Scope::DeclScope) == 0) || 1986 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1987 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1988 S = S->getParent(); 1989 return S; 1990 } 1991 1992 /// Looks up the declaration of "struct objc_super" and 1993 /// saves it for later use in building builtin declaration of 1994 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1995 /// pre-existing declaration exists no action takes place. 1996 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1997 IdentifierInfo *II) { 1998 if (!II->isStr("objc_msgSendSuper")) 1999 return; 2000 ASTContext &Context = ThisSema.Context; 2001 2002 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2003 SourceLocation(), Sema::LookupTagName); 2004 ThisSema.LookupName(Result, S); 2005 if (Result.getResultKind() == LookupResult::Found) 2006 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2007 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2008 } 2009 2010 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2011 ASTContext::GetBuiltinTypeError Error) { 2012 switch (Error) { 2013 case ASTContext::GE_None: 2014 return ""; 2015 case ASTContext::GE_Missing_type: 2016 return BuiltinInfo.getHeaderName(ID); 2017 case ASTContext::GE_Missing_stdio: 2018 return "stdio.h"; 2019 case ASTContext::GE_Missing_setjmp: 2020 return "setjmp.h"; 2021 case ASTContext::GE_Missing_ucontext: 2022 return "ucontext.h"; 2023 } 2024 llvm_unreachable("unhandled error kind"); 2025 } 2026 2027 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2028 /// file scope. lazily create a decl for it. ForRedeclaration is true 2029 /// if we're creating this built-in in anticipation of redeclaring the 2030 /// built-in. 2031 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2032 Scope *S, bool ForRedeclaration, 2033 SourceLocation Loc) { 2034 LookupPredefedObjCSuperType(*this, S, II); 2035 2036 ASTContext::GetBuiltinTypeError Error; 2037 QualType R = Context.GetBuiltinType(ID, Error); 2038 if (Error) { 2039 if (!ForRedeclaration) 2040 return nullptr; 2041 2042 // If we have a builtin without an associated type we should not emit a 2043 // warning when we were not able to find a type for it. 2044 if (Error == ASTContext::GE_Missing_type) 2045 return nullptr; 2046 2047 // If we could not find a type for setjmp it is because the jmp_buf type was 2048 // not defined prior to the setjmp declaration. 2049 if (Error == ASTContext::GE_Missing_setjmp) { 2050 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2051 << Context.BuiltinInfo.getName(ID); 2052 return nullptr; 2053 } 2054 2055 // Generally, we emit a warning that the declaration requires the 2056 // appropriate header. 2057 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2058 << getHeaderName(Context.BuiltinInfo, ID, Error) 2059 << Context.BuiltinInfo.getName(ID); 2060 return nullptr; 2061 } 2062 2063 if (!ForRedeclaration && 2064 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2065 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2066 Diag(Loc, diag::ext_implicit_lib_function_decl) 2067 << Context.BuiltinInfo.getName(ID) << R; 2068 if (Context.BuiltinInfo.getHeaderName(ID) && 2069 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2070 Diag(Loc, diag::note_include_header_or_declare) 2071 << Context.BuiltinInfo.getHeaderName(ID) 2072 << Context.BuiltinInfo.getName(ID); 2073 } 2074 2075 if (R.isNull()) 2076 return nullptr; 2077 2078 DeclContext *Parent = Context.getTranslationUnitDecl(); 2079 if (getLangOpts().CPlusPlus) { 2080 LinkageSpecDecl *CLinkageDecl = 2081 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2082 LinkageSpecDecl::lang_c, false); 2083 CLinkageDecl->setImplicit(); 2084 Parent->addDecl(CLinkageDecl); 2085 Parent = CLinkageDecl; 2086 } 2087 2088 FunctionDecl *New = FunctionDecl::Create(Context, 2089 Parent, 2090 Loc, Loc, II, R, /*TInfo=*/nullptr, 2091 SC_Extern, 2092 false, 2093 R->isFunctionProtoType()); 2094 New->setImplicit(); 2095 2096 // Create Decl objects for each parameter, adding them to the 2097 // FunctionDecl. 2098 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2099 SmallVector<ParmVarDecl*, 16> Params; 2100 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2101 ParmVarDecl *parm = 2102 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2103 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2104 SC_None, nullptr); 2105 parm->setScopeInfo(0, i); 2106 Params.push_back(parm); 2107 } 2108 New->setParams(Params); 2109 } 2110 2111 AddKnownFunctionAttributes(New); 2112 RegisterLocallyScopedExternCDecl(New, S); 2113 2114 // TUScope is the translation-unit scope to insert this function into. 2115 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2116 // relate Scopes to DeclContexts, and probably eliminate CurContext 2117 // entirely, but we're not there yet. 2118 DeclContext *SavedContext = CurContext; 2119 CurContext = Parent; 2120 PushOnScopeChains(New, TUScope); 2121 CurContext = SavedContext; 2122 return New; 2123 } 2124 2125 /// Typedef declarations don't have linkage, but they still denote the same 2126 /// entity if their types are the same. 2127 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2128 /// isSameEntity. 2129 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2130 TypedefNameDecl *Decl, 2131 LookupResult &Previous) { 2132 // This is only interesting when modules are enabled. 2133 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2134 return; 2135 2136 // Empty sets are uninteresting. 2137 if (Previous.empty()) 2138 return; 2139 2140 LookupResult::Filter Filter = Previous.makeFilter(); 2141 while (Filter.hasNext()) { 2142 NamedDecl *Old = Filter.next(); 2143 2144 // Non-hidden declarations are never ignored. 2145 if (S.isVisible(Old)) 2146 continue; 2147 2148 // Declarations of the same entity are not ignored, even if they have 2149 // different linkages. 2150 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2151 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2152 Decl->getUnderlyingType())) 2153 continue; 2154 2155 // If both declarations give a tag declaration a typedef name for linkage 2156 // purposes, then they declare the same entity. 2157 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2158 Decl->getAnonDeclWithTypedefName()) 2159 continue; 2160 } 2161 2162 Filter.erase(); 2163 } 2164 2165 Filter.done(); 2166 } 2167 2168 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2169 QualType OldType; 2170 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2171 OldType = OldTypedef->getUnderlyingType(); 2172 else 2173 OldType = Context.getTypeDeclType(Old); 2174 QualType NewType = New->getUnderlyingType(); 2175 2176 if (NewType->isVariablyModifiedType()) { 2177 // Must not redefine a typedef with a variably-modified type. 2178 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2179 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2180 << Kind << NewType; 2181 if (Old->getLocation().isValid()) 2182 notePreviousDefinition(Old, New->getLocation()); 2183 New->setInvalidDecl(); 2184 return true; 2185 } 2186 2187 if (OldType != NewType && 2188 !OldType->isDependentType() && 2189 !NewType->isDependentType() && 2190 !Context.hasSameType(OldType, NewType)) { 2191 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2192 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2193 << Kind << NewType << OldType; 2194 if (Old->getLocation().isValid()) 2195 notePreviousDefinition(Old, New->getLocation()); 2196 New->setInvalidDecl(); 2197 return true; 2198 } 2199 return false; 2200 } 2201 2202 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2203 /// same name and scope as a previous declaration 'Old'. Figure out 2204 /// how to resolve this situation, merging decls or emitting 2205 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2206 /// 2207 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2208 LookupResult &OldDecls) { 2209 // If the new decl is known invalid already, don't bother doing any 2210 // merging checks. 2211 if (New->isInvalidDecl()) return; 2212 2213 // Allow multiple definitions for ObjC built-in typedefs. 2214 // FIXME: Verify the underlying types are equivalent! 2215 if (getLangOpts().ObjC) { 2216 const IdentifierInfo *TypeID = New->getIdentifier(); 2217 switch (TypeID->getLength()) { 2218 default: break; 2219 case 2: 2220 { 2221 if (!TypeID->isStr("id")) 2222 break; 2223 QualType T = New->getUnderlyingType(); 2224 if (!T->isPointerType()) 2225 break; 2226 if (!T->isVoidPointerType()) { 2227 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2228 if (!PT->isStructureType()) 2229 break; 2230 } 2231 Context.setObjCIdRedefinitionType(T); 2232 // Install the built-in type for 'id', ignoring the current definition. 2233 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2234 return; 2235 } 2236 case 5: 2237 if (!TypeID->isStr("Class")) 2238 break; 2239 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2240 // Install the built-in type for 'Class', ignoring the current definition. 2241 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2242 return; 2243 case 3: 2244 if (!TypeID->isStr("SEL")) 2245 break; 2246 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2247 // Install the built-in type for 'SEL', ignoring the current definition. 2248 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2249 return; 2250 } 2251 // Fall through - the typedef name was not a builtin type. 2252 } 2253 2254 // Verify the old decl was also a type. 2255 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2256 if (!Old) { 2257 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2258 << New->getDeclName(); 2259 2260 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2261 if (OldD->getLocation().isValid()) 2262 notePreviousDefinition(OldD, New->getLocation()); 2263 2264 return New->setInvalidDecl(); 2265 } 2266 2267 // If the old declaration is invalid, just give up here. 2268 if (Old->isInvalidDecl()) 2269 return New->setInvalidDecl(); 2270 2271 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2272 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2273 auto *NewTag = New->getAnonDeclWithTypedefName(); 2274 NamedDecl *Hidden = nullptr; 2275 if (OldTag && NewTag && 2276 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2277 !hasVisibleDefinition(OldTag, &Hidden)) { 2278 // There is a definition of this tag, but it is not visible. Use it 2279 // instead of our tag. 2280 New->setTypeForDecl(OldTD->getTypeForDecl()); 2281 if (OldTD->isModed()) 2282 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2283 OldTD->getUnderlyingType()); 2284 else 2285 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2286 2287 // Make the old tag definition visible. 2288 makeMergedDefinitionVisible(Hidden); 2289 2290 // If this was an unscoped enumeration, yank all of its enumerators 2291 // out of the scope. 2292 if (isa<EnumDecl>(NewTag)) { 2293 Scope *EnumScope = getNonFieldDeclScope(S); 2294 for (auto *D : NewTag->decls()) { 2295 auto *ED = cast<EnumConstantDecl>(D); 2296 assert(EnumScope->isDeclScope(ED)); 2297 EnumScope->RemoveDecl(ED); 2298 IdResolver.RemoveDecl(ED); 2299 ED->getLexicalDeclContext()->removeDecl(ED); 2300 } 2301 } 2302 } 2303 } 2304 2305 // If the typedef types are not identical, reject them in all languages and 2306 // with any extensions enabled. 2307 if (isIncompatibleTypedef(Old, New)) 2308 return; 2309 2310 // The types match. Link up the redeclaration chain and merge attributes if 2311 // the old declaration was a typedef. 2312 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2313 New->setPreviousDecl(Typedef); 2314 mergeDeclAttributes(New, Old); 2315 } 2316 2317 if (getLangOpts().MicrosoftExt) 2318 return; 2319 2320 if (getLangOpts().CPlusPlus) { 2321 // C++ [dcl.typedef]p2: 2322 // In a given non-class scope, a typedef specifier can be used to 2323 // redefine the name of any type declared in that scope to refer 2324 // to the type to which it already refers. 2325 if (!isa<CXXRecordDecl>(CurContext)) 2326 return; 2327 2328 // C++0x [dcl.typedef]p4: 2329 // In a given class scope, a typedef specifier can be used to redefine 2330 // any class-name declared in that scope that is not also a typedef-name 2331 // to refer to the type to which it already refers. 2332 // 2333 // This wording came in via DR424, which was a correction to the 2334 // wording in DR56, which accidentally banned code like: 2335 // 2336 // struct S { 2337 // typedef struct A { } A; 2338 // }; 2339 // 2340 // in the C++03 standard. We implement the C++0x semantics, which 2341 // allow the above but disallow 2342 // 2343 // struct S { 2344 // typedef int I; 2345 // typedef int I; 2346 // }; 2347 // 2348 // since that was the intent of DR56. 2349 if (!isa<TypedefNameDecl>(Old)) 2350 return; 2351 2352 Diag(New->getLocation(), diag::err_redefinition) 2353 << New->getDeclName(); 2354 notePreviousDefinition(Old, New->getLocation()); 2355 return New->setInvalidDecl(); 2356 } 2357 2358 // Modules always permit redefinition of typedefs, as does C11. 2359 if (getLangOpts().Modules || getLangOpts().C11) 2360 return; 2361 2362 // If we have a redefinition of a typedef in C, emit a warning. This warning 2363 // is normally mapped to an error, but can be controlled with 2364 // -Wtypedef-redefinition. If either the original or the redefinition is 2365 // in a system header, don't emit this for compatibility with GCC. 2366 if (getDiagnostics().getSuppressSystemWarnings() && 2367 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2368 (Old->isImplicit() || 2369 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2370 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2371 return; 2372 2373 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2374 << New->getDeclName(); 2375 notePreviousDefinition(Old, New->getLocation()); 2376 } 2377 2378 /// DeclhasAttr - returns true if decl Declaration already has the target 2379 /// attribute. 2380 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2381 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2382 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2383 for (const auto *i : D->attrs()) 2384 if (i->getKind() == A->getKind()) { 2385 if (Ann) { 2386 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2387 return true; 2388 continue; 2389 } 2390 // FIXME: Don't hardcode this check 2391 if (OA && isa<OwnershipAttr>(i)) 2392 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2393 return true; 2394 } 2395 2396 return false; 2397 } 2398 2399 static bool isAttributeTargetADefinition(Decl *D) { 2400 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2401 return VD->isThisDeclarationADefinition(); 2402 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2403 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2404 return true; 2405 } 2406 2407 /// Merge alignment attributes from \p Old to \p New, taking into account the 2408 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2409 /// 2410 /// \return \c true if any attributes were added to \p New. 2411 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2412 // Look for alignas attributes on Old, and pick out whichever attribute 2413 // specifies the strictest alignment requirement. 2414 AlignedAttr *OldAlignasAttr = nullptr; 2415 AlignedAttr *OldStrictestAlignAttr = nullptr; 2416 unsigned OldAlign = 0; 2417 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2418 // FIXME: We have no way of representing inherited dependent alignments 2419 // in a case like: 2420 // template<int A, int B> struct alignas(A) X; 2421 // template<int A, int B> struct alignas(B) X {}; 2422 // For now, we just ignore any alignas attributes which are not on the 2423 // definition in such a case. 2424 if (I->isAlignmentDependent()) 2425 return false; 2426 2427 if (I->isAlignas()) 2428 OldAlignasAttr = I; 2429 2430 unsigned Align = I->getAlignment(S.Context); 2431 if (Align > OldAlign) { 2432 OldAlign = Align; 2433 OldStrictestAlignAttr = I; 2434 } 2435 } 2436 2437 // Look for alignas attributes on New. 2438 AlignedAttr *NewAlignasAttr = nullptr; 2439 unsigned NewAlign = 0; 2440 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2441 if (I->isAlignmentDependent()) 2442 return false; 2443 2444 if (I->isAlignas()) 2445 NewAlignasAttr = I; 2446 2447 unsigned Align = I->getAlignment(S.Context); 2448 if (Align > NewAlign) 2449 NewAlign = Align; 2450 } 2451 2452 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2453 // Both declarations have 'alignas' attributes. We require them to match. 2454 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2455 // fall short. (If two declarations both have alignas, they must both match 2456 // every definition, and so must match each other if there is a definition.) 2457 2458 // If either declaration only contains 'alignas(0)' specifiers, then it 2459 // specifies the natural alignment for the type. 2460 if (OldAlign == 0 || NewAlign == 0) { 2461 QualType Ty; 2462 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2463 Ty = VD->getType(); 2464 else 2465 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2466 2467 if (OldAlign == 0) 2468 OldAlign = S.Context.getTypeAlign(Ty); 2469 if (NewAlign == 0) 2470 NewAlign = S.Context.getTypeAlign(Ty); 2471 } 2472 2473 if (OldAlign != NewAlign) { 2474 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2475 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2476 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2477 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2478 } 2479 } 2480 2481 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2482 // C++11 [dcl.align]p6: 2483 // if any declaration of an entity has an alignment-specifier, 2484 // every defining declaration of that entity shall specify an 2485 // equivalent alignment. 2486 // C11 6.7.5/7: 2487 // If the definition of an object does not have an alignment 2488 // specifier, any other declaration of that object shall also 2489 // have no alignment specifier. 2490 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2491 << OldAlignasAttr; 2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2493 << OldAlignasAttr; 2494 } 2495 2496 bool AnyAdded = false; 2497 2498 // Ensure we have an attribute representing the strictest alignment. 2499 if (OldAlign > NewAlign) { 2500 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2501 Clone->setInherited(true); 2502 New->addAttr(Clone); 2503 AnyAdded = true; 2504 } 2505 2506 // Ensure we have an alignas attribute if the old declaration had one. 2507 if (OldAlignasAttr && !NewAlignasAttr && 2508 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2509 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2510 Clone->setInherited(true); 2511 New->addAttr(Clone); 2512 AnyAdded = true; 2513 } 2514 2515 return AnyAdded; 2516 } 2517 2518 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2519 const InheritableAttr *Attr, 2520 Sema::AvailabilityMergeKind AMK) { 2521 // This function copies an attribute Attr from a previous declaration to the 2522 // new declaration D if the new declaration doesn't itself have that attribute 2523 // yet or if that attribute allows duplicates. 2524 // If you're adding a new attribute that requires logic different from 2525 // "use explicit attribute on decl if present, else use attribute from 2526 // previous decl", for example if the attribute needs to be consistent 2527 // between redeclarations, you need to call a custom merge function here. 2528 InheritableAttr *NewAttr = nullptr; 2529 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2530 NewAttr = S.mergeAvailabilityAttr( 2531 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2532 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2533 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2534 AA->getPriority()); 2535 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2536 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2537 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2538 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2539 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2540 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2541 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2542 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2543 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2544 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2545 FA->getFirstArg()); 2546 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2547 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2548 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2549 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2550 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2551 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2552 IA->getSemanticSpelling()); 2553 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2554 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2555 &S.Context.Idents.get(AA->getSpelling())); 2556 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2557 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2558 isa<CUDAGlobalAttr>(Attr))) { 2559 // CUDA target attributes are part of function signature for 2560 // overloading purposes and must not be merged. 2561 return false; 2562 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2563 NewAttr = S.mergeMinSizeAttr(D, *MA); 2564 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2565 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2566 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2567 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2568 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2569 NewAttr = S.mergeCommonAttr(D, *CommonA); 2570 else if (isa<AlignedAttr>(Attr)) 2571 // AlignedAttrs are handled separately, because we need to handle all 2572 // such attributes on a declaration at the same time. 2573 NewAttr = nullptr; 2574 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2575 (AMK == Sema::AMK_Override || 2576 AMK == Sema::AMK_ProtocolImplementation)) 2577 NewAttr = nullptr; 2578 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2579 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2580 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2581 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2582 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2583 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2584 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2585 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2586 2587 if (NewAttr) { 2588 NewAttr->setInherited(true); 2589 D->addAttr(NewAttr); 2590 if (isa<MSInheritanceAttr>(NewAttr)) 2591 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2592 return true; 2593 } 2594 2595 return false; 2596 } 2597 2598 static const NamedDecl *getDefinition(const Decl *D) { 2599 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2600 return TD->getDefinition(); 2601 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2602 const VarDecl *Def = VD->getDefinition(); 2603 if (Def) 2604 return Def; 2605 return VD->getActingDefinition(); 2606 } 2607 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2608 return FD->getDefinition(); 2609 return nullptr; 2610 } 2611 2612 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2613 for (const auto *Attribute : D->attrs()) 2614 if (Attribute->getKind() == Kind) 2615 return true; 2616 return false; 2617 } 2618 2619 /// checkNewAttributesAfterDef - If we already have a definition, check that 2620 /// there are no new attributes in this declaration. 2621 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2622 if (!New->hasAttrs()) 2623 return; 2624 2625 const NamedDecl *Def = getDefinition(Old); 2626 if (!Def || Def == New) 2627 return; 2628 2629 AttrVec &NewAttributes = New->getAttrs(); 2630 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2631 const Attr *NewAttribute = NewAttributes[I]; 2632 2633 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2634 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2635 Sema::SkipBodyInfo SkipBody; 2636 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2637 2638 // If we're skipping this definition, drop the "alias" attribute. 2639 if (SkipBody.ShouldSkip) { 2640 NewAttributes.erase(NewAttributes.begin() + I); 2641 --E; 2642 continue; 2643 } 2644 } else { 2645 VarDecl *VD = cast<VarDecl>(New); 2646 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2647 VarDecl::TentativeDefinition 2648 ? diag::err_alias_after_tentative 2649 : diag::err_redefinition; 2650 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2651 if (Diag == diag::err_redefinition) 2652 S.notePreviousDefinition(Def, VD->getLocation()); 2653 else 2654 S.Diag(Def->getLocation(), diag::note_previous_definition); 2655 VD->setInvalidDecl(); 2656 } 2657 ++I; 2658 continue; 2659 } 2660 2661 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2662 // Tentative definitions are only interesting for the alias check above. 2663 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2664 ++I; 2665 continue; 2666 } 2667 } 2668 2669 if (hasAttribute(Def, NewAttribute->getKind())) { 2670 ++I; 2671 continue; // regular attr merging will take care of validating this. 2672 } 2673 2674 if (isa<C11NoReturnAttr>(NewAttribute)) { 2675 // C's _Noreturn is allowed to be added to a function after it is defined. 2676 ++I; 2677 continue; 2678 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2679 if (AA->isAlignas()) { 2680 // C++11 [dcl.align]p6: 2681 // if any declaration of an entity has an alignment-specifier, 2682 // every defining declaration of that entity shall specify an 2683 // equivalent alignment. 2684 // C11 6.7.5/7: 2685 // If the definition of an object does not have an alignment 2686 // specifier, any other declaration of that object shall also 2687 // have no alignment specifier. 2688 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2689 << AA; 2690 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2691 << AA; 2692 NewAttributes.erase(NewAttributes.begin() + I); 2693 --E; 2694 continue; 2695 } 2696 } else if (isa<SelectAnyAttr>(NewAttribute) && 2697 cast<VarDecl>(New)->isInline() && 2698 !cast<VarDecl>(New)->isInlineSpecified()) { 2699 // Don't warn about applying selectany to implicitly inline variables. 2700 // Older compilers and language modes would require the use of selectany 2701 // to make such variables inline, and it would have no effect if we 2702 // honored it. 2703 ++I; 2704 continue; 2705 } 2706 2707 S.Diag(NewAttribute->getLocation(), 2708 diag::warn_attribute_precede_definition); 2709 S.Diag(Def->getLocation(), diag::note_previous_definition); 2710 NewAttributes.erase(NewAttributes.begin() + I); 2711 --E; 2712 } 2713 } 2714 2715 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2716 const ConstInitAttr *CIAttr, 2717 bool AttrBeforeInit) { 2718 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2719 2720 // Figure out a good way to write this specifier on the old declaration. 2721 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2722 // enough of the attribute list spelling information to extract that without 2723 // heroics. 2724 std::string SuitableSpelling; 2725 if (S.getLangOpts().CPlusPlus2a) 2726 SuitableSpelling = 2727 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}); 2728 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2729 SuitableSpelling = S.PP.getLastMacroWithSpelling( 2730 InsertLoc, 2731 {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"), 2732 tok::coloncolon, 2733 S.PP.getIdentifierInfo("require_constant_initialization"), 2734 tok::r_square, tok::r_square}); 2735 if (SuitableSpelling.empty()) 2736 SuitableSpelling = S.PP.getLastMacroWithSpelling( 2737 InsertLoc, 2738 {tok::kw___attribute, tok::l_paren, tok::r_paren, 2739 S.PP.getIdentifierInfo("require_constant_initialization"), 2740 tok::r_paren, tok::r_paren}); 2741 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2742 SuitableSpelling = "constinit"; 2743 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2744 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2745 if (SuitableSpelling.empty()) 2746 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2747 SuitableSpelling += " "; 2748 2749 if (AttrBeforeInit) { 2750 // extern constinit int a; 2751 // int a = 0; // error (missing 'constinit'), accepted as extension 2752 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2753 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2754 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2755 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2756 } else { 2757 // int a = 0; 2758 // constinit extern int a; // error (missing 'constinit') 2759 S.Diag(CIAttr->getLocation(), 2760 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2761 : diag::warn_require_const_init_added_too_late) 2762 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2763 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2764 << CIAttr->isConstinit() 2765 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2766 } 2767 } 2768 2769 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2770 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2771 AvailabilityMergeKind AMK) { 2772 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2773 UsedAttr *NewAttr = OldAttr->clone(Context); 2774 NewAttr->setInherited(true); 2775 New->addAttr(NewAttr); 2776 } 2777 2778 if (!Old->hasAttrs() && !New->hasAttrs()) 2779 return; 2780 2781 // [dcl.constinit]p1: 2782 // If the [constinit] specifier is applied to any declaration of a 2783 // variable, it shall be applied to the initializing declaration. 2784 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2785 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2786 if (bool(OldConstInit) != bool(NewConstInit)) { 2787 const auto *OldVD = cast<VarDecl>(Old); 2788 auto *NewVD = cast<VarDecl>(New); 2789 2790 // Find the initializing declaration. Note that we might not have linked 2791 // the new declaration into the redeclaration chain yet. 2792 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2793 if (!InitDecl && 2794 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2795 InitDecl = NewVD; 2796 2797 if (InitDecl == NewVD) { 2798 // This is the initializing declaration. If it would inherit 'constinit', 2799 // that's ill-formed. (Note that we do not apply this to the attribute 2800 // form). 2801 if (OldConstInit && OldConstInit->isConstinit()) 2802 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2803 /*AttrBeforeInit=*/true); 2804 } else if (NewConstInit) { 2805 // This is the first time we've been told that this declaration should 2806 // have a constant initializer. If we already saw the initializing 2807 // declaration, this is too late. 2808 if (InitDecl && InitDecl != NewVD) { 2809 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2810 /*AttrBeforeInit=*/false); 2811 NewVD->dropAttr<ConstInitAttr>(); 2812 } 2813 } 2814 } 2815 2816 // Attributes declared post-definition are currently ignored. 2817 checkNewAttributesAfterDef(*this, New, Old); 2818 2819 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2820 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2821 if (!OldA->isEquivalent(NewA)) { 2822 // This redeclaration changes __asm__ label. 2823 Diag(New->getLocation(), diag::err_different_asm_label); 2824 Diag(OldA->getLocation(), diag::note_previous_declaration); 2825 } 2826 } else if (Old->isUsed()) { 2827 // This redeclaration adds an __asm__ label to a declaration that has 2828 // already been ODR-used. 2829 Diag(New->getLocation(), diag::err_late_asm_label_name) 2830 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2831 } 2832 } 2833 2834 // Re-declaration cannot add abi_tag's. 2835 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2836 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2837 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2838 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2839 NewTag) == OldAbiTagAttr->tags_end()) { 2840 Diag(NewAbiTagAttr->getLocation(), 2841 diag::err_new_abi_tag_on_redeclaration) 2842 << NewTag; 2843 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2844 } 2845 } 2846 } else { 2847 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2848 Diag(Old->getLocation(), diag::note_previous_declaration); 2849 } 2850 } 2851 2852 // This redeclaration adds a section attribute. 2853 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2854 if (auto *VD = dyn_cast<VarDecl>(New)) { 2855 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2856 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2857 Diag(Old->getLocation(), diag::note_previous_declaration); 2858 } 2859 } 2860 } 2861 2862 // Redeclaration adds code-seg attribute. 2863 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2864 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2865 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2866 Diag(New->getLocation(), diag::warn_mismatched_section) 2867 << 0 /*codeseg*/; 2868 Diag(Old->getLocation(), diag::note_previous_declaration); 2869 } 2870 2871 if (!Old->hasAttrs()) 2872 return; 2873 2874 bool foundAny = New->hasAttrs(); 2875 2876 // Ensure that any moving of objects within the allocated map is done before 2877 // we process them. 2878 if (!foundAny) New->setAttrs(AttrVec()); 2879 2880 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2881 // Ignore deprecated/unavailable/availability attributes if requested. 2882 AvailabilityMergeKind LocalAMK = AMK_None; 2883 if (isa<DeprecatedAttr>(I) || 2884 isa<UnavailableAttr>(I) || 2885 isa<AvailabilityAttr>(I)) { 2886 switch (AMK) { 2887 case AMK_None: 2888 continue; 2889 2890 case AMK_Redeclaration: 2891 case AMK_Override: 2892 case AMK_ProtocolImplementation: 2893 LocalAMK = AMK; 2894 break; 2895 } 2896 } 2897 2898 // Already handled. 2899 if (isa<UsedAttr>(I)) 2900 continue; 2901 2902 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2903 foundAny = true; 2904 } 2905 2906 if (mergeAlignedAttrs(*this, New, Old)) 2907 foundAny = true; 2908 2909 if (!foundAny) New->dropAttrs(); 2910 } 2911 2912 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2913 /// to the new one. 2914 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2915 const ParmVarDecl *oldDecl, 2916 Sema &S) { 2917 // C++11 [dcl.attr.depend]p2: 2918 // The first declaration of a function shall specify the 2919 // carries_dependency attribute for its declarator-id if any declaration 2920 // of the function specifies the carries_dependency attribute. 2921 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2922 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2923 S.Diag(CDA->getLocation(), 2924 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2925 // Find the first declaration of the parameter. 2926 // FIXME: Should we build redeclaration chains for function parameters? 2927 const FunctionDecl *FirstFD = 2928 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2929 const ParmVarDecl *FirstVD = 2930 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2931 S.Diag(FirstVD->getLocation(), 2932 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2933 } 2934 2935 if (!oldDecl->hasAttrs()) 2936 return; 2937 2938 bool foundAny = newDecl->hasAttrs(); 2939 2940 // Ensure that any moving of objects within the allocated map is 2941 // done before we process them. 2942 if (!foundAny) newDecl->setAttrs(AttrVec()); 2943 2944 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2945 if (!DeclHasAttr(newDecl, I)) { 2946 InheritableAttr *newAttr = 2947 cast<InheritableParamAttr>(I->clone(S.Context)); 2948 newAttr->setInherited(true); 2949 newDecl->addAttr(newAttr); 2950 foundAny = true; 2951 } 2952 } 2953 2954 if (!foundAny) newDecl->dropAttrs(); 2955 } 2956 2957 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2958 const ParmVarDecl *OldParam, 2959 Sema &S) { 2960 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2961 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2962 if (*Oldnullability != *Newnullability) { 2963 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2964 << DiagNullabilityKind( 2965 *Newnullability, 2966 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2967 != 0)) 2968 << DiagNullabilityKind( 2969 *Oldnullability, 2970 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2971 != 0)); 2972 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2973 } 2974 } else { 2975 QualType NewT = NewParam->getType(); 2976 NewT = S.Context.getAttributedType( 2977 AttributedType::getNullabilityAttrKind(*Oldnullability), 2978 NewT, NewT); 2979 NewParam->setType(NewT); 2980 } 2981 } 2982 } 2983 2984 namespace { 2985 2986 /// Used in MergeFunctionDecl to keep track of function parameters in 2987 /// C. 2988 struct GNUCompatibleParamWarning { 2989 ParmVarDecl *OldParm; 2990 ParmVarDecl *NewParm; 2991 QualType PromotedType; 2992 }; 2993 2994 } // end anonymous namespace 2995 2996 // Determine whether the previous declaration was a definition, implicit 2997 // declaration, or a declaration. 2998 template <typename T> 2999 static std::pair<diag::kind, SourceLocation> 3000 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3001 diag::kind PrevDiag; 3002 SourceLocation OldLocation = Old->getLocation(); 3003 if (Old->isThisDeclarationADefinition()) 3004 PrevDiag = diag::note_previous_definition; 3005 else if (Old->isImplicit()) { 3006 PrevDiag = diag::note_previous_implicit_declaration; 3007 if (OldLocation.isInvalid()) 3008 OldLocation = New->getLocation(); 3009 } else 3010 PrevDiag = diag::note_previous_declaration; 3011 return std::make_pair(PrevDiag, OldLocation); 3012 } 3013 3014 /// canRedefineFunction - checks if a function can be redefined. Currently, 3015 /// only extern inline functions can be redefined, and even then only in 3016 /// GNU89 mode. 3017 static bool canRedefineFunction(const FunctionDecl *FD, 3018 const LangOptions& LangOpts) { 3019 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3020 !LangOpts.CPlusPlus && 3021 FD->isInlineSpecified() && 3022 FD->getStorageClass() == SC_Extern); 3023 } 3024 3025 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3026 const AttributedType *AT = T->getAs<AttributedType>(); 3027 while (AT && !AT->isCallingConv()) 3028 AT = AT->getModifiedType()->getAs<AttributedType>(); 3029 return AT; 3030 } 3031 3032 template <typename T> 3033 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3034 const DeclContext *DC = Old->getDeclContext(); 3035 if (DC->isRecord()) 3036 return false; 3037 3038 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3039 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3040 return true; 3041 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3042 return true; 3043 return false; 3044 } 3045 3046 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3047 static bool isExternC(VarTemplateDecl *) { return false; } 3048 3049 /// Check whether a redeclaration of an entity introduced by a 3050 /// using-declaration is valid, given that we know it's not an overload 3051 /// (nor a hidden tag declaration). 3052 template<typename ExpectedDecl> 3053 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3054 ExpectedDecl *New) { 3055 // C++11 [basic.scope.declarative]p4: 3056 // Given a set of declarations in a single declarative region, each of 3057 // which specifies the same unqualified name, 3058 // -- they shall all refer to the same entity, or all refer to functions 3059 // and function templates; or 3060 // -- exactly one declaration shall declare a class name or enumeration 3061 // name that is not a typedef name and the other declarations shall all 3062 // refer to the same variable or enumerator, or all refer to functions 3063 // and function templates; in this case the class name or enumeration 3064 // name is hidden (3.3.10). 3065 3066 // C++11 [namespace.udecl]p14: 3067 // If a function declaration in namespace scope or block scope has the 3068 // same name and the same parameter-type-list as a function introduced 3069 // by a using-declaration, and the declarations do not declare the same 3070 // function, the program is ill-formed. 3071 3072 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3073 if (Old && 3074 !Old->getDeclContext()->getRedeclContext()->Equals( 3075 New->getDeclContext()->getRedeclContext()) && 3076 !(isExternC(Old) && isExternC(New))) 3077 Old = nullptr; 3078 3079 if (!Old) { 3080 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3081 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3082 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3083 return true; 3084 } 3085 return false; 3086 } 3087 3088 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3089 const FunctionDecl *B) { 3090 assert(A->getNumParams() == B->getNumParams()); 3091 3092 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3093 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3094 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3095 if (AttrA == AttrB) 3096 return true; 3097 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3098 AttrA->isDynamic() == AttrB->isDynamic(); 3099 }; 3100 3101 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3102 } 3103 3104 /// If necessary, adjust the semantic declaration context for a qualified 3105 /// declaration to name the correct inline namespace within the qualifier. 3106 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3107 DeclaratorDecl *OldD) { 3108 // The only case where we need to update the DeclContext is when 3109 // redeclaration lookup for a qualified name finds a declaration 3110 // in an inline namespace within the context named by the qualifier: 3111 // 3112 // inline namespace N { int f(); } 3113 // int ::f(); // Sema DC needs adjusting from :: to N::. 3114 // 3115 // For unqualified declarations, the semantic context *can* change 3116 // along the redeclaration chain (for local extern declarations, 3117 // extern "C" declarations, and friend declarations in particular). 3118 if (!NewD->getQualifier()) 3119 return; 3120 3121 // NewD is probably already in the right context. 3122 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3123 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3124 if (NamedDC->Equals(SemaDC)) 3125 return; 3126 3127 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3128 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3129 "unexpected context for redeclaration"); 3130 3131 auto *LexDC = NewD->getLexicalDeclContext(); 3132 auto FixSemaDC = [=](NamedDecl *D) { 3133 if (!D) 3134 return; 3135 D->setDeclContext(SemaDC); 3136 D->setLexicalDeclContext(LexDC); 3137 }; 3138 3139 FixSemaDC(NewD); 3140 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3141 FixSemaDC(FD->getDescribedFunctionTemplate()); 3142 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3143 FixSemaDC(VD->getDescribedVarTemplate()); 3144 } 3145 3146 /// MergeFunctionDecl - We just parsed a function 'New' from 3147 /// declarator D which has the same name and scope as a previous 3148 /// declaration 'Old'. Figure out how to resolve this situation, 3149 /// merging decls or emitting diagnostics as appropriate. 3150 /// 3151 /// In C++, New and Old must be declarations that are not 3152 /// overloaded. Use IsOverload to determine whether New and Old are 3153 /// overloaded, and to select the Old declaration that New should be 3154 /// merged with. 3155 /// 3156 /// Returns true if there was an error, false otherwise. 3157 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3158 Scope *S, bool MergeTypeWithOld) { 3159 // Verify the old decl was also a function. 3160 FunctionDecl *Old = OldD->getAsFunction(); 3161 if (!Old) { 3162 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3163 if (New->getFriendObjectKind()) { 3164 Diag(New->getLocation(), diag::err_using_decl_friend); 3165 Diag(Shadow->getTargetDecl()->getLocation(), 3166 diag::note_using_decl_target); 3167 Diag(Shadow->getUsingDecl()->getLocation(), 3168 diag::note_using_decl) << 0; 3169 return true; 3170 } 3171 3172 // Check whether the two declarations might declare the same function. 3173 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3174 return true; 3175 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3176 } else { 3177 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3178 << New->getDeclName(); 3179 notePreviousDefinition(OldD, New->getLocation()); 3180 return true; 3181 } 3182 } 3183 3184 // If the old declaration is invalid, just give up here. 3185 if (Old->isInvalidDecl()) 3186 return true; 3187 3188 // Disallow redeclaration of some builtins. 3189 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3190 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3191 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3192 << Old << Old->getType(); 3193 return true; 3194 } 3195 3196 diag::kind PrevDiag; 3197 SourceLocation OldLocation; 3198 std::tie(PrevDiag, OldLocation) = 3199 getNoteDiagForInvalidRedeclaration(Old, New); 3200 3201 // Don't complain about this if we're in GNU89 mode and the old function 3202 // is an extern inline function. 3203 // Don't complain about specializations. They are not supposed to have 3204 // storage classes. 3205 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3206 New->getStorageClass() == SC_Static && 3207 Old->hasExternalFormalLinkage() && 3208 !New->getTemplateSpecializationInfo() && 3209 !canRedefineFunction(Old, getLangOpts())) { 3210 if (getLangOpts().MicrosoftExt) { 3211 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3212 Diag(OldLocation, PrevDiag); 3213 } else { 3214 Diag(New->getLocation(), diag::err_static_non_static) << New; 3215 Diag(OldLocation, PrevDiag); 3216 return true; 3217 } 3218 } 3219 3220 if (New->hasAttr<InternalLinkageAttr>() && 3221 !Old->hasAttr<InternalLinkageAttr>()) { 3222 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3223 << New->getDeclName(); 3224 notePreviousDefinition(Old, New->getLocation()); 3225 New->dropAttr<InternalLinkageAttr>(); 3226 } 3227 3228 if (CheckRedeclarationModuleOwnership(New, Old)) 3229 return true; 3230 3231 if (!getLangOpts().CPlusPlus) { 3232 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3233 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3234 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3235 << New << OldOvl; 3236 3237 // Try our best to find a decl that actually has the overloadable 3238 // attribute for the note. In most cases (e.g. programs with only one 3239 // broken declaration/definition), this won't matter. 3240 // 3241 // FIXME: We could do this if we juggled some extra state in 3242 // OverloadableAttr, rather than just removing it. 3243 const Decl *DiagOld = Old; 3244 if (OldOvl) { 3245 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3246 const auto *A = D->getAttr<OverloadableAttr>(); 3247 return A && !A->isImplicit(); 3248 }); 3249 // If we've implicitly added *all* of the overloadable attrs to this 3250 // chain, emitting a "previous redecl" note is pointless. 3251 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3252 } 3253 3254 if (DiagOld) 3255 Diag(DiagOld->getLocation(), 3256 diag::note_attribute_overloadable_prev_overload) 3257 << OldOvl; 3258 3259 if (OldOvl) 3260 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3261 else 3262 New->dropAttr<OverloadableAttr>(); 3263 } 3264 } 3265 3266 // If a function is first declared with a calling convention, but is later 3267 // declared or defined without one, all following decls assume the calling 3268 // convention of the first. 3269 // 3270 // It's OK if a function is first declared without a calling convention, 3271 // but is later declared or defined with the default calling convention. 3272 // 3273 // To test if either decl has an explicit calling convention, we look for 3274 // AttributedType sugar nodes on the type as written. If they are missing or 3275 // were canonicalized away, we assume the calling convention was implicit. 3276 // 3277 // Note also that we DO NOT return at this point, because we still have 3278 // other tests to run. 3279 QualType OldQType = Context.getCanonicalType(Old->getType()); 3280 QualType NewQType = Context.getCanonicalType(New->getType()); 3281 const FunctionType *OldType = cast<FunctionType>(OldQType); 3282 const FunctionType *NewType = cast<FunctionType>(NewQType); 3283 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3284 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3285 bool RequiresAdjustment = false; 3286 3287 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3288 FunctionDecl *First = Old->getFirstDecl(); 3289 const FunctionType *FT = 3290 First->getType().getCanonicalType()->castAs<FunctionType>(); 3291 FunctionType::ExtInfo FI = FT->getExtInfo(); 3292 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3293 if (!NewCCExplicit) { 3294 // Inherit the CC from the previous declaration if it was specified 3295 // there but not here. 3296 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3297 RequiresAdjustment = true; 3298 } else if (New->getBuiltinID()) { 3299 // Calling Conventions on a Builtin aren't really useful and setting a 3300 // default calling convention and cdecl'ing some builtin redeclarations is 3301 // common, so warn and ignore the calling convention on the redeclaration. 3302 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3303 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3304 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3305 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3306 RequiresAdjustment = true; 3307 } else { 3308 // Calling conventions aren't compatible, so complain. 3309 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3310 Diag(New->getLocation(), diag::err_cconv_change) 3311 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3312 << !FirstCCExplicit 3313 << (!FirstCCExplicit ? "" : 3314 FunctionType::getNameForCallConv(FI.getCC())); 3315 3316 // Put the note on the first decl, since it is the one that matters. 3317 Diag(First->getLocation(), diag::note_previous_declaration); 3318 return true; 3319 } 3320 } 3321 3322 // FIXME: diagnose the other way around? 3323 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3324 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3325 RequiresAdjustment = true; 3326 } 3327 3328 // Merge regparm attribute. 3329 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3330 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3331 if (NewTypeInfo.getHasRegParm()) { 3332 Diag(New->getLocation(), diag::err_regparm_mismatch) 3333 << NewType->getRegParmType() 3334 << OldType->getRegParmType(); 3335 Diag(OldLocation, diag::note_previous_declaration); 3336 return true; 3337 } 3338 3339 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3340 RequiresAdjustment = true; 3341 } 3342 3343 // Merge ns_returns_retained attribute. 3344 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3345 if (NewTypeInfo.getProducesResult()) { 3346 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3347 << "'ns_returns_retained'"; 3348 Diag(OldLocation, diag::note_previous_declaration); 3349 return true; 3350 } 3351 3352 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3353 RequiresAdjustment = true; 3354 } 3355 3356 if (OldTypeInfo.getNoCallerSavedRegs() != 3357 NewTypeInfo.getNoCallerSavedRegs()) { 3358 if (NewTypeInfo.getNoCallerSavedRegs()) { 3359 AnyX86NoCallerSavedRegistersAttr *Attr = 3360 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3361 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3362 Diag(OldLocation, diag::note_previous_declaration); 3363 return true; 3364 } 3365 3366 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3367 RequiresAdjustment = true; 3368 } 3369 3370 if (RequiresAdjustment) { 3371 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3372 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3373 New->setType(QualType(AdjustedType, 0)); 3374 NewQType = Context.getCanonicalType(New->getType()); 3375 } 3376 3377 // If this redeclaration makes the function inline, we may need to add it to 3378 // UndefinedButUsed. 3379 if (!Old->isInlined() && New->isInlined() && 3380 !New->hasAttr<GNUInlineAttr>() && 3381 !getLangOpts().GNUInline && 3382 Old->isUsed(false) && 3383 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3384 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3385 SourceLocation())); 3386 3387 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3388 // about it. 3389 if (New->hasAttr<GNUInlineAttr>() && 3390 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3391 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3392 } 3393 3394 // If pass_object_size params don't match up perfectly, this isn't a valid 3395 // redeclaration. 3396 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3397 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3398 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3399 << New->getDeclName(); 3400 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3401 return true; 3402 } 3403 3404 if (getLangOpts().CPlusPlus) { 3405 // C++1z [over.load]p2 3406 // Certain function declarations cannot be overloaded: 3407 // -- Function declarations that differ only in the return type, 3408 // the exception specification, or both cannot be overloaded. 3409 3410 // Check the exception specifications match. This may recompute the type of 3411 // both Old and New if it resolved exception specifications, so grab the 3412 // types again after this. Because this updates the type, we do this before 3413 // any of the other checks below, which may update the "de facto" NewQType 3414 // but do not necessarily update the type of New. 3415 if (CheckEquivalentExceptionSpec(Old, New)) 3416 return true; 3417 OldQType = Context.getCanonicalType(Old->getType()); 3418 NewQType = Context.getCanonicalType(New->getType()); 3419 3420 // Go back to the type source info to compare the declared return types, 3421 // per C++1y [dcl.type.auto]p13: 3422 // Redeclarations or specializations of a function or function template 3423 // with a declared return type that uses a placeholder type shall also 3424 // use that placeholder, not a deduced type. 3425 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3426 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3427 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3428 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3429 OldDeclaredReturnType)) { 3430 QualType ResQT; 3431 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3432 OldDeclaredReturnType->isObjCObjectPointerType()) 3433 // FIXME: This does the wrong thing for a deduced return type. 3434 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3435 if (ResQT.isNull()) { 3436 if (New->isCXXClassMember() && New->isOutOfLine()) 3437 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3438 << New << New->getReturnTypeSourceRange(); 3439 else 3440 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3441 << New->getReturnTypeSourceRange(); 3442 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3443 << Old->getReturnTypeSourceRange(); 3444 return true; 3445 } 3446 else 3447 NewQType = ResQT; 3448 } 3449 3450 QualType OldReturnType = OldType->getReturnType(); 3451 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3452 if (OldReturnType != NewReturnType) { 3453 // If this function has a deduced return type and has already been 3454 // defined, copy the deduced value from the old declaration. 3455 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3456 if (OldAT && OldAT->isDeduced()) { 3457 New->setType( 3458 SubstAutoType(New->getType(), 3459 OldAT->isDependentType() ? Context.DependentTy 3460 : OldAT->getDeducedType())); 3461 NewQType = Context.getCanonicalType( 3462 SubstAutoType(NewQType, 3463 OldAT->isDependentType() ? Context.DependentTy 3464 : OldAT->getDeducedType())); 3465 } 3466 } 3467 3468 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3469 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3470 if (OldMethod && NewMethod) { 3471 // Preserve triviality. 3472 NewMethod->setTrivial(OldMethod->isTrivial()); 3473 3474 // MSVC allows explicit template specialization at class scope: 3475 // 2 CXXMethodDecls referring to the same function will be injected. 3476 // We don't want a redeclaration error. 3477 bool IsClassScopeExplicitSpecialization = 3478 OldMethod->isFunctionTemplateSpecialization() && 3479 NewMethod->isFunctionTemplateSpecialization(); 3480 bool isFriend = NewMethod->getFriendObjectKind(); 3481 3482 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3483 !IsClassScopeExplicitSpecialization) { 3484 // -- Member function declarations with the same name and the 3485 // same parameter types cannot be overloaded if any of them 3486 // is a static member function declaration. 3487 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3488 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3489 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3490 return true; 3491 } 3492 3493 // C++ [class.mem]p1: 3494 // [...] A member shall not be declared twice in the 3495 // member-specification, except that a nested class or member 3496 // class template can be declared and then later defined. 3497 if (!inTemplateInstantiation()) { 3498 unsigned NewDiag; 3499 if (isa<CXXConstructorDecl>(OldMethod)) 3500 NewDiag = diag::err_constructor_redeclared; 3501 else if (isa<CXXDestructorDecl>(NewMethod)) 3502 NewDiag = diag::err_destructor_redeclared; 3503 else if (isa<CXXConversionDecl>(NewMethod)) 3504 NewDiag = diag::err_conv_function_redeclared; 3505 else 3506 NewDiag = diag::err_member_redeclared; 3507 3508 Diag(New->getLocation(), NewDiag); 3509 } else { 3510 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3511 << New << New->getType(); 3512 } 3513 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3514 return true; 3515 3516 // Complain if this is an explicit declaration of a special 3517 // member that was initially declared implicitly. 3518 // 3519 // As an exception, it's okay to befriend such methods in order 3520 // to permit the implicit constructor/destructor/operator calls. 3521 } else if (OldMethod->isImplicit()) { 3522 if (isFriend) { 3523 NewMethod->setImplicit(); 3524 } else { 3525 Diag(NewMethod->getLocation(), 3526 diag::err_definition_of_implicitly_declared_member) 3527 << New << getSpecialMember(OldMethod); 3528 return true; 3529 } 3530 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3531 Diag(NewMethod->getLocation(), 3532 diag::err_definition_of_explicitly_defaulted_member) 3533 << getSpecialMember(OldMethod); 3534 return true; 3535 } 3536 } 3537 3538 // C++11 [dcl.attr.noreturn]p1: 3539 // The first declaration of a function shall specify the noreturn 3540 // attribute if any declaration of that function specifies the noreturn 3541 // attribute. 3542 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3543 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3544 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3545 Diag(Old->getFirstDecl()->getLocation(), 3546 diag::note_noreturn_missing_first_decl); 3547 } 3548 3549 // C++11 [dcl.attr.depend]p2: 3550 // The first declaration of a function shall specify the 3551 // carries_dependency attribute for its declarator-id if any declaration 3552 // of the function specifies the carries_dependency attribute. 3553 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3554 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3555 Diag(CDA->getLocation(), 3556 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3557 Diag(Old->getFirstDecl()->getLocation(), 3558 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3559 } 3560 3561 // (C++98 8.3.5p3): 3562 // All declarations for a function shall agree exactly in both the 3563 // return type and the parameter-type-list. 3564 // We also want to respect all the extended bits except noreturn. 3565 3566 // noreturn should now match unless the old type info didn't have it. 3567 QualType OldQTypeForComparison = OldQType; 3568 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3569 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3570 const FunctionType *OldTypeForComparison 3571 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3572 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3573 assert(OldQTypeForComparison.isCanonical()); 3574 } 3575 3576 if (haveIncompatibleLanguageLinkages(Old, New)) { 3577 // As a special case, retain the language linkage from previous 3578 // declarations of a friend function as an extension. 3579 // 3580 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3581 // and is useful because there's otherwise no way to specify language 3582 // linkage within class scope. 3583 // 3584 // Check cautiously as the friend object kind isn't yet complete. 3585 if (New->getFriendObjectKind() != Decl::FOK_None) { 3586 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3587 Diag(OldLocation, PrevDiag); 3588 } else { 3589 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3590 Diag(OldLocation, PrevDiag); 3591 return true; 3592 } 3593 } 3594 3595 // If the function types are compatible, merge the declarations. Ignore the 3596 // exception specifier because it was already checked above in 3597 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3598 // about incompatible types under -fms-compatibility. 3599 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3600 NewQType)) 3601 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3602 3603 // If the types are imprecise (due to dependent constructs in friends or 3604 // local extern declarations), it's OK if they differ. We'll check again 3605 // during instantiation. 3606 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3607 return false; 3608 3609 // Fall through for conflicting redeclarations and redefinitions. 3610 } 3611 3612 // C: Function types need to be compatible, not identical. This handles 3613 // duplicate function decls like "void f(int); void f(enum X);" properly. 3614 if (!getLangOpts().CPlusPlus && 3615 Context.typesAreCompatible(OldQType, NewQType)) { 3616 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3617 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3618 const FunctionProtoType *OldProto = nullptr; 3619 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3620 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3621 // The old declaration provided a function prototype, but the 3622 // new declaration does not. Merge in the prototype. 3623 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3624 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3625 NewQType = 3626 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3627 OldProto->getExtProtoInfo()); 3628 New->setType(NewQType); 3629 New->setHasInheritedPrototype(); 3630 3631 // Synthesize parameters with the same types. 3632 SmallVector<ParmVarDecl*, 16> Params; 3633 for (const auto &ParamType : OldProto->param_types()) { 3634 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3635 SourceLocation(), nullptr, 3636 ParamType, /*TInfo=*/nullptr, 3637 SC_None, nullptr); 3638 Param->setScopeInfo(0, Params.size()); 3639 Param->setImplicit(); 3640 Params.push_back(Param); 3641 } 3642 3643 New->setParams(Params); 3644 } 3645 3646 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3647 } 3648 3649 // GNU C permits a K&R definition to follow a prototype declaration 3650 // if the declared types of the parameters in the K&R definition 3651 // match the types in the prototype declaration, even when the 3652 // promoted types of the parameters from the K&R definition differ 3653 // from the types in the prototype. GCC then keeps the types from 3654 // the prototype. 3655 // 3656 // If a variadic prototype is followed by a non-variadic K&R definition, 3657 // the K&R definition becomes variadic. This is sort of an edge case, but 3658 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3659 // C99 6.9.1p8. 3660 if (!getLangOpts().CPlusPlus && 3661 Old->hasPrototype() && !New->hasPrototype() && 3662 New->getType()->getAs<FunctionProtoType>() && 3663 Old->getNumParams() == New->getNumParams()) { 3664 SmallVector<QualType, 16> ArgTypes; 3665 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3666 const FunctionProtoType *OldProto 3667 = Old->getType()->getAs<FunctionProtoType>(); 3668 const FunctionProtoType *NewProto 3669 = New->getType()->getAs<FunctionProtoType>(); 3670 3671 // Determine whether this is the GNU C extension. 3672 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3673 NewProto->getReturnType()); 3674 bool LooseCompatible = !MergedReturn.isNull(); 3675 for (unsigned Idx = 0, End = Old->getNumParams(); 3676 LooseCompatible && Idx != End; ++Idx) { 3677 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3678 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3679 if (Context.typesAreCompatible(OldParm->getType(), 3680 NewProto->getParamType(Idx))) { 3681 ArgTypes.push_back(NewParm->getType()); 3682 } else if (Context.typesAreCompatible(OldParm->getType(), 3683 NewParm->getType(), 3684 /*CompareUnqualified=*/true)) { 3685 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3686 NewProto->getParamType(Idx) }; 3687 Warnings.push_back(Warn); 3688 ArgTypes.push_back(NewParm->getType()); 3689 } else 3690 LooseCompatible = false; 3691 } 3692 3693 if (LooseCompatible) { 3694 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3695 Diag(Warnings[Warn].NewParm->getLocation(), 3696 diag::ext_param_promoted_not_compatible_with_prototype) 3697 << Warnings[Warn].PromotedType 3698 << Warnings[Warn].OldParm->getType(); 3699 if (Warnings[Warn].OldParm->getLocation().isValid()) 3700 Diag(Warnings[Warn].OldParm->getLocation(), 3701 diag::note_previous_declaration); 3702 } 3703 3704 if (MergeTypeWithOld) 3705 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3706 OldProto->getExtProtoInfo())); 3707 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3708 } 3709 3710 // Fall through to diagnose conflicting types. 3711 } 3712 3713 // A function that has already been declared has been redeclared or 3714 // defined with a different type; show an appropriate diagnostic. 3715 3716 // If the previous declaration was an implicitly-generated builtin 3717 // declaration, then at the very least we should use a specialized note. 3718 unsigned BuiltinID; 3719 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3720 // If it's actually a library-defined builtin function like 'malloc' 3721 // or 'printf', just warn about the incompatible redeclaration. 3722 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3723 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3724 Diag(OldLocation, diag::note_previous_builtin_declaration) 3725 << Old << Old->getType(); 3726 3727 // If this is a global redeclaration, just forget hereafter 3728 // about the "builtin-ness" of the function. 3729 // 3730 // Doing this for local extern declarations is problematic. If 3731 // the builtin declaration remains visible, a second invalid 3732 // local declaration will produce a hard error; if it doesn't 3733 // remain visible, a single bogus local redeclaration (which is 3734 // actually only a warning) could break all the downstream code. 3735 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3736 New->getIdentifier()->revertBuiltin(); 3737 3738 return false; 3739 } 3740 3741 PrevDiag = diag::note_previous_builtin_declaration; 3742 } 3743 3744 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3745 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3746 return true; 3747 } 3748 3749 /// Completes the merge of two function declarations that are 3750 /// known to be compatible. 3751 /// 3752 /// This routine handles the merging of attributes and other 3753 /// properties of function declarations from the old declaration to 3754 /// the new declaration, once we know that New is in fact a 3755 /// redeclaration of Old. 3756 /// 3757 /// \returns false 3758 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3759 Scope *S, bool MergeTypeWithOld) { 3760 // Merge the attributes 3761 mergeDeclAttributes(New, Old); 3762 3763 // Merge "pure" flag. 3764 if (Old->isPure()) 3765 New->setPure(); 3766 3767 // Merge "used" flag. 3768 if (Old->getMostRecentDecl()->isUsed(false)) 3769 New->setIsUsed(); 3770 3771 // Merge attributes from the parameters. These can mismatch with K&R 3772 // declarations. 3773 if (New->getNumParams() == Old->getNumParams()) 3774 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3775 ParmVarDecl *NewParam = New->getParamDecl(i); 3776 ParmVarDecl *OldParam = Old->getParamDecl(i); 3777 mergeParamDeclAttributes(NewParam, OldParam, *this); 3778 mergeParamDeclTypes(NewParam, OldParam, *this); 3779 } 3780 3781 if (getLangOpts().CPlusPlus) 3782 return MergeCXXFunctionDecl(New, Old, S); 3783 3784 // Merge the function types so the we get the composite types for the return 3785 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3786 // was visible. 3787 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3788 if (!Merged.isNull() && MergeTypeWithOld) 3789 New->setType(Merged); 3790 3791 return false; 3792 } 3793 3794 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3795 ObjCMethodDecl *oldMethod) { 3796 // Merge the attributes, including deprecated/unavailable 3797 AvailabilityMergeKind MergeKind = 3798 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3799 ? AMK_ProtocolImplementation 3800 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3801 : AMK_Override; 3802 3803 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3804 3805 // Merge attributes from the parameters. 3806 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3807 oe = oldMethod->param_end(); 3808 for (ObjCMethodDecl::param_iterator 3809 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3810 ni != ne && oi != oe; ++ni, ++oi) 3811 mergeParamDeclAttributes(*ni, *oi, *this); 3812 3813 CheckObjCMethodOverride(newMethod, oldMethod); 3814 } 3815 3816 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3817 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3818 3819 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3820 ? diag::err_redefinition_different_type 3821 : diag::err_redeclaration_different_type) 3822 << New->getDeclName() << New->getType() << Old->getType(); 3823 3824 diag::kind PrevDiag; 3825 SourceLocation OldLocation; 3826 std::tie(PrevDiag, OldLocation) 3827 = getNoteDiagForInvalidRedeclaration(Old, New); 3828 S.Diag(OldLocation, PrevDiag); 3829 New->setInvalidDecl(); 3830 } 3831 3832 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3833 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3834 /// emitting diagnostics as appropriate. 3835 /// 3836 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3837 /// to here in AddInitializerToDecl. We can't check them before the initializer 3838 /// is attached. 3839 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3840 bool MergeTypeWithOld) { 3841 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3842 return; 3843 3844 QualType MergedT; 3845 if (getLangOpts().CPlusPlus) { 3846 if (New->getType()->isUndeducedType()) { 3847 // We don't know what the new type is until the initializer is attached. 3848 return; 3849 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3850 // These could still be something that needs exception specs checked. 3851 return MergeVarDeclExceptionSpecs(New, Old); 3852 } 3853 // C++ [basic.link]p10: 3854 // [...] the types specified by all declarations referring to a given 3855 // object or function shall be identical, except that declarations for an 3856 // array object can specify array types that differ by the presence or 3857 // absence of a major array bound (8.3.4). 3858 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3859 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3860 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3861 3862 // We are merging a variable declaration New into Old. If it has an array 3863 // bound, and that bound differs from Old's bound, we should diagnose the 3864 // mismatch. 3865 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3866 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3867 PrevVD = PrevVD->getPreviousDecl()) { 3868 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3869 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3870 continue; 3871 3872 if (!Context.hasSameType(NewArray, PrevVDTy)) 3873 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3874 } 3875 } 3876 3877 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3878 if (Context.hasSameType(OldArray->getElementType(), 3879 NewArray->getElementType())) 3880 MergedT = New->getType(); 3881 } 3882 // FIXME: Check visibility. New is hidden but has a complete type. If New 3883 // has no array bound, it should not inherit one from Old, if Old is not 3884 // visible. 3885 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3886 if (Context.hasSameType(OldArray->getElementType(), 3887 NewArray->getElementType())) 3888 MergedT = Old->getType(); 3889 } 3890 } 3891 else if (New->getType()->isObjCObjectPointerType() && 3892 Old->getType()->isObjCObjectPointerType()) { 3893 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3894 Old->getType()); 3895 } 3896 } else { 3897 // C 6.2.7p2: 3898 // All declarations that refer to the same object or function shall have 3899 // compatible type. 3900 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3901 } 3902 if (MergedT.isNull()) { 3903 // It's OK if we couldn't merge types if either type is dependent, for a 3904 // block-scope variable. In other cases (static data members of class 3905 // templates, variable templates, ...), we require the types to be 3906 // equivalent. 3907 // FIXME: The C++ standard doesn't say anything about this. 3908 if ((New->getType()->isDependentType() || 3909 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3910 // If the old type was dependent, we can't merge with it, so the new type 3911 // becomes dependent for now. We'll reproduce the original type when we 3912 // instantiate the TypeSourceInfo for the variable. 3913 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3914 New->setType(Context.DependentTy); 3915 return; 3916 } 3917 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3918 } 3919 3920 // Don't actually update the type on the new declaration if the old 3921 // declaration was an extern declaration in a different scope. 3922 if (MergeTypeWithOld) 3923 New->setType(MergedT); 3924 } 3925 3926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3927 LookupResult &Previous) { 3928 // C11 6.2.7p4: 3929 // For an identifier with internal or external linkage declared 3930 // in a scope in which a prior declaration of that identifier is 3931 // visible, if the prior declaration specifies internal or 3932 // external linkage, the type of the identifier at the later 3933 // declaration becomes the composite type. 3934 // 3935 // If the variable isn't visible, we do not merge with its type. 3936 if (Previous.isShadowed()) 3937 return false; 3938 3939 if (S.getLangOpts().CPlusPlus) { 3940 // C++11 [dcl.array]p3: 3941 // If there is a preceding declaration of the entity in the same 3942 // scope in which the bound was specified, an omitted array bound 3943 // is taken to be the same as in that earlier declaration. 3944 return NewVD->isPreviousDeclInSameBlockScope() || 3945 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3946 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3947 } else { 3948 // If the old declaration was function-local, don't merge with its 3949 // type unless we're in the same function. 3950 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3951 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3952 } 3953 } 3954 3955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3956 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3957 /// situation, merging decls or emitting diagnostics as appropriate. 3958 /// 3959 /// Tentative definition rules (C99 6.9.2p2) are checked by 3960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3961 /// definitions here, since the initializer hasn't been attached. 3962 /// 3963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3964 // If the new decl is already invalid, don't do any other checking. 3965 if (New->isInvalidDecl()) 3966 return; 3967 3968 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3969 return; 3970 3971 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3972 3973 // Verify the old decl was also a variable or variable template. 3974 VarDecl *Old = nullptr; 3975 VarTemplateDecl *OldTemplate = nullptr; 3976 if (Previous.isSingleResult()) { 3977 if (NewTemplate) { 3978 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3979 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3980 3981 if (auto *Shadow = 3982 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3983 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3984 return New->setInvalidDecl(); 3985 } else { 3986 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3987 3988 if (auto *Shadow = 3989 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3990 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3991 return New->setInvalidDecl(); 3992 } 3993 } 3994 if (!Old) { 3995 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3996 << New->getDeclName(); 3997 notePreviousDefinition(Previous.getRepresentativeDecl(), 3998 New->getLocation()); 3999 return New->setInvalidDecl(); 4000 } 4001 4002 // Ensure the template parameters are compatible. 4003 if (NewTemplate && 4004 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4005 OldTemplate->getTemplateParameters(), 4006 /*Complain=*/true, TPL_TemplateMatch)) 4007 return New->setInvalidDecl(); 4008 4009 // C++ [class.mem]p1: 4010 // A member shall not be declared twice in the member-specification [...] 4011 // 4012 // Here, we need only consider static data members. 4013 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4014 Diag(New->getLocation(), diag::err_duplicate_member) 4015 << New->getIdentifier(); 4016 Diag(Old->getLocation(), diag::note_previous_declaration); 4017 New->setInvalidDecl(); 4018 } 4019 4020 mergeDeclAttributes(New, Old); 4021 // Warn if an already-declared variable is made a weak_import in a subsequent 4022 // declaration 4023 if (New->hasAttr<WeakImportAttr>() && 4024 Old->getStorageClass() == SC_None && 4025 !Old->hasAttr<WeakImportAttr>()) { 4026 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4027 notePreviousDefinition(Old, New->getLocation()); 4028 // Remove weak_import attribute on new declaration. 4029 New->dropAttr<WeakImportAttr>(); 4030 } 4031 4032 if (New->hasAttr<InternalLinkageAttr>() && 4033 !Old->hasAttr<InternalLinkageAttr>()) { 4034 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4035 << New->getDeclName(); 4036 notePreviousDefinition(Old, New->getLocation()); 4037 New->dropAttr<InternalLinkageAttr>(); 4038 } 4039 4040 // Merge the types. 4041 VarDecl *MostRecent = Old->getMostRecentDecl(); 4042 if (MostRecent != Old) { 4043 MergeVarDeclTypes(New, MostRecent, 4044 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4045 if (New->isInvalidDecl()) 4046 return; 4047 } 4048 4049 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4050 if (New->isInvalidDecl()) 4051 return; 4052 4053 diag::kind PrevDiag; 4054 SourceLocation OldLocation; 4055 std::tie(PrevDiag, OldLocation) = 4056 getNoteDiagForInvalidRedeclaration(Old, New); 4057 4058 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4059 if (New->getStorageClass() == SC_Static && 4060 !New->isStaticDataMember() && 4061 Old->hasExternalFormalLinkage()) { 4062 if (getLangOpts().MicrosoftExt) { 4063 Diag(New->getLocation(), diag::ext_static_non_static) 4064 << New->getDeclName(); 4065 Diag(OldLocation, PrevDiag); 4066 } else { 4067 Diag(New->getLocation(), diag::err_static_non_static) 4068 << New->getDeclName(); 4069 Diag(OldLocation, PrevDiag); 4070 return New->setInvalidDecl(); 4071 } 4072 } 4073 // C99 6.2.2p4: 4074 // For an identifier declared with the storage-class specifier 4075 // extern in a scope in which a prior declaration of that 4076 // identifier is visible,23) if the prior declaration specifies 4077 // internal or external linkage, the linkage of the identifier at 4078 // the later declaration is the same as the linkage specified at 4079 // the prior declaration. If no prior declaration is visible, or 4080 // if the prior declaration specifies no linkage, then the 4081 // identifier has external linkage. 4082 if (New->hasExternalStorage() && Old->hasLinkage()) 4083 /* Okay */; 4084 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4085 !New->isStaticDataMember() && 4086 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4087 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4088 Diag(OldLocation, PrevDiag); 4089 return New->setInvalidDecl(); 4090 } 4091 4092 // Check if extern is followed by non-extern and vice-versa. 4093 if (New->hasExternalStorage() && 4094 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4095 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4096 Diag(OldLocation, PrevDiag); 4097 return New->setInvalidDecl(); 4098 } 4099 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4100 !New->hasExternalStorage()) { 4101 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4102 Diag(OldLocation, PrevDiag); 4103 return New->setInvalidDecl(); 4104 } 4105 4106 if (CheckRedeclarationModuleOwnership(New, Old)) 4107 return; 4108 4109 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4110 4111 // FIXME: The test for external storage here seems wrong? We still 4112 // need to check for mismatches. 4113 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4114 // Don't complain about out-of-line definitions of static members. 4115 !(Old->getLexicalDeclContext()->isRecord() && 4116 !New->getLexicalDeclContext()->isRecord())) { 4117 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4118 Diag(OldLocation, PrevDiag); 4119 return New->setInvalidDecl(); 4120 } 4121 4122 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4123 if (VarDecl *Def = Old->getDefinition()) { 4124 // C++1z [dcl.fcn.spec]p4: 4125 // If the definition of a variable appears in a translation unit before 4126 // its first declaration as inline, the program is ill-formed. 4127 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4128 Diag(Def->getLocation(), diag::note_previous_definition); 4129 } 4130 } 4131 4132 // If this redeclaration makes the variable inline, we may need to add it to 4133 // UndefinedButUsed. 4134 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4135 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4136 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4137 SourceLocation())); 4138 4139 if (New->getTLSKind() != Old->getTLSKind()) { 4140 if (!Old->getTLSKind()) { 4141 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4142 Diag(OldLocation, PrevDiag); 4143 } else if (!New->getTLSKind()) { 4144 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4145 Diag(OldLocation, PrevDiag); 4146 } else { 4147 // Do not allow redeclaration to change the variable between requiring 4148 // static and dynamic initialization. 4149 // FIXME: GCC allows this, but uses the TLS keyword on the first 4150 // declaration to determine the kind. Do we need to be compatible here? 4151 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4152 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4153 Diag(OldLocation, PrevDiag); 4154 } 4155 } 4156 4157 // C++ doesn't have tentative definitions, so go right ahead and check here. 4158 if (getLangOpts().CPlusPlus && 4159 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4160 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4161 Old->getCanonicalDecl()->isConstexpr()) { 4162 // This definition won't be a definition any more once it's been merged. 4163 Diag(New->getLocation(), 4164 diag::warn_deprecated_redundant_constexpr_static_def); 4165 } else if (VarDecl *Def = Old->getDefinition()) { 4166 if (checkVarDeclRedefinition(Def, New)) 4167 return; 4168 } 4169 } 4170 4171 if (haveIncompatibleLanguageLinkages(Old, New)) { 4172 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4173 Diag(OldLocation, PrevDiag); 4174 New->setInvalidDecl(); 4175 return; 4176 } 4177 4178 // Merge "used" flag. 4179 if (Old->getMostRecentDecl()->isUsed(false)) 4180 New->setIsUsed(); 4181 4182 // Keep a chain of previous declarations. 4183 New->setPreviousDecl(Old); 4184 if (NewTemplate) 4185 NewTemplate->setPreviousDecl(OldTemplate); 4186 adjustDeclContextForDeclaratorDecl(New, Old); 4187 4188 // Inherit access appropriately. 4189 New->setAccess(Old->getAccess()); 4190 if (NewTemplate) 4191 NewTemplate->setAccess(New->getAccess()); 4192 4193 if (Old->isInline()) 4194 New->setImplicitlyInline(); 4195 } 4196 4197 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4198 SourceManager &SrcMgr = getSourceManager(); 4199 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4200 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4201 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4202 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4203 auto &HSI = PP.getHeaderSearchInfo(); 4204 StringRef HdrFilename = 4205 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4206 4207 auto noteFromModuleOrInclude = [&](Module *Mod, 4208 SourceLocation IncLoc) -> bool { 4209 // Redefinition errors with modules are common with non modular mapped 4210 // headers, example: a non-modular header H in module A that also gets 4211 // included directly in a TU. Pointing twice to the same header/definition 4212 // is confusing, try to get better diagnostics when modules is on. 4213 if (IncLoc.isValid()) { 4214 if (Mod) { 4215 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4216 << HdrFilename.str() << Mod->getFullModuleName(); 4217 if (!Mod->DefinitionLoc.isInvalid()) 4218 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4219 << Mod->getFullModuleName(); 4220 } else { 4221 Diag(IncLoc, diag::note_redefinition_include_same_file) 4222 << HdrFilename.str(); 4223 } 4224 return true; 4225 } 4226 4227 return false; 4228 }; 4229 4230 // Is it the same file and same offset? Provide more information on why 4231 // this leads to a redefinition error. 4232 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4233 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4234 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4235 bool EmittedDiag = 4236 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4237 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4238 4239 // If the header has no guards, emit a note suggesting one. 4240 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4241 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4242 4243 if (EmittedDiag) 4244 return; 4245 } 4246 4247 // Redefinition coming from different files or couldn't do better above. 4248 if (Old->getLocation().isValid()) 4249 Diag(Old->getLocation(), diag::note_previous_definition); 4250 } 4251 4252 /// We've just determined that \p Old and \p New both appear to be definitions 4253 /// of the same variable. Either diagnose or fix the problem. 4254 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4255 if (!hasVisibleDefinition(Old) && 4256 (New->getFormalLinkage() == InternalLinkage || 4257 New->isInline() || 4258 New->getDescribedVarTemplate() || 4259 New->getNumTemplateParameterLists() || 4260 New->getDeclContext()->isDependentContext())) { 4261 // The previous definition is hidden, and multiple definitions are 4262 // permitted (in separate TUs). Demote this to a declaration. 4263 New->demoteThisDefinitionToDeclaration(); 4264 4265 // Make the canonical definition visible. 4266 if (auto *OldTD = Old->getDescribedVarTemplate()) 4267 makeMergedDefinitionVisible(OldTD); 4268 makeMergedDefinitionVisible(Old); 4269 return false; 4270 } else { 4271 Diag(New->getLocation(), diag::err_redefinition) << New; 4272 notePreviousDefinition(Old, New->getLocation()); 4273 New->setInvalidDecl(); 4274 return true; 4275 } 4276 } 4277 4278 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4279 /// no declarator (e.g. "struct foo;") is parsed. 4280 Decl * 4281 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4282 RecordDecl *&AnonRecord) { 4283 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4284 AnonRecord); 4285 } 4286 4287 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4288 // disambiguate entities defined in different scopes. 4289 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4290 // compatibility. 4291 // We will pick our mangling number depending on which version of MSVC is being 4292 // targeted. 4293 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4294 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4295 ? S->getMSCurManglingNumber() 4296 : S->getMSLastManglingNumber(); 4297 } 4298 4299 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4300 if (!Context.getLangOpts().CPlusPlus) 4301 return; 4302 4303 if (isa<CXXRecordDecl>(Tag->getParent())) { 4304 // If this tag is the direct child of a class, number it if 4305 // it is anonymous. 4306 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4307 return; 4308 MangleNumberingContext &MCtx = 4309 Context.getManglingNumberContext(Tag->getParent()); 4310 Context.setManglingNumber( 4311 Tag, MCtx.getManglingNumber( 4312 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4313 return; 4314 } 4315 4316 // If this tag isn't a direct child of a class, number it if it is local. 4317 MangleNumberingContext *MCtx; 4318 Decl *ManglingContextDecl; 4319 std::tie(MCtx, ManglingContextDecl) = 4320 getCurrentMangleNumberContext(Tag->getDeclContext()); 4321 if (MCtx) { 4322 Context.setManglingNumber( 4323 Tag, MCtx->getManglingNumber( 4324 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4325 } 4326 } 4327 4328 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4329 TypedefNameDecl *NewTD) { 4330 if (TagFromDeclSpec->isInvalidDecl()) 4331 return; 4332 4333 // Do nothing if the tag already has a name for linkage purposes. 4334 if (TagFromDeclSpec->hasNameForLinkage()) 4335 return; 4336 4337 // A well-formed anonymous tag must always be a TUK_Definition. 4338 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4339 4340 // The type must match the tag exactly; no qualifiers allowed. 4341 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4342 Context.getTagDeclType(TagFromDeclSpec))) { 4343 if (getLangOpts().CPlusPlus) 4344 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4345 return; 4346 } 4347 4348 // If we've already computed linkage for the anonymous tag, then 4349 // adding a typedef name for the anonymous decl can change that 4350 // linkage, which might be a serious problem. Diagnose this as 4351 // unsupported and ignore the typedef name. TODO: we should 4352 // pursue this as a language defect and establish a formal rule 4353 // for how to handle it. 4354 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4355 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4356 4357 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4358 tagLoc = getLocForEndOfToken(tagLoc); 4359 4360 llvm::SmallString<40> textToInsert; 4361 textToInsert += ' '; 4362 textToInsert += NewTD->getIdentifier()->getName(); 4363 Diag(tagLoc, diag::note_typedef_changes_linkage) 4364 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4365 return; 4366 } 4367 4368 // Otherwise, set this is the anon-decl typedef for the tag. 4369 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4370 } 4371 4372 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4373 switch (T) { 4374 case DeclSpec::TST_class: 4375 return 0; 4376 case DeclSpec::TST_struct: 4377 return 1; 4378 case DeclSpec::TST_interface: 4379 return 2; 4380 case DeclSpec::TST_union: 4381 return 3; 4382 case DeclSpec::TST_enum: 4383 return 4; 4384 default: 4385 llvm_unreachable("unexpected type specifier"); 4386 } 4387 } 4388 4389 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4390 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4391 /// parameters to cope with template friend declarations. 4392 Decl * 4393 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4394 MultiTemplateParamsArg TemplateParams, 4395 bool IsExplicitInstantiation, 4396 RecordDecl *&AnonRecord) { 4397 Decl *TagD = nullptr; 4398 TagDecl *Tag = nullptr; 4399 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4400 DS.getTypeSpecType() == DeclSpec::TST_struct || 4401 DS.getTypeSpecType() == DeclSpec::TST_interface || 4402 DS.getTypeSpecType() == DeclSpec::TST_union || 4403 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4404 TagD = DS.getRepAsDecl(); 4405 4406 if (!TagD) // We probably had an error 4407 return nullptr; 4408 4409 // Note that the above type specs guarantee that the 4410 // type rep is a Decl, whereas in many of the others 4411 // it's a Type. 4412 if (isa<TagDecl>(TagD)) 4413 Tag = cast<TagDecl>(TagD); 4414 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4415 Tag = CTD->getTemplatedDecl(); 4416 } 4417 4418 if (Tag) { 4419 handleTagNumbering(Tag, S); 4420 Tag->setFreeStanding(); 4421 if (Tag->isInvalidDecl()) 4422 return Tag; 4423 } 4424 4425 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4426 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4427 // or incomplete types shall not be restrict-qualified." 4428 if (TypeQuals & DeclSpec::TQ_restrict) 4429 Diag(DS.getRestrictSpecLoc(), 4430 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4431 << DS.getSourceRange(); 4432 } 4433 4434 if (DS.isInlineSpecified()) 4435 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4436 << getLangOpts().CPlusPlus17; 4437 4438 if (DS.hasConstexprSpecifier()) { 4439 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4440 // and definitions of functions and variables. 4441 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4442 // the declaration of a function or function template 4443 if (Tag) 4444 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4445 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4446 << DS.getConstexprSpecifier(); 4447 else 4448 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4449 << DS.getConstexprSpecifier(); 4450 // Don't emit warnings after this error. 4451 return TagD; 4452 } 4453 4454 DiagnoseFunctionSpecifiers(DS); 4455 4456 if (DS.isFriendSpecified()) { 4457 // If we're dealing with a decl but not a TagDecl, assume that 4458 // whatever routines created it handled the friendship aspect. 4459 if (TagD && !Tag) 4460 return nullptr; 4461 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4462 } 4463 4464 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4465 bool IsExplicitSpecialization = 4466 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4467 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4468 !IsExplicitInstantiation && !IsExplicitSpecialization && 4469 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4470 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4471 // nested-name-specifier unless it is an explicit instantiation 4472 // or an explicit specialization. 4473 // 4474 // FIXME: We allow class template partial specializations here too, per the 4475 // obvious intent of DR1819. 4476 // 4477 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4478 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4479 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4480 return nullptr; 4481 } 4482 4483 // Track whether this decl-specifier declares anything. 4484 bool DeclaresAnything = true; 4485 4486 // Handle anonymous struct definitions. 4487 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4488 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4489 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4490 if (getLangOpts().CPlusPlus || 4491 Record->getDeclContext()->isRecord()) { 4492 // If CurContext is a DeclContext that can contain statements, 4493 // RecursiveASTVisitor won't visit the decls that 4494 // BuildAnonymousStructOrUnion() will put into CurContext. 4495 // Also store them here so that they can be part of the 4496 // DeclStmt that gets created in this case. 4497 // FIXME: Also return the IndirectFieldDecls created by 4498 // BuildAnonymousStructOr union, for the same reason? 4499 if (CurContext->isFunctionOrMethod()) 4500 AnonRecord = Record; 4501 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4502 Context.getPrintingPolicy()); 4503 } 4504 4505 DeclaresAnything = false; 4506 } 4507 } 4508 4509 // C11 6.7.2.1p2: 4510 // A struct-declaration that does not declare an anonymous structure or 4511 // anonymous union shall contain a struct-declarator-list. 4512 // 4513 // This rule also existed in C89 and C99; the grammar for struct-declaration 4514 // did not permit a struct-declaration without a struct-declarator-list. 4515 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4516 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4517 // Check for Microsoft C extension: anonymous struct/union member. 4518 // Handle 2 kinds of anonymous struct/union: 4519 // struct STRUCT; 4520 // union UNION; 4521 // and 4522 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4523 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4524 if ((Tag && Tag->getDeclName()) || 4525 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4526 RecordDecl *Record = nullptr; 4527 if (Tag) 4528 Record = dyn_cast<RecordDecl>(Tag); 4529 else if (const RecordType *RT = 4530 DS.getRepAsType().get()->getAsStructureType()) 4531 Record = RT->getDecl(); 4532 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4533 Record = UT->getDecl(); 4534 4535 if (Record && getLangOpts().MicrosoftExt) { 4536 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4537 << Record->isUnion() << DS.getSourceRange(); 4538 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4539 } 4540 4541 DeclaresAnything = false; 4542 } 4543 } 4544 4545 // Skip all the checks below if we have a type error. 4546 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4547 (TagD && TagD->isInvalidDecl())) 4548 return TagD; 4549 4550 if (getLangOpts().CPlusPlus && 4551 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4552 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4553 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4554 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4555 DeclaresAnything = false; 4556 4557 if (!DS.isMissingDeclaratorOk()) { 4558 // Customize diagnostic for a typedef missing a name. 4559 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4560 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4561 << DS.getSourceRange(); 4562 else 4563 DeclaresAnything = false; 4564 } 4565 4566 if (DS.isModulePrivateSpecified() && 4567 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4568 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4569 << Tag->getTagKind() 4570 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4571 4572 ActOnDocumentableDecl(TagD); 4573 4574 // C 6.7/2: 4575 // A declaration [...] shall declare at least a declarator [...], a tag, 4576 // or the members of an enumeration. 4577 // C++ [dcl.dcl]p3: 4578 // [If there are no declarators], and except for the declaration of an 4579 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4580 // names into the program, or shall redeclare a name introduced by a 4581 // previous declaration. 4582 if (!DeclaresAnything) { 4583 // In C, we allow this as a (popular) extension / bug. Don't bother 4584 // producing further diagnostics for redundant qualifiers after this. 4585 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4586 return TagD; 4587 } 4588 4589 // C++ [dcl.stc]p1: 4590 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4591 // init-declarator-list of the declaration shall not be empty. 4592 // C++ [dcl.fct.spec]p1: 4593 // If a cv-qualifier appears in a decl-specifier-seq, the 4594 // init-declarator-list of the declaration shall not be empty. 4595 // 4596 // Spurious qualifiers here appear to be valid in C. 4597 unsigned DiagID = diag::warn_standalone_specifier; 4598 if (getLangOpts().CPlusPlus) 4599 DiagID = diag::ext_standalone_specifier; 4600 4601 // Note that a linkage-specification sets a storage class, but 4602 // 'extern "C" struct foo;' is actually valid and not theoretically 4603 // useless. 4604 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4605 if (SCS == DeclSpec::SCS_mutable) 4606 // Since mutable is not a viable storage class specifier in C, there is 4607 // no reason to treat it as an extension. Instead, diagnose as an error. 4608 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4609 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4610 Diag(DS.getStorageClassSpecLoc(), DiagID) 4611 << DeclSpec::getSpecifierName(SCS); 4612 } 4613 4614 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4615 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4616 << DeclSpec::getSpecifierName(TSCS); 4617 if (DS.getTypeQualifiers()) { 4618 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4619 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4620 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4621 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4622 // Restrict is covered above. 4623 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4624 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4625 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4626 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4627 } 4628 4629 // Warn about ignored type attributes, for example: 4630 // __attribute__((aligned)) struct A; 4631 // Attributes should be placed after tag to apply to type declaration. 4632 if (!DS.getAttributes().empty()) { 4633 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4634 if (TypeSpecType == DeclSpec::TST_class || 4635 TypeSpecType == DeclSpec::TST_struct || 4636 TypeSpecType == DeclSpec::TST_interface || 4637 TypeSpecType == DeclSpec::TST_union || 4638 TypeSpecType == DeclSpec::TST_enum) { 4639 for (const ParsedAttr &AL : DS.getAttributes()) 4640 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4641 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4642 } 4643 } 4644 4645 return TagD; 4646 } 4647 4648 /// We are trying to inject an anonymous member into the given scope; 4649 /// check if there's an existing declaration that can't be overloaded. 4650 /// 4651 /// \return true if this is a forbidden redeclaration 4652 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4653 Scope *S, 4654 DeclContext *Owner, 4655 DeclarationName Name, 4656 SourceLocation NameLoc, 4657 bool IsUnion) { 4658 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4659 Sema::ForVisibleRedeclaration); 4660 if (!SemaRef.LookupName(R, S)) return false; 4661 4662 // Pick a representative declaration. 4663 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4664 assert(PrevDecl && "Expected a non-null Decl"); 4665 4666 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4667 return false; 4668 4669 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4670 << IsUnion << Name; 4671 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4672 4673 return true; 4674 } 4675 4676 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4677 /// anonymous struct or union AnonRecord into the owning context Owner 4678 /// and scope S. This routine will be invoked just after we realize 4679 /// that an unnamed union or struct is actually an anonymous union or 4680 /// struct, e.g., 4681 /// 4682 /// @code 4683 /// union { 4684 /// int i; 4685 /// float f; 4686 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4687 /// // f into the surrounding scope.x 4688 /// @endcode 4689 /// 4690 /// This routine is recursive, injecting the names of nested anonymous 4691 /// structs/unions into the owning context and scope as well. 4692 static bool 4693 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4694 RecordDecl *AnonRecord, AccessSpecifier AS, 4695 SmallVectorImpl<NamedDecl *> &Chaining) { 4696 bool Invalid = false; 4697 4698 // Look every FieldDecl and IndirectFieldDecl with a name. 4699 for (auto *D : AnonRecord->decls()) { 4700 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4701 cast<NamedDecl>(D)->getDeclName()) { 4702 ValueDecl *VD = cast<ValueDecl>(D); 4703 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4704 VD->getLocation(), 4705 AnonRecord->isUnion())) { 4706 // C++ [class.union]p2: 4707 // The names of the members of an anonymous union shall be 4708 // distinct from the names of any other entity in the 4709 // scope in which the anonymous union is declared. 4710 Invalid = true; 4711 } else { 4712 // C++ [class.union]p2: 4713 // For the purpose of name lookup, after the anonymous union 4714 // definition, the members of the anonymous union are 4715 // considered to have been defined in the scope in which the 4716 // anonymous union is declared. 4717 unsigned OldChainingSize = Chaining.size(); 4718 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4719 Chaining.append(IF->chain_begin(), IF->chain_end()); 4720 else 4721 Chaining.push_back(VD); 4722 4723 assert(Chaining.size() >= 2); 4724 NamedDecl **NamedChain = 4725 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4726 for (unsigned i = 0; i < Chaining.size(); i++) 4727 NamedChain[i] = Chaining[i]; 4728 4729 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4730 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4731 VD->getType(), {NamedChain, Chaining.size()}); 4732 4733 for (const auto *Attr : VD->attrs()) 4734 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4735 4736 IndirectField->setAccess(AS); 4737 IndirectField->setImplicit(); 4738 SemaRef.PushOnScopeChains(IndirectField, S); 4739 4740 // That includes picking up the appropriate access specifier. 4741 if (AS != AS_none) IndirectField->setAccess(AS); 4742 4743 Chaining.resize(OldChainingSize); 4744 } 4745 } 4746 } 4747 4748 return Invalid; 4749 } 4750 4751 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4752 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4753 /// illegal input values are mapped to SC_None. 4754 static StorageClass 4755 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4756 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4757 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4758 "Parser allowed 'typedef' as storage class VarDecl."); 4759 switch (StorageClassSpec) { 4760 case DeclSpec::SCS_unspecified: return SC_None; 4761 case DeclSpec::SCS_extern: 4762 if (DS.isExternInLinkageSpec()) 4763 return SC_None; 4764 return SC_Extern; 4765 case DeclSpec::SCS_static: return SC_Static; 4766 case DeclSpec::SCS_auto: return SC_Auto; 4767 case DeclSpec::SCS_register: return SC_Register; 4768 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4769 // Illegal SCSs map to None: error reporting is up to the caller. 4770 case DeclSpec::SCS_mutable: // Fall through. 4771 case DeclSpec::SCS_typedef: return SC_None; 4772 } 4773 llvm_unreachable("unknown storage class specifier"); 4774 } 4775 4776 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4777 assert(Record->hasInClassInitializer()); 4778 4779 for (const auto *I : Record->decls()) { 4780 const auto *FD = dyn_cast<FieldDecl>(I); 4781 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4782 FD = IFD->getAnonField(); 4783 if (FD && FD->hasInClassInitializer()) 4784 return FD->getLocation(); 4785 } 4786 4787 llvm_unreachable("couldn't find in-class initializer"); 4788 } 4789 4790 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4791 SourceLocation DefaultInitLoc) { 4792 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4793 return; 4794 4795 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4796 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4797 } 4798 4799 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4800 CXXRecordDecl *AnonUnion) { 4801 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4802 return; 4803 4804 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4805 } 4806 4807 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4808 /// anonymous structure or union. Anonymous unions are a C++ feature 4809 /// (C++ [class.union]) and a C11 feature; anonymous structures 4810 /// are a C11 feature and GNU C++ extension. 4811 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4812 AccessSpecifier AS, 4813 RecordDecl *Record, 4814 const PrintingPolicy &Policy) { 4815 DeclContext *Owner = Record->getDeclContext(); 4816 4817 // Diagnose whether this anonymous struct/union is an extension. 4818 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4819 Diag(Record->getLocation(), diag::ext_anonymous_union); 4820 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4821 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4822 else if (!Record->isUnion() && !getLangOpts().C11) 4823 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4824 4825 // C and C++ require different kinds of checks for anonymous 4826 // structs/unions. 4827 bool Invalid = false; 4828 if (getLangOpts().CPlusPlus) { 4829 const char *PrevSpec = nullptr; 4830 if (Record->isUnion()) { 4831 // C++ [class.union]p6: 4832 // C++17 [class.union.anon]p2: 4833 // Anonymous unions declared in a named namespace or in the 4834 // global namespace shall be declared static. 4835 unsigned DiagID; 4836 DeclContext *OwnerScope = Owner->getRedeclContext(); 4837 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4838 (OwnerScope->isTranslationUnit() || 4839 (OwnerScope->isNamespace() && 4840 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4841 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4842 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4843 4844 // Recover by adding 'static'. 4845 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4846 PrevSpec, DiagID, Policy); 4847 } 4848 // C++ [class.union]p6: 4849 // A storage class is not allowed in a declaration of an 4850 // anonymous union in a class scope. 4851 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4852 isa<RecordDecl>(Owner)) { 4853 Diag(DS.getStorageClassSpecLoc(), 4854 diag::err_anonymous_union_with_storage_spec) 4855 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4856 4857 // Recover by removing the storage specifier. 4858 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4859 SourceLocation(), 4860 PrevSpec, DiagID, Context.getPrintingPolicy()); 4861 } 4862 } 4863 4864 // Ignore const/volatile/restrict qualifiers. 4865 if (DS.getTypeQualifiers()) { 4866 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4867 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4868 << Record->isUnion() << "const" 4869 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4870 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4871 Diag(DS.getVolatileSpecLoc(), 4872 diag::ext_anonymous_struct_union_qualified) 4873 << Record->isUnion() << "volatile" 4874 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4875 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4876 Diag(DS.getRestrictSpecLoc(), 4877 diag::ext_anonymous_struct_union_qualified) 4878 << Record->isUnion() << "restrict" 4879 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4880 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4881 Diag(DS.getAtomicSpecLoc(), 4882 diag::ext_anonymous_struct_union_qualified) 4883 << Record->isUnion() << "_Atomic" 4884 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4885 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4886 Diag(DS.getUnalignedSpecLoc(), 4887 diag::ext_anonymous_struct_union_qualified) 4888 << Record->isUnion() << "__unaligned" 4889 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4890 4891 DS.ClearTypeQualifiers(); 4892 } 4893 4894 // C++ [class.union]p2: 4895 // The member-specification of an anonymous union shall only 4896 // define non-static data members. [Note: nested types and 4897 // functions cannot be declared within an anonymous union. ] 4898 for (auto *Mem : Record->decls()) { 4899 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4900 // C++ [class.union]p3: 4901 // An anonymous union shall not have private or protected 4902 // members (clause 11). 4903 assert(FD->getAccess() != AS_none); 4904 if (FD->getAccess() != AS_public) { 4905 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4906 << Record->isUnion() << (FD->getAccess() == AS_protected); 4907 Invalid = true; 4908 } 4909 4910 // C++ [class.union]p1 4911 // An object of a class with a non-trivial constructor, a non-trivial 4912 // copy constructor, a non-trivial destructor, or a non-trivial copy 4913 // assignment operator cannot be a member of a union, nor can an 4914 // array of such objects. 4915 if (CheckNontrivialField(FD)) 4916 Invalid = true; 4917 } else if (Mem->isImplicit()) { 4918 // Any implicit members are fine. 4919 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4920 // This is a type that showed up in an 4921 // elaborated-type-specifier inside the anonymous struct or 4922 // union, but which actually declares a type outside of the 4923 // anonymous struct or union. It's okay. 4924 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4925 if (!MemRecord->isAnonymousStructOrUnion() && 4926 MemRecord->getDeclName()) { 4927 // Visual C++ allows type definition in anonymous struct or union. 4928 if (getLangOpts().MicrosoftExt) 4929 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4930 << Record->isUnion(); 4931 else { 4932 // This is a nested type declaration. 4933 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4934 << Record->isUnion(); 4935 Invalid = true; 4936 } 4937 } else { 4938 // This is an anonymous type definition within another anonymous type. 4939 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4940 // not part of standard C++. 4941 Diag(MemRecord->getLocation(), 4942 diag::ext_anonymous_record_with_anonymous_type) 4943 << Record->isUnion(); 4944 } 4945 } else if (isa<AccessSpecDecl>(Mem)) { 4946 // Any access specifier is fine. 4947 } else if (isa<StaticAssertDecl>(Mem)) { 4948 // In C++1z, static_assert declarations are also fine. 4949 } else { 4950 // We have something that isn't a non-static data 4951 // member. Complain about it. 4952 unsigned DK = diag::err_anonymous_record_bad_member; 4953 if (isa<TypeDecl>(Mem)) 4954 DK = diag::err_anonymous_record_with_type; 4955 else if (isa<FunctionDecl>(Mem)) 4956 DK = diag::err_anonymous_record_with_function; 4957 else if (isa<VarDecl>(Mem)) 4958 DK = diag::err_anonymous_record_with_static; 4959 4960 // Visual C++ allows type definition in anonymous struct or union. 4961 if (getLangOpts().MicrosoftExt && 4962 DK == diag::err_anonymous_record_with_type) 4963 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4964 << Record->isUnion(); 4965 else { 4966 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4967 Invalid = true; 4968 } 4969 } 4970 } 4971 4972 // C++11 [class.union]p8 (DR1460): 4973 // At most one variant member of a union may have a 4974 // brace-or-equal-initializer. 4975 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4976 Owner->isRecord()) 4977 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4978 cast<CXXRecordDecl>(Record)); 4979 } 4980 4981 if (!Record->isUnion() && !Owner->isRecord()) { 4982 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4983 << getLangOpts().CPlusPlus; 4984 Invalid = true; 4985 } 4986 4987 // C++ [dcl.dcl]p3: 4988 // [If there are no declarators], and except for the declaration of an 4989 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4990 // names into the program 4991 // C++ [class.mem]p2: 4992 // each such member-declaration shall either declare at least one member 4993 // name of the class or declare at least one unnamed bit-field 4994 // 4995 // For C this is an error even for a named struct, and is diagnosed elsewhere. 4996 if (getLangOpts().CPlusPlus && Record->field_empty()) 4997 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4998 4999 // Mock up a declarator. 5000 Declarator Dc(DS, DeclaratorContext::MemberContext); 5001 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5002 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5003 5004 // Create a declaration for this anonymous struct/union. 5005 NamedDecl *Anon = nullptr; 5006 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5007 Anon = FieldDecl::Create( 5008 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5009 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5010 /*BitWidth=*/nullptr, /*Mutable=*/false, 5011 /*InitStyle=*/ICIS_NoInit); 5012 Anon->setAccess(AS); 5013 if (getLangOpts().CPlusPlus) 5014 FieldCollector->Add(cast<FieldDecl>(Anon)); 5015 } else { 5016 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5017 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5018 if (SCSpec == DeclSpec::SCS_mutable) { 5019 // mutable can only appear on non-static class members, so it's always 5020 // an error here 5021 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5022 Invalid = true; 5023 SC = SC_None; 5024 } 5025 5026 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5027 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5028 Context.getTypeDeclType(Record), TInfo, SC); 5029 5030 // Default-initialize the implicit variable. This initialization will be 5031 // trivial in almost all cases, except if a union member has an in-class 5032 // initializer: 5033 // union { int n = 0; }; 5034 ActOnUninitializedDecl(Anon); 5035 } 5036 Anon->setImplicit(); 5037 5038 // Mark this as an anonymous struct/union type. 5039 Record->setAnonymousStructOrUnion(true); 5040 5041 // Add the anonymous struct/union object to the current 5042 // context. We'll be referencing this object when we refer to one of 5043 // its members. 5044 Owner->addDecl(Anon); 5045 5046 // Inject the members of the anonymous struct/union into the owning 5047 // context and into the identifier resolver chain for name lookup 5048 // purposes. 5049 SmallVector<NamedDecl*, 2> Chain; 5050 Chain.push_back(Anon); 5051 5052 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5053 Invalid = true; 5054 5055 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5056 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5057 MangleNumberingContext *MCtx; 5058 Decl *ManglingContextDecl; 5059 std::tie(MCtx, ManglingContextDecl) = 5060 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5061 if (MCtx) { 5062 Context.setManglingNumber( 5063 NewVD, MCtx->getManglingNumber( 5064 NewVD, getMSManglingNumber(getLangOpts(), S))); 5065 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5066 } 5067 } 5068 } 5069 5070 if (Invalid) 5071 Anon->setInvalidDecl(); 5072 5073 return Anon; 5074 } 5075 5076 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5077 /// Microsoft C anonymous structure. 5078 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5079 /// Example: 5080 /// 5081 /// struct A { int a; }; 5082 /// struct B { struct A; int b; }; 5083 /// 5084 /// void foo() { 5085 /// B var; 5086 /// var.a = 3; 5087 /// } 5088 /// 5089 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5090 RecordDecl *Record) { 5091 assert(Record && "expected a record!"); 5092 5093 // Mock up a declarator. 5094 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5095 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5096 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5097 5098 auto *ParentDecl = cast<RecordDecl>(CurContext); 5099 QualType RecTy = Context.getTypeDeclType(Record); 5100 5101 // Create a declaration for this anonymous struct. 5102 NamedDecl *Anon = 5103 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5104 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5105 /*BitWidth=*/nullptr, /*Mutable=*/false, 5106 /*InitStyle=*/ICIS_NoInit); 5107 Anon->setImplicit(); 5108 5109 // Add the anonymous struct object to the current context. 5110 CurContext->addDecl(Anon); 5111 5112 // Inject the members of the anonymous struct into the current 5113 // context and into the identifier resolver chain for name lookup 5114 // purposes. 5115 SmallVector<NamedDecl*, 2> Chain; 5116 Chain.push_back(Anon); 5117 5118 RecordDecl *RecordDef = Record->getDefinition(); 5119 if (RequireCompleteType(Anon->getLocation(), RecTy, 5120 diag::err_field_incomplete) || 5121 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5122 AS_none, Chain)) { 5123 Anon->setInvalidDecl(); 5124 ParentDecl->setInvalidDecl(); 5125 } 5126 5127 return Anon; 5128 } 5129 5130 /// GetNameForDeclarator - Determine the full declaration name for the 5131 /// given Declarator. 5132 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5133 return GetNameFromUnqualifiedId(D.getName()); 5134 } 5135 5136 /// Retrieves the declaration name from a parsed unqualified-id. 5137 DeclarationNameInfo 5138 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5139 DeclarationNameInfo NameInfo; 5140 NameInfo.setLoc(Name.StartLocation); 5141 5142 switch (Name.getKind()) { 5143 5144 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5145 case UnqualifiedIdKind::IK_Identifier: 5146 NameInfo.setName(Name.Identifier); 5147 return NameInfo; 5148 5149 case UnqualifiedIdKind::IK_DeductionGuideName: { 5150 // C++ [temp.deduct.guide]p3: 5151 // The simple-template-id shall name a class template specialization. 5152 // The template-name shall be the same identifier as the template-name 5153 // of the simple-template-id. 5154 // These together intend to imply that the template-name shall name a 5155 // class template. 5156 // FIXME: template<typename T> struct X {}; 5157 // template<typename T> using Y = X<T>; 5158 // Y(int) -> Y<int>; 5159 // satisfies these rules but does not name a class template. 5160 TemplateName TN = Name.TemplateName.get().get(); 5161 auto *Template = TN.getAsTemplateDecl(); 5162 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5163 Diag(Name.StartLocation, 5164 diag::err_deduction_guide_name_not_class_template) 5165 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5166 if (Template) 5167 Diag(Template->getLocation(), diag::note_template_decl_here); 5168 return DeclarationNameInfo(); 5169 } 5170 5171 NameInfo.setName( 5172 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5173 return NameInfo; 5174 } 5175 5176 case UnqualifiedIdKind::IK_OperatorFunctionId: 5177 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5178 Name.OperatorFunctionId.Operator)); 5179 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5180 = Name.OperatorFunctionId.SymbolLocations[0]; 5181 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5182 = Name.EndLocation.getRawEncoding(); 5183 return NameInfo; 5184 5185 case UnqualifiedIdKind::IK_LiteralOperatorId: 5186 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5187 Name.Identifier)); 5188 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5189 return NameInfo; 5190 5191 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5192 TypeSourceInfo *TInfo; 5193 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5194 if (Ty.isNull()) 5195 return DeclarationNameInfo(); 5196 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5197 Context.getCanonicalType(Ty))); 5198 NameInfo.setNamedTypeInfo(TInfo); 5199 return NameInfo; 5200 } 5201 5202 case UnqualifiedIdKind::IK_ConstructorName: { 5203 TypeSourceInfo *TInfo; 5204 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5205 if (Ty.isNull()) 5206 return DeclarationNameInfo(); 5207 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5208 Context.getCanonicalType(Ty))); 5209 NameInfo.setNamedTypeInfo(TInfo); 5210 return NameInfo; 5211 } 5212 5213 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5214 // In well-formed code, we can only have a constructor 5215 // template-id that refers to the current context, so go there 5216 // to find the actual type being constructed. 5217 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5218 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5219 return DeclarationNameInfo(); 5220 5221 // Determine the type of the class being constructed. 5222 QualType CurClassType = Context.getTypeDeclType(CurClass); 5223 5224 // FIXME: Check two things: that the template-id names the same type as 5225 // CurClassType, and that the template-id does not occur when the name 5226 // was qualified. 5227 5228 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5229 Context.getCanonicalType(CurClassType))); 5230 // FIXME: should we retrieve TypeSourceInfo? 5231 NameInfo.setNamedTypeInfo(nullptr); 5232 return NameInfo; 5233 } 5234 5235 case UnqualifiedIdKind::IK_DestructorName: { 5236 TypeSourceInfo *TInfo; 5237 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5238 if (Ty.isNull()) 5239 return DeclarationNameInfo(); 5240 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5241 Context.getCanonicalType(Ty))); 5242 NameInfo.setNamedTypeInfo(TInfo); 5243 return NameInfo; 5244 } 5245 5246 case UnqualifiedIdKind::IK_TemplateId: { 5247 TemplateName TName = Name.TemplateId->Template.get(); 5248 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5249 return Context.getNameForTemplate(TName, TNameLoc); 5250 } 5251 5252 } // switch (Name.getKind()) 5253 5254 llvm_unreachable("Unknown name kind"); 5255 } 5256 5257 static QualType getCoreType(QualType Ty) { 5258 do { 5259 if (Ty->isPointerType() || Ty->isReferenceType()) 5260 Ty = Ty->getPointeeType(); 5261 else if (Ty->isArrayType()) 5262 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5263 else 5264 return Ty.withoutLocalFastQualifiers(); 5265 } while (true); 5266 } 5267 5268 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5269 /// and Definition have "nearly" matching parameters. This heuristic is 5270 /// used to improve diagnostics in the case where an out-of-line function 5271 /// definition doesn't match any declaration within the class or namespace. 5272 /// Also sets Params to the list of indices to the parameters that differ 5273 /// between the declaration and the definition. If hasSimilarParameters 5274 /// returns true and Params is empty, then all of the parameters match. 5275 static bool hasSimilarParameters(ASTContext &Context, 5276 FunctionDecl *Declaration, 5277 FunctionDecl *Definition, 5278 SmallVectorImpl<unsigned> &Params) { 5279 Params.clear(); 5280 if (Declaration->param_size() != Definition->param_size()) 5281 return false; 5282 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5283 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5284 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5285 5286 // The parameter types are identical 5287 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5288 continue; 5289 5290 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5291 QualType DefParamBaseTy = getCoreType(DefParamTy); 5292 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5293 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5294 5295 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5296 (DeclTyName && DeclTyName == DefTyName)) 5297 Params.push_back(Idx); 5298 else // The two parameters aren't even close 5299 return false; 5300 } 5301 5302 return true; 5303 } 5304 5305 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5306 /// declarator needs to be rebuilt in the current instantiation. 5307 /// Any bits of declarator which appear before the name are valid for 5308 /// consideration here. That's specifically the type in the decl spec 5309 /// and the base type in any member-pointer chunks. 5310 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5311 DeclarationName Name) { 5312 // The types we specifically need to rebuild are: 5313 // - typenames, typeofs, and decltypes 5314 // - types which will become injected class names 5315 // Of course, we also need to rebuild any type referencing such a 5316 // type. It's safest to just say "dependent", but we call out a 5317 // few cases here. 5318 5319 DeclSpec &DS = D.getMutableDeclSpec(); 5320 switch (DS.getTypeSpecType()) { 5321 case DeclSpec::TST_typename: 5322 case DeclSpec::TST_typeofType: 5323 case DeclSpec::TST_underlyingType: 5324 case DeclSpec::TST_atomic: { 5325 // Grab the type from the parser. 5326 TypeSourceInfo *TSI = nullptr; 5327 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5328 if (T.isNull() || !T->isDependentType()) break; 5329 5330 // Make sure there's a type source info. This isn't really much 5331 // of a waste; most dependent types should have type source info 5332 // attached already. 5333 if (!TSI) 5334 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5335 5336 // Rebuild the type in the current instantiation. 5337 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5338 if (!TSI) return true; 5339 5340 // Store the new type back in the decl spec. 5341 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5342 DS.UpdateTypeRep(LocType); 5343 break; 5344 } 5345 5346 case DeclSpec::TST_decltype: 5347 case DeclSpec::TST_typeofExpr: { 5348 Expr *E = DS.getRepAsExpr(); 5349 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5350 if (Result.isInvalid()) return true; 5351 DS.UpdateExprRep(Result.get()); 5352 break; 5353 } 5354 5355 default: 5356 // Nothing to do for these decl specs. 5357 break; 5358 } 5359 5360 // It doesn't matter what order we do this in. 5361 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5362 DeclaratorChunk &Chunk = D.getTypeObject(I); 5363 5364 // The only type information in the declarator which can come 5365 // before the declaration name is the base type of a member 5366 // pointer. 5367 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5368 continue; 5369 5370 // Rebuild the scope specifier in-place. 5371 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5372 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5373 return true; 5374 } 5375 5376 return false; 5377 } 5378 5379 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5380 D.setFunctionDefinitionKind(FDK_Declaration); 5381 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5382 5383 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5384 Dcl && Dcl->getDeclContext()->isFileContext()) 5385 Dcl->setTopLevelDeclInObjCContainer(); 5386 5387 if (getLangOpts().OpenCL) 5388 setCurrentOpenCLExtensionForDecl(Dcl); 5389 5390 return Dcl; 5391 } 5392 5393 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5394 /// If T is the name of a class, then each of the following shall have a 5395 /// name different from T: 5396 /// - every static data member of class T; 5397 /// - every member function of class T 5398 /// - every member of class T that is itself a type; 5399 /// \returns true if the declaration name violates these rules. 5400 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5401 DeclarationNameInfo NameInfo) { 5402 DeclarationName Name = NameInfo.getName(); 5403 5404 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5405 while (Record && Record->isAnonymousStructOrUnion()) 5406 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5407 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5408 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5409 return true; 5410 } 5411 5412 return false; 5413 } 5414 5415 /// Diagnose a declaration whose declarator-id has the given 5416 /// nested-name-specifier. 5417 /// 5418 /// \param SS The nested-name-specifier of the declarator-id. 5419 /// 5420 /// \param DC The declaration context to which the nested-name-specifier 5421 /// resolves. 5422 /// 5423 /// \param Name The name of the entity being declared. 5424 /// 5425 /// \param Loc The location of the name of the entity being declared. 5426 /// 5427 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5428 /// we're declaring an explicit / partial specialization / instantiation. 5429 /// 5430 /// \returns true if we cannot safely recover from this error, false otherwise. 5431 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5432 DeclarationName Name, 5433 SourceLocation Loc, bool IsTemplateId) { 5434 DeclContext *Cur = CurContext; 5435 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5436 Cur = Cur->getParent(); 5437 5438 // If the user provided a superfluous scope specifier that refers back to the 5439 // class in which the entity is already declared, diagnose and ignore it. 5440 // 5441 // class X { 5442 // void X::f(); 5443 // }; 5444 // 5445 // Note, it was once ill-formed to give redundant qualification in all 5446 // contexts, but that rule was removed by DR482. 5447 if (Cur->Equals(DC)) { 5448 if (Cur->isRecord()) { 5449 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5450 : diag::err_member_extra_qualification) 5451 << Name << FixItHint::CreateRemoval(SS.getRange()); 5452 SS.clear(); 5453 } else { 5454 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5455 } 5456 return false; 5457 } 5458 5459 // Check whether the qualifying scope encloses the scope of the original 5460 // declaration. For a template-id, we perform the checks in 5461 // CheckTemplateSpecializationScope. 5462 if (!Cur->Encloses(DC) && !IsTemplateId) { 5463 if (Cur->isRecord()) 5464 Diag(Loc, diag::err_member_qualification) 5465 << Name << SS.getRange(); 5466 else if (isa<TranslationUnitDecl>(DC)) 5467 Diag(Loc, diag::err_invalid_declarator_global_scope) 5468 << Name << SS.getRange(); 5469 else if (isa<FunctionDecl>(Cur)) 5470 Diag(Loc, diag::err_invalid_declarator_in_function) 5471 << Name << SS.getRange(); 5472 else if (isa<BlockDecl>(Cur)) 5473 Diag(Loc, diag::err_invalid_declarator_in_block) 5474 << Name << SS.getRange(); 5475 else 5476 Diag(Loc, diag::err_invalid_declarator_scope) 5477 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5478 5479 return true; 5480 } 5481 5482 if (Cur->isRecord()) { 5483 // Cannot qualify members within a class. 5484 Diag(Loc, diag::err_member_qualification) 5485 << Name << SS.getRange(); 5486 SS.clear(); 5487 5488 // C++ constructors and destructors with incorrect scopes can break 5489 // our AST invariants by having the wrong underlying types. If 5490 // that's the case, then drop this declaration entirely. 5491 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5492 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5493 !Context.hasSameType(Name.getCXXNameType(), 5494 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5495 return true; 5496 5497 return false; 5498 } 5499 5500 // C++11 [dcl.meaning]p1: 5501 // [...] "The nested-name-specifier of the qualified declarator-id shall 5502 // not begin with a decltype-specifer" 5503 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5504 while (SpecLoc.getPrefix()) 5505 SpecLoc = SpecLoc.getPrefix(); 5506 if (dyn_cast_or_null<DecltypeType>( 5507 SpecLoc.getNestedNameSpecifier()->getAsType())) 5508 Diag(Loc, diag::err_decltype_in_declarator) 5509 << SpecLoc.getTypeLoc().getSourceRange(); 5510 5511 return false; 5512 } 5513 5514 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5515 MultiTemplateParamsArg TemplateParamLists) { 5516 // TODO: consider using NameInfo for diagnostic. 5517 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5518 DeclarationName Name = NameInfo.getName(); 5519 5520 // All of these full declarators require an identifier. If it doesn't have 5521 // one, the ParsedFreeStandingDeclSpec action should be used. 5522 if (D.isDecompositionDeclarator()) { 5523 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5524 } else if (!Name) { 5525 if (!D.isInvalidType()) // Reject this if we think it is valid. 5526 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5527 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5528 return nullptr; 5529 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5530 return nullptr; 5531 5532 // The scope passed in may not be a decl scope. Zip up the scope tree until 5533 // we find one that is. 5534 while ((S->getFlags() & Scope::DeclScope) == 0 || 5535 (S->getFlags() & Scope::TemplateParamScope) != 0) 5536 S = S->getParent(); 5537 5538 DeclContext *DC = CurContext; 5539 if (D.getCXXScopeSpec().isInvalid()) 5540 D.setInvalidType(); 5541 else if (D.getCXXScopeSpec().isSet()) { 5542 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5543 UPPC_DeclarationQualifier)) 5544 return nullptr; 5545 5546 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5547 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5548 if (!DC || isa<EnumDecl>(DC)) { 5549 // If we could not compute the declaration context, it's because the 5550 // declaration context is dependent but does not refer to a class, 5551 // class template, or class template partial specialization. Complain 5552 // and return early, to avoid the coming semantic disaster. 5553 Diag(D.getIdentifierLoc(), 5554 diag::err_template_qualified_declarator_no_match) 5555 << D.getCXXScopeSpec().getScopeRep() 5556 << D.getCXXScopeSpec().getRange(); 5557 return nullptr; 5558 } 5559 bool IsDependentContext = DC->isDependentContext(); 5560 5561 if (!IsDependentContext && 5562 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5563 return nullptr; 5564 5565 // If a class is incomplete, do not parse entities inside it. 5566 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5567 Diag(D.getIdentifierLoc(), 5568 diag::err_member_def_undefined_record) 5569 << Name << DC << D.getCXXScopeSpec().getRange(); 5570 return nullptr; 5571 } 5572 if (!D.getDeclSpec().isFriendSpecified()) { 5573 if (diagnoseQualifiedDeclaration( 5574 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5575 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5576 if (DC->isRecord()) 5577 return nullptr; 5578 5579 D.setInvalidType(); 5580 } 5581 } 5582 5583 // Check whether we need to rebuild the type of the given 5584 // declaration in the current instantiation. 5585 if (EnteringContext && IsDependentContext && 5586 TemplateParamLists.size() != 0) { 5587 ContextRAII SavedContext(*this, DC); 5588 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5589 D.setInvalidType(); 5590 } 5591 } 5592 5593 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5594 QualType R = TInfo->getType(); 5595 5596 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5597 UPPC_DeclarationType)) 5598 D.setInvalidType(); 5599 5600 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5601 forRedeclarationInCurContext()); 5602 5603 // See if this is a redefinition of a variable in the same scope. 5604 if (!D.getCXXScopeSpec().isSet()) { 5605 bool IsLinkageLookup = false; 5606 bool CreateBuiltins = false; 5607 5608 // If the declaration we're planning to build will be a function 5609 // or object with linkage, then look for another declaration with 5610 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5611 // 5612 // If the declaration we're planning to build will be declared with 5613 // external linkage in the translation unit, create any builtin with 5614 // the same name. 5615 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5616 /* Do nothing*/; 5617 else if (CurContext->isFunctionOrMethod() && 5618 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5619 R->isFunctionType())) { 5620 IsLinkageLookup = true; 5621 CreateBuiltins = 5622 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5623 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5624 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5625 CreateBuiltins = true; 5626 5627 if (IsLinkageLookup) { 5628 Previous.clear(LookupRedeclarationWithLinkage); 5629 Previous.setRedeclarationKind(ForExternalRedeclaration); 5630 } 5631 5632 LookupName(Previous, S, CreateBuiltins); 5633 } else { // Something like "int foo::x;" 5634 LookupQualifiedName(Previous, DC); 5635 5636 // C++ [dcl.meaning]p1: 5637 // When the declarator-id is qualified, the declaration shall refer to a 5638 // previously declared member of the class or namespace to which the 5639 // qualifier refers (or, in the case of a namespace, of an element of the 5640 // inline namespace set of that namespace (7.3.1)) or to a specialization 5641 // thereof; [...] 5642 // 5643 // Note that we already checked the context above, and that we do not have 5644 // enough information to make sure that Previous contains the declaration 5645 // we want to match. For example, given: 5646 // 5647 // class X { 5648 // void f(); 5649 // void f(float); 5650 // }; 5651 // 5652 // void X::f(int) { } // ill-formed 5653 // 5654 // In this case, Previous will point to the overload set 5655 // containing the two f's declared in X, but neither of them 5656 // matches. 5657 5658 // C++ [dcl.meaning]p1: 5659 // [...] the member shall not merely have been introduced by a 5660 // using-declaration in the scope of the class or namespace nominated by 5661 // the nested-name-specifier of the declarator-id. 5662 RemoveUsingDecls(Previous); 5663 } 5664 5665 if (Previous.isSingleResult() && 5666 Previous.getFoundDecl()->isTemplateParameter()) { 5667 // Maybe we will complain about the shadowed template parameter. 5668 if (!D.isInvalidType()) 5669 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5670 Previous.getFoundDecl()); 5671 5672 // Just pretend that we didn't see the previous declaration. 5673 Previous.clear(); 5674 } 5675 5676 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5677 // Forget that the previous declaration is the injected-class-name. 5678 Previous.clear(); 5679 5680 // In C++, the previous declaration we find might be a tag type 5681 // (class or enum). In this case, the new declaration will hide the 5682 // tag type. Note that this applies to functions, function templates, and 5683 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5684 if (Previous.isSingleTagDecl() && 5685 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5686 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5687 Previous.clear(); 5688 5689 // Check that there are no default arguments other than in the parameters 5690 // of a function declaration (C++ only). 5691 if (getLangOpts().CPlusPlus) 5692 CheckExtraCXXDefaultArguments(D); 5693 5694 NamedDecl *New; 5695 5696 bool AddToScope = true; 5697 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5698 if (TemplateParamLists.size()) { 5699 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5700 return nullptr; 5701 } 5702 5703 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5704 } else if (R->isFunctionType()) { 5705 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5706 TemplateParamLists, 5707 AddToScope); 5708 } else { 5709 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5710 AddToScope); 5711 } 5712 5713 if (!New) 5714 return nullptr; 5715 5716 // If this has an identifier and is not a function template specialization, 5717 // add it to the scope stack. 5718 if (New->getDeclName() && AddToScope) 5719 PushOnScopeChains(New, S); 5720 5721 if (isInOpenMPDeclareTargetContext()) 5722 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5723 5724 return New; 5725 } 5726 5727 /// Helper method to turn variable array types into constant array 5728 /// types in certain situations which would otherwise be errors (for 5729 /// GCC compatibility). 5730 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5731 ASTContext &Context, 5732 bool &SizeIsNegative, 5733 llvm::APSInt &Oversized) { 5734 // This method tries to turn a variable array into a constant 5735 // array even when the size isn't an ICE. This is necessary 5736 // for compatibility with code that depends on gcc's buggy 5737 // constant expression folding, like struct {char x[(int)(char*)2];} 5738 SizeIsNegative = false; 5739 Oversized = 0; 5740 5741 if (T->isDependentType()) 5742 return QualType(); 5743 5744 QualifierCollector Qs; 5745 const Type *Ty = Qs.strip(T); 5746 5747 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5748 QualType Pointee = PTy->getPointeeType(); 5749 QualType FixedType = 5750 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5751 Oversized); 5752 if (FixedType.isNull()) return FixedType; 5753 FixedType = Context.getPointerType(FixedType); 5754 return Qs.apply(Context, FixedType); 5755 } 5756 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5757 QualType Inner = PTy->getInnerType(); 5758 QualType FixedType = 5759 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5760 Oversized); 5761 if (FixedType.isNull()) return FixedType; 5762 FixedType = Context.getParenType(FixedType); 5763 return Qs.apply(Context, FixedType); 5764 } 5765 5766 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5767 if (!VLATy) 5768 return QualType(); 5769 // FIXME: We should probably handle this case 5770 if (VLATy->getElementType()->isVariablyModifiedType()) 5771 return QualType(); 5772 5773 Expr::EvalResult Result; 5774 if (!VLATy->getSizeExpr() || 5775 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5776 return QualType(); 5777 5778 llvm::APSInt Res = Result.Val.getInt(); 5779 5780 // Check whether the array size is negative. 5781 if (Res.isSigned() && Res.isNegative()) { 5782 SizeIsNegative = true; 5783 return QualType(); 5784 } 5785 5786 // Check whether the array is too large to be addressed. 5787 unsigned ActiveSizeBits 5788 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5789 Res); 5790 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5791 Oversized = Res; 5792 return QualType(); 5793 } 5794 5795 return Context.getConstantArrayType( 5796 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5797 } 5798 5799 static void 5800 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5801 SrcTL = SrcTL.getUnqualifiedLoc(); 5802 DstTL = DstTL.getUnqualifiedLoc(); 5803 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5804 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5805 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5806 DstPTL.getPointeeLoc()); 5807 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5808 return; 5809 } 5810 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5811 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5812 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5813 DstPTL.getInnerLoc()); 5814 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5815 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5816 return; 5817 } 5818 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5819 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5820 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5821 TypeLoc DstElemTL = DstATL.getElementLoc(); 5822 DstElemTL.initializeFullCopy(SrcElemTL); 5823 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5824 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5825 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5826 } 5827 5828 /// Helper method to turn variable array types into constant array 5829 /// types in certain situations which would otherwise be errors (for 5830 /// GCC compatibility). 5831 static TypeSourceInfo* 5832 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5833 ASTContext &Context, 5834 bool &SizeIsNegative, 5835 llvm::APSInt &Oversized) { 5836 QualType FixedTy 5837 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5838 SizeIsNegative, Oversized); 5839 if (FixedTy.isNull()) 5840 return nullptr; 5841 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5842 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5843 FixedTInfo->getTypeLoc()); 5844 return FixedTInfo; 5845 } 5846 5847 /// Register the given locally-scoped extern "C" declaration so 5848 /// that it can be found later for redeclarations. We include any extern "C" 5849 /// declaration that is not visible in the translation unit here, not just 5850 /// function-scope declarations. 5851 void 5852 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5853 if (!getLangOpts().CPlusPlus && 5854 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5855 // Don't need to track declarations in the TU in C. 5856 return; 5857 5858 // Note that we have a locally-scoped external with this name. 5859 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5860 } 5861 5862 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5863 // FIXME: We can have multiple results via __attribute__((overloadable)). 5864 auto Result = Context.getExternCContextDecl()->lookup(Name); 5865 return Result.empty() ? nullptr : *Result.begin(); 5866 } 5867 5868 /// Diagnose function specifiers on a declaration of an identifier that 5869 /// does not identify a function. 5870 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5871 // FIXME: We should probably indicate the identifier in question to avoid 5872 // confusion for constructs like "virtual int a(), b;" 5873 if (DS.isVirtualSpecified()) 5874 Diag(DS.getVirtualSpecLoc(), 5875 diag::err_virtual_non_function); 5876 5877 if (DS.hasExplicitSpecifier()) 5878 Diag(DS.getExplicitSpecLoc(), 5879 diag::err_explicit_non_function); 5880 5881 if (DS.isNoreturnSpecified()) 5882 Diag(DS.getNoreturnSpecLoc(), 5883 diag::err_noreturn_non_function); 5884 } 5885 5886 NamedDecl* 5887 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5888 TypeSourceInfo *TInfo, LookupResult &Previous) { 5889 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5890 if (D.getCXXScopeSpec().isSet()) { 5891 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5892 << D.getCXXScopeSpec().getRange(); 5893 D.setInvalidType(); 5894 // Pretend we didn't see the scope specifier. 5895 DC = CurContext; 5896 Previous.clear(); 5897 } 5898 5899 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5900 5901 if (D.getDeclSpec().isInlineSpecified()) 5902 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5903 << getLangOpts().CPlusPlus17; 5904 if (D.getDeclSpec().hasConstexprSpecifier()) 5905 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5906 << 1 << D.getDeclSpec().getConstexprSpecifier(); 5907 5908 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5909 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5910 Diag(D.getName().StartLocation, 5911 diag::err_deduction_guide_invalid_specifier) 5912 << "typedef"; 5913 else 5914 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5915 << D.getName().getSourceRange(); 5916 return nullptr; 5917 } 5918 5919 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5920 if (!NewTD) return nullptr; 5921 5922 // Handle attributes prior to checking for duplicates in MergeVarDecl 5923 ProcessDeclAttributes(S, NewTD, D); 5924 5925 CheckTypedefForVariablyModifiedType(S, NewTD); 5926 5927 bool Redeclaration = D.isRedeclaration(); 5928 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5929 D.setRedeclaration(Redeclaration); 5930 return ND; 5931 } 5932 5933 void 5934 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5935 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5936 // then it shall have block scope. 5937 // Note that variably modified types must be fixed before merging the decl so 5938 // that redeclarations will match. 5939 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5940 QualType T = TInfo->getType(); 5941 if (T->isVariablyModifiedType()) { 5942 setFunctionHasBranchProtectedScope(); 5943 5944 if (S->getFnParent() == nullptr) { 5945 bool SizeIsNegative; 5946 llvm::APSInt Oversized; 5947 TypeSourceInfo *FixedTInfo = 5948 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5949 SizeIsNegative, 5950 Oversized); 5951 if (FixedTInfo) { 5952 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5953 NewTD->setTypeSourceInfo(FixedTInfo); 5954 } else { 5955 if (SizeIsNegative) 5956 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5957 else if (T->isVariableArrayType()) 5958 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5959 else if (Oversized.getBoolValue()) 5960 Diag(NewTD->getLocation(), diag::err_array_too_large) 5961 << Oversized.toString(10); 5962 else 5963 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5964 NewTD->setInvalidDecl(); 5965 } 5966 } 5967 } 5968 } 5969 5970 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5971 /// declares a typedef-name, either using the 'typedef' type specifier or via 5972 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5973 NamedDecl* 5974 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5975 LookupResult &Previous, bool &Redeclaration) { 5976 5977 // Find the shadowed declaration before filtering for scope. 5978 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5979 5980 // Merge the decl with the existing one if appropriate. If the decl is 5981 // in an outer scope, it isn't the same thing. 5982 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5983 /*AllowInlineNamespace*/false); 5984 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5985 if (!Previous.empty()) { 5986 Redeclaration = true; 5987 MergeTypedefNameDecl(S, NewTD, Previous); 5988 } else { 5989 inferGslPointerAttribute(NewTD); 5990 } 5991 5992 if (ShadowedDecl && !Redeclaration) 5993 CheckShadow(NewTD, ShadowedDecl, Previous); 5994 5995 // If this is the C FILE type, notify the AST context. 5996 if (IdentifierInfo *II = NewTD->getIdentifier()) 5997 if (!NewTD->isInvalidDecl() && 5998 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5999 if (II->isStr("FILE")) 6000 Context.setFILEDecl(NewTD); 6001 else if (II->isStr("jmp_buf")) 6002 Context.setjmp_bufDecl(NewTD); 6003 else if (II->isStr("sigjmp_buf")) 6004 Context.setsigjmp_bufDecl(NewTD); 6005 else if (II->isStr("ucontext_t")) 6006 Context.setucontext_tDecl(NewTD); 6007 } 6008 6009 return NewTD; 6010 } 6011 6012 /// Determines whether the given declaration is an out-of-scope 6013 /// previous declaration. 6014 /// 6015 /// This routine should be invoked when name lookup has found a 6016 /// previous declaration (PrevDecl) that is not in the scope where a 6017 /// new declaration by the same name is being introduced. If the new 6018 /// declaration occurs in a local scope, previous declarations with 6019 /// linkage may still be considered previous declarations (C99 6020 /// 6.2.2p4-5, C++ [basic.link]p6). 6021 /// 6022 /// \param PrevDecl the previous declaration found by name 6023 /// lookup 6024 /// 6025 /// \param DC the context in which the new declaration is being 6026 /// declared. 6027 /// 6028 /// \returns true if PrevDecl is an out-of-scope previous declaration 6029 /// for a new delcaration with the same name. 6030 static bool 6031 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6032 ASTContext &Context) { 6033 if (!PrevDecl) 6034 return false; 6035 6036 if (!PrevDecl->hasLinkage()) 6037 return false; 6038 6039 if (Context.getLangOpts().CPlusPlus) { 6040 // C++ [basic.link]p6: 6041 // If there is a visible declaration of an entity with linkage 6042 // having the same name and type, ignoring entities declared 6043 // outside the innermost enclosing namespace scope, the block 6044 // scope declaration declares that same entity and receives the 6045 // linkage of the previous declaration. 6046 DeclContext *OuterContext = DC->getRedeclContext(); 6047 if (!OuterContext->isFunctionOrMethod()) 6048 // This rule only applies to block-scope declarations. 6049 return false; 6050 6051 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6052 if (PrevOuterContext->isRecord()) 6053 // We found a member function: ignore it. 6054 return false; 6055 6056 // Find the innermost enclosing namespace for the new and 6057 // previous declarations. 6058 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6059 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6060 6061 // The previous declaration is in a different namespace, so it 6062 // isn't the same function. 6063 if (!OuterContext->Equals(PrevOuterContext)) 6064 return false; 6065 } 6066 6067 return true; 6068 } 6069 6070 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6071 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6072 if (!SS.isSet()) return; 6073 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6074 } 6075 6076 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6077 QualType type = decl->getType(); 6078 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6079 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6080 // Various kinds of declaration aren't allowed to be __autoreleasing. 6081 unsigned kind = -1U; 6082 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6083 if (var->hasAttr<BlocksAttr>()) 6084 kind = 0; // __block 6085 else if (!var->hasLocalStorage()) 6086 kind = 1; // global 6087 } else if (isa<ObjCIvarDecl>(decl)) { 6088 kind = 3; // ivar 6089 } else if (isa<FieldDecl>(decl)) { 6090 kind = 2; // field 6091 } 6092 6093 if (kind != -1U) { 6094 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6095 << kind; 6096 } 6097 } else if (lifetime == Qualifiers::OCL_None) { 6098 // Try to infer lifetime. 6099 if (!type->isObjCLifetimeType()) 6100 return false; 6101 6102 lifetime = type->getObjCARCImplicitLifetime(); 6103 type = Context.getLifetimeQualifiedType(type, lifetime); 6104 decl->setType(type); 6105 } 6106 6107 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6108 // Thread-local variables cannot have lifetime. 6109 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6110 var->getTLSKind()) { 6111 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6112 << var->getType(); 6113 return true; 6114 } 6115 } 6116 6117 return false; 6118 } 6119 6120 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6121 // Ensure that an auto decl is deduced otherwise the checks below might cache 6122 // the wrong linkage. 6123 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6124 6125 // 'weak' only applies to declarations with external linkage. 6126 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6127 if (!ND.isExternallyVisible()) { 6128 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6129 ND.dropAttr<WeakAttr>(); 6130 } 6131 } 6132 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6133 if (ND.isExternallyVisible()) { 6134 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6135 ND.dropAttr<WeakRefAttr>(); 6136 ND.dropAttr<AliasAttr>(); 6137 } 6138 } 6139 6140 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6141 if (VD->hasInit()) { 6142 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6143 assert(VD->isThisDeclarationADefinition() && 6144 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6145 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6146 VD->dropAttr<AliasAttr>(); 6147 } 6148 } 6149 } 6150 6151 // 'selectany' only applies to externally visible variable declarations. 6152 // It does not apply to functions. 6153 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6154 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6155 S.Diag(Attr->getLocation(), 6156 diag::err_attribute_selectany_non_extern_data); 6157 ND.dropAttr<SelectAnyAttr>(); 6158 } 6159 } 6160 6161 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6162 auto *VD = dyn_cast<VarDecl>(&ND); 6163 bool IsAnonymousNS = false; 6164 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6165 if (VD) { 6166 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6167 while (NS && !IsAnonymousNS) { 6168 IsAnonymousNS = NS->isAnonymousNamespace(); 6169 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6170 } 6171 } 6172 // dll attributes require external linkage. Static locals may have external 6173 // linkage but still cannot be explicitly imported or exported. 6174 // In Microsoft mode, a variable defined in anonymous namespace must have 6175 // external linkage in order to be exported. 6176 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6177 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6178 (!AnonNSInMicrosoftMode && 6179 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6180 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6181 << &ND << Attr; 6182 ND.setInvalidDecl(); 6183 } 6184 } 6185 6186 // Virtual functions cannot be marked as 'notail'. 6187 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6188 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6189 if (MD->isVirtual()) { 6190 S.Diag(ND.getLocation(), 6191 diag::err_invalid_attribute_on_virtual_function) 6192 << Attr; 6193 ND.dropAttr<NotTailCalledAttr>(); 6194 } 6195 6196 // Check the attributes on the function type, if any. 6197 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6198 // Don't declare this variable in the second operand of the for-statement; 6199 // GCC miscompiles that by ending its lifetime before evaluating the 6200 // third operand. See gcc.gnu.org/PR86769. 6201 AttributedTypeLoc ATL; 6202 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6203 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6204 TL = ATL.getModifiedLoc()) { 6205 // The [[lifetimebound]] attribute can be applied to the implicit object 6206 // parameter of a non-static member function (other than a ctor or dtor) 6207 // by applying it to the function type. 6208 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6209 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6210 if (!MD || MD->isStatic()) { 6211 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6212 << !MD << A->getRange(); 6213 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6214 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6215 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6216 } 6217 } 6218 } 6219 } 6220 } 6221 6222 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6223 NamedDecl *NewDecl, 6224 bool IsSpecialization, 6225 bool IsDefinition) { 6226 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6227 return; 6228 6229 bool IsTemplate = false; 6230 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6231 OldDecl = OldTD->getTemplatedDecl(); 6232 IsTemplate = true; 6233 if (!IsSpecialization) 6234 IsDefinition = false; 6235 } 6236 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6237 NewDecl = NewTD->getTemplatedDecl(); 6238 IsTemplate = true; 6239 } 6240 6241 if (!OldDecl || !NewDecl) 6242 return; 6243 6244 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6245 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6246 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6247 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6248 6249 // dllimport and dllexport are inheritable attributes so we have to exclude 6250 // inherited attribute instances. 6251 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6252 (NewExportAttr && !NewExportAttr->isInherited()); 6253 6254 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6255 // the only exception being explicit specializations. 6256 // Implicitly generated declarations are also excluded for now because there 6257 // is no other way to switch these to use dllimport or dllexport. 6258 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6259 6260 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6261 // Allow with a warning for free functions and global variables. 6262 bool JustWarn = false; 6263 if (!OldDecl->isCXXClassMember()) { 6264 auto *VD = dyn_cast<VarDecl>(OldDecl); 6265 if (VD && !VD->getDescribedVarTemplate()) 6266 JustWarn = true; 6267 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6268 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6269 JustWarn = true; 6270 } 6271 6272 // We cannot change a declaration that's been used because IR has already 6273 // been emitted. Dllimported functions will still work though (modulo 6274 // address equality) as they can use the thunk. 6275 if (OldDecl->isUsed()) 6276 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6277 JustWarn = false; 6278 6279 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6280 : diag::err_attribute_dll_redeclaration; 6281 S.Diag(NewDecl->getLocation(), DiagID) 6282 << NewDecl 6283 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6284 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6285 if (!JustWarn) { 6286 NewDecl->setInvalidDecl(); 6287 return; 6288 } 6289 } 6290 6291 // A redeclaration is not allowed to drop a dllimport attribute, the only 6292 // exceptions being inline function definitions (except for function 6293 // templates), local extern declarations, qualified friend declarations or 6294 // special MSVC extension: in the last case, the declaration is treated as if 6295 // it were marked dllexport. 6296 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6297 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6298 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6299 // Ignore static data because out-of-line definitions are diagnosed 6300 // separately. 6301 IsStaticDataMember = VD->isStaticDataMember(); 6302 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6303 VarDecl::DeclarationOnly; 6304 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6305 IsInline = FD->isInlined(); 6306 IsQualifiedFriend = FD->getQualifier() && 6307 FD->getFriendObjectKind() == Decl::FOK_Declared; 6308 } 6309 6310 if (OldImportAttr && !HasNewAttr && 6311 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6312 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6313 if (IsMicrosoft && IsDefinition) { 6314 S.Diag(NewDecl->getLocation(), 6315 diag::warn_redeclaration_without_import_attribute) 6316 << NewDecl; 6317 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6318 NewDecl->dropAttr<DLLImportAttr>(); 6319 NewDecl->addAttr( 6320 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6321 } else { 6322 S.Diag(NewDecl->getLocation(), 6323 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6324 << NewDecl << OldImportAttr; 6325 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6326 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6327 OldDecl->dropAttr<DLLImportAttr>(); 6328 NewDecl->dropAttr<DLLImportAttr>(); 6329 } 6330 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6331 // In MinGW, seeing a function declared inline drops the dllimport 6332 // attribute. 6333 OldDecl->dropAttr<DLLImportAttr>(); 6334 NewDecl->dropAttr<DLLImportAttr>(); 6335 S.Diag(NewDecl->getLocation(), 6336 diag::warn_dllimport_dropped_from_inline_function) 6337 << NewDecl << OldImportAttr; 6338 } 6339 6340 // A specialization of a class template member function is processed here 6341 // since it's a redeclaration. If the parent class is dllexport, the 6342 // specialization inherits that attribute. This doesn't happen automatically 6343 // since the parent class isn't instantiated until later. 6344 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6345 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6346 !NewImportAttr && !NewExportAttr) { 6347 if (const DLLExportAttr *ParentExportAttr = 6348 MD->getParent()->getAttr<DLLExportAttr>()) { 6349 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6350 NewAttr->setInherited(true); 6351 NewDecl->addAttr(NewAttr); 6352 } 6353 } 6354 } 6355 } 6356 6357 /// Given that we are within the definition of the given function, 6358 /// will that definition behave like C99's 'inline', where the 6359 /// definition is discarded except for optimization purposes? 6360 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6361 // Try to avoid calling GetGVALinkageForFunction. 6362 6363 // All cases of this require the 'inline' keyword. 6364 if (!FD->isInlined()) return false; 6365 6366 // This is only possible in C++ with the gnu_inline attribute. 6367 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6368 return false; 6369 6370 // Okay, go ahead and call the relatively-more-expensive function. 6371 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6372 } 6373 6374 /// Determine whether a variable is extern "C" prior to attaching 6375 /// an initializer. We can't just call isExternC() here, because that 6376 /// will also compute and cache whether the declaration is externally 6377 /// visible, which might change when we attach the initializer. 6378 /// 6379 /// This can only be used if the declaration is known to not be a 6380 /// redeclaration of an internal linkage declaration. 6381 /// 6382 /// For instance: 6383 /// 6384 /// auto x = []{}; 6385 /// 6386 /// Attaching the initializer here makes this declaration not externally 6387 /// visible, because its type has internal linkage. 6388 /// 6389 /// FIXME: This is a hack. 6390 template<typename T> 6391 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6392 if (S.getLangOpts().CPlusPlus) { 6393 // In C++, the overloadable attribute negates the effects of extern "C". 6394 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6395 return false; 6396 6397 // So do CUDA's host/device attributes. 6398 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6399 D->template hasAttr<CUDAHostAttr>())) 6400 return false; 6401 } 6402 return D->isExternC(); 6403 } 6404 6405 static bool shouldConsiderLinkage(const VarDecl *VD) { 6406 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6407 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6408 isa<OMPDeclareMapperDecl>(DC)) 6409 return VD->hasExternalStorage(); 6410 if (DC->isFileContext()) 6411 return true; 6412 if (DC->isRecord()) 6413 return false; 6414 llvm_unreachable("Unexpected context"); 6415 } 6416 6417 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6418 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6419 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6420 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6421 return true; 6422 if (DC->isRecord()) 6423 return false; 6424 llvm_unreachable("Unexpected context"); 6425 } 6426 6427 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6428 ParsedAttr::Kind Kind) { 6429 // Check decl attributes on the DeclSpec. 6430 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6431 return true; 6432 6433 // Walk the declarator structure, checking decl attributes that were in a type 6434 // position to the decl itself. 6435 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6436 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6437 return true; 6438 } 6439 6440 // Finally, check attributes on the decl itself. 6441 return PD.getAttributes().hasAttribute(Kind); 6442 } 6443 6444 /// Adjust the \c DeclContext for a function or variable that might be a 6445 /// function-local external declaration. 6446 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6447 if (!DC->isFunctionOrMethod()) 6448 return false; 6449 6450 // If this is a local extern function or variable declared within a function 6451 // template, don't add it into the enclosing namespace scope until it is 6452 // instantiated; it might have a dependent type right now. 6453 if (DC->isDependentContext()) 6454 return true; 6455 6456 // C++11 [basic.link]p7: 6457 // When a block scope declaration of an entity with linkage is not found to 6458 // refer to some other declaration, then that entity is a member of the 6459 // innermost enclosing namespace. 6460 // 6461 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6462 // semantically-enclosing namespace, not a lexically-enclosing one. 6463 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6464 DC = DC->getParent(); 6465 return true; 6466 } 6467 6468 /// Returns true if given declaration has external C language linkage. 6469 static bool isDeclExternC(const Decl *D) { 6470 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6471 return FD->isExternC(); 6472 if (const auto *VD = dyn_cast<VarDecl>(D)) 6473 return VD->isExternC(); 6474 6475 llvm_unreachable("Unknown type of decl!"); 6476 } 6477 6478 NamedDecl *Sema::ActOnVariableDeclarator( 6479 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6480 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6481 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6482 QualType R = TInfo->getType(); 6483 DeclarationName Name = GetNameForDeclarator(D).getName(); 6484 6485 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6486 6487 if (D.isDecompositionDeclarator()) { 6488 // Take the name of the first declarator as our name for diagnostic 6489 // purposes. 6490 auto &Decomp = D.getDecompositionDeclarator(); 6491 if (!Decomp.bindings().empty()) { 6492 II = Decomp.bindings()[0].Name; 6493 Name = II; 6494 } 6495 } else if (!II) { 6496 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6497 return nullptr; 6498 } 6499 6500 if (getLangOpts().OpenCL) { 6501 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6502 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6503 // argument. 6504 if (R->isImageType() || R->isPipeType()) { 6505 Diag(D.getIdentifierLoc(), 6506 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6507 << R; 6508 D.setInvalidType(); 6509 return nullptr; 6510 } 6511 6512 // OpenCL v1.2 s6.9.r: 6513 // The event type cannot be used to declare a program scope variable. 6514 // OpenCL v2.0 s6.9.q: 6515 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6516 if (NULL == S->getParent()) { 6517 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6518 Diag(D.getIdentifierLoc(), 6519 diag::err_invalid_type_for_program_scope_var) << R; 6520 D.setInvalidType(); 6521 return nullptr; 6522 } 6523 } 6524 6525 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6526 QualType NR = R; 6527 while (NR->isPointerType()) { 6528 if (NR->isFunctionPointerType()) { 6529 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6530 D.setInvalidType(); 6531 break; 6532 } 6533 NR = NR->getPointeeType(); 6534 } 6535 6536 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6537 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6538 // half array type (unless the cl_khr_fp16 extension is enabled). 6539 if (Context.getBaseElementType(R)->isHalfType()) { 6540 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6541 D.setInvalidType(); 6542 } 6543 } 6544 6545 if (R->isSamplerT()) { 6546 // OpenCL v1.2 s6.9.b p4: 6547 // The sampler type cannot be used with the __local and __global address 6548 // space qualifiers. 6549 if (R.getAddressSpace() == LangAS::opencl_local || 6550 R.getAddressSpace() == LangAS::opencl_global) { 6551 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6552 } 6553 6554 // OpenCL v1.2 s6.12.14.1: 6555 // A global sampler must be declared with either the constant address 6556 // space qualifier or with the const qualifier. 6557 if (DC->isTranslationUnit() && 6558 !(R.getAddressSpace() == LangAS::opencl_constant || 6559 R.isConstQualified())) { 6560 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6561 D.setInvalidType(); 6562 } 6563 } 6564 6565 // OpenCL v1.2 s6.9.r: 6566 // The event type cannot be used with the __local, __constant and __global 6567 // address space qualifiers. 6568 if (R->isEventT()) { 6569 if (R.getAddressSpace() != LangAS::opencl_private) { 6570 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6571 D.setInvalidType(); 6572 } 6573 } 6574 6575 // C++ for OpenCL does not allow the thread_local storage qualifier. 6576 // OpenCL C does not support thread_local either, and 6577 // also reject all other thread storage class specifiers. 6578 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6579 if (TSC != TSCS_unspecified) { 6580 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6581 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6582 diag::err_opencl_unknown_type_specifier) 6583 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6584 << DeclSpec::getSpecifierName(TSC) << 1; 6585 D.setInvalidType(); 6586 return nullptr; 6587 } 6588 } 6589 6590 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6591 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6592 6593 // dllimport globals without explicit storage class are treated as extern. We 6594 // have to change the storage class this early to get the right DeclContext. 6595 if (SC == SC_None && !DC->isRecord() && 6596 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6597 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6598 SC = SC_Extern; 6599 6600 DeclContext *OriginalDC = DC; 6601 bool IsLocalExternDecl = SC == SC_Extern && 6602 adjustContextForLocalExternDecl(DC); 6603 6604 if (SCSpec == DeclSpec::SCS_mutable) { 6605 // mutable can only appear on non-static class members, so it's always 6606 // an error here 6607 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6608 D.setInvalidType(); 6609 SC = SC_None; 6610 } 6611 6612 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6613 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6614 D.getDeclSpec().getStorageClassSpecLoc())) { 6615 // In C++11, the 'register' storage class specifier is deprecated. 6616 // Suppress the warning in system macros, it's used in macros in some 6617 // popular C system headers, such as in glibc's htonl() macro. 6618 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6619 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6620 : diag::warn_deprecated_register) 6621 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6622 } 6623 6624 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6625 6626 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6627 // C99 6.9p2: The storage-class specifiers auto and register shall not 6628 // appear in the declaration specifiers in an external declaration. 6629 // Global Register+Asm is a GNU extension we support. 6630 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6631 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6632 D.setInvalidType(); 6633 } 6634 } 6635 6636 bool IsMemberSpecialization = false; 6637 bool IsVariableTemplateSpecialization = false; 6638 bool IsPartialSpecialization = false; 6639 bool IsVariableTemplate = false; 6640 VarDecl *NewVD = nullptr; 6641 VarTemplateDecl *NewTemplate = nullptr; 6642 TemplateParameterList *TemplateParams = nullptr; 6643 if (!getLangOpts().CPlusPlus) { 6644 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6645 II, R, TInfo, SC); 6646 6647 if (R->getContainedDeducedType()) 6648 ParsingInitForAutoVars.insert(NewVD); 6649 6650 if (D.isInvalidType()) 6651 NewVD->setInvalidDecl(); 6652 6653 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6654 NewVD->hasLocalStorage()) 6655 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6656 NTCUC_AutoVar, NTCUK_Destruct); 6657 } else { 6658 bool Invalid = false; 6659 6660 if (DC->isRecord() && !CurContext->isRecord()) { 6661 // This is an out-of-line definition of a static data member. 6662 switch (SC) { 6663 case SC_None: 6664 break; 6665 case SC_Static: 6666 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6667 diag::err_static_out_of_line) 6668 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6669 break; 6670 case SC_Auto: 6671 case SC_Register: 6672 case SC_Extern: 6673 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6674 // to names of variables declared in a block or to function parameters. 6675 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6676 // of class members 6677 6678 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6679 diag::err_storage_class_for_static_member) 6680 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6681 break; 6682 case SC_PrivateExtern: 6683 llvm_unreachable("C storage class in c++!"); 6684 } 6685 } 6686 6687 if (SC == SC_Static && CurContext->isRecord()) { 6688 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6689 if (RD->isLocalClass()) 6690 Diag(D.getIdentifierLoc(), 6691 diag::err_static_data_member_not_allowed_in_local_class) 6692 << Name << RD->getDeclName(); 6693 6694 // C++98 [class.union]p1: If a union contains a static data member, 6695 // the program is ill-formed. C++11 drops this restriction. 6696 if (RD->isUnion()) 6697 Diag(D.getIdentifierLoc(), 6698 getLangOpts().CPlusPlus11 6699 ? diag::warn_cxx98_compat_static_data_member_in_union 6700 : diag::ext_static_data_member_in_union) << Name; 6701 // We conservatively disallow static data members in anonymous structs. 6702 else if (!RD->getDeclName()) 6703 Diag(D.getIdentifierLoc(), 6704 diag::err_static_data_member_not_allowed_in_anon_struct) 6705 << Name << RD->isUnion(); 6706 } 6707 } 6708 6709 // Match up the template parameter lists with the scope specifier, then 6710 // determine whether we have a template or a template specialization. 6711 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6712 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6713 D.getCXXScopeSpec(), 6714 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6715 ? D.getName().TemplateId 6716 : nullptr, 6717 TemplateParamLists, 6718 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6719 6720 if (TemplateParams) { 6721 if (!TemplateParams->size() && 6722 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6723 // There is an extraneous 'template<>' for this variable. Complain 6724 // about it, but allow the declaration of the variable. 6725 Diag(TemplateParams->getTemplateLoc(), 6726 diag::err_template_variable_noparams) 6727 << II 6728 << SourceRange(TemplateParams->getTemplateLoc(), 6729 TemplateParams->getRAngleLoc()); 6730 TemplateParams = nullptr; 6731 } else { 6732 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6733 // This is an explicit specialization or a partial specialization. 6734 // FIXME: Check that we can declare a specialization here. 6735 IsVariableTemplateSpecialization = true; 6736 IsPartialSpecialization = TemplateParams->size() > 0; 6737 } else { // if (TemplateParams->size() > 0) 6738 // This is a template declaration. 6739 IsVariableTemplate = true; 6740 6741 // Check that we can declare a template here. 6742 if (CheckTemplateDeclScope(S, TemplateParams)) 6743 return nullptr; 6744 6745 // Only C++1y supports variable templates (N3651). 6746 Diag(D.getIdentifierLoc(), 6747 getLangOpts().CPlusPlus14 6748 ? diag::warn_cxx11_compat_variable_template 6749 : diag::ext_variable_template); 6750 } 6751 } 6752 } else { 6753 assert((Invalid || 6754 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6755 "should have a 'template<>' for this decl"); 6756 } 6757 6758 if (IsVariableTemplateSpecialization) { 6759 SourceLocation TemplateKWLoc = 6760 TemplateParamLists.size() > 0 6761 ? TemplateParamLists[0]->getTemplateLoc() 6762 : SourceLocation(); 6763 DeclResult Res = ActOnVarTemplateSpecialization( 6764 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6765 IsPartialSpecialization); 6766 if (Res.isInvalid()) 6767 return nullptr; 6768 NewVD = cast<VarDecl>(Res.get()); 6769 AddToScope = false; 6770 } else if (D.isDecompositionDeclarator()) { 6771 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6772 D.getIdentifierLoc(), R, TInfo, SC, 6773 Bindings); 6774 } else 6775 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6776 D.getIdentifierLoc(), II, R, TInfo, SC); 6777 6778 // If this is supposed to be a variable template, create it as such. 6779 if (IsVariableTemplate) { 6780 NewTemplate = 6781 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6782 TemplateParams, NewVD); 6783 NewVD->setDescribedVarTemplate(NewTemplate); 6784 } 6785 6786 // If this decl has an auto type in need of deduction, make a note of the 6787 // Decl so we can diagnose uses of it in its own initializer. 6788 if (R->getContainedDeducedType()) 6789 ParsingInitForAutoVars.insert(NewVD); 6790 6791 if (D.isInvalidType() || Invalid) { 6792 NewVD->setInvalidDecl(); 6793 if (NewTemplate) 6794 NewTemplate->setInvalidDecl(); 6795 } 6796 6797 SetNestedNameSpecifier(*this, NewVD, D); 6798 6799 // If we have any template parameter lists that don't directly belong to 6800 // the variable (matching the scope specifier), store them. 6801 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6802 if (TemplateParamLists.size() > VDTemplateParamLists) 6803 NewVD->setTemplateParameterListsInfo( 6804 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6805 } 6806 6807 if (D.getDeclSpec().isInlineSpecified()) { 6808 if (!getLangOpts().CPlusPlus) { 6809 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6810 << 0; 6811 } else if (CurContext->isFunctionOrMethod()) { 6812 // 'inline' is not allowed on block scope variable declaration. 6813 Diag(D.getDeclSpec().getInlineSpecLoc(), 6814 diag::err_inline_declaration_block_scope) << Name 6815 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6816 } else { 6817 Diag(D.getDeclSpec().getInlineSpecLoc(), 6818 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6819 : diag::ext_inline_variable); 6820 NewVD->setInlineSpecified(); 6821 } 6822 } 6823 6824 // Set the lexical context. If the declarator has a C++ scope specifier, the 6825 // lexical context will be different from the semantic context. 6826 NewVD->setLexicalDeclContext(CurContext); 6827 if (NewTemplate) 6828 NewTemplate->setLexicalDeclContext(CurContext); 6829 6830 if (IsLocalExternDecl) { 6831 if (D.isDecompositionDeclarator()) 6832 for (auto *B : Bindings) 6833 B->setLocalExternDecl(); 6834 else 6835 NewVD->setLocalExternDecl(); 6836 } 6837 6838 bool EmitTLSUnsupportedError = false; 6839 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6840 // C++11 [dcl.stc]p4: 6841 // When thread_local is applied to a variable of block scope the 6842 // storage-class-specifier static is implied if it does not appear 6843 // explicitly. 6844 // Core issue: 'static' is not implied if the variable is declared 6845 // 'extern'. 6846 if (NewVD->hasLocalStorage() && 6847 (SCSpec != DeclSpec::SCS_unspecified || 6848 TSCS != DeclSpec::TSCS_thread_local || 6849 !DC->isFunctionOrMethod())) 6850 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6851 diag::err_thread_non_global) 6852 << DeclSpec::getSpecifierName(TSCS); 6853 else if (!Context.getTargetInfo().isTLSSupported()) { 6854 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6855 // Postpone error emission until we've collected attributes required to 6856 // figure out whether it's a host or device variable and whether the 6857 // error should be ignored. 6858 EmitTLSUnsupportedError = true; 6859 // We still need to mark the variable as TLS so it shows up in AST with 6860 // proper storage class for other tools to use even if we're not going 6861 // to emit any code for it. 6862 NewVD->setTSCSpec(TSCS); 6863 } else 6864 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6865 diag::err_thread_unsupported); 6866 } else 6867 NewVD->setTSCSpec(TSCS); 6868 } 6869 6870 switch (D.getDeclSpec().getConstexprSpecifier()) { 6871 case CSK_unspecified: 6872 break; 6873 6874 case CSK_consteval: 6875 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6876 diag::err_constexpr_wrong_decl_kind) 6877 << D.getDeclSpec().getConstexprSpecifier(); 6878 LLVM_FALLTHROUGH; 6879 6880 case CSK_constexpr: 6881 NewVD->setConstexpr(true); 6882 // C++1z [dcl.spec.constexpr]p1: 6883 // A static data member declared with the constexpr specifier is 6884 // implicitly an inline variable. 6885 if (NewVD->isStaticDataMember() && 6886 (getLangOpts().CPlusPlus17 || 6887 Context.getTargetInfo().getCXXABI().isMicrosoft())) 6888 NewVD->setImplicitlyInline(); 6889 break; 6890 6891 case CSK_constinit: 6892 if (!NewVD->hasGlobalStorage()) 6893 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6894 diag::err_constinit_local_variable); 6895 else 6896 NewVD->addAttr(ConstInitAttr::Create( 6897 Context, D.getDeclSpec().getConstexprSpecLoc(), 6898 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 6899 break; 6900 } 6901 6902 // C99 6.7.4p3 6903 // An inline definition of a function with external linkage shall 6904 // not contain a definition of a modifiable object with static or 6905 // thread storage duration... 6906 // We only apply this when the function is required to be defined 6907 // elsewhere, i.e. when the function is not 'extern inline'. Note 6908 // that a local variable with thread storage duration still has to 6909 // be marked 'static'. Also note that it's possible to get these 6910 // semantics in C++ using __attribute__((gnu_inline)). 6911 if (SC == SC_Static && S->getFnParent() != nullptr && 6912 !NewVD->getType().isConstQualified()) { 6913 FunctionDecl *CurFD = getCurFunctionDecl(); 6914 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6915 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6916 diag::warn_static_local_in_extern_inline); 6917 MaybeSuggestAddingStaticToDecl(CurFD); 6918 } 6919 } 6920 6921 if (D.getDeclSpec().isModulePrivateSpecified()) { 6922 if (IsVariableTemplateSpecialization) 6923 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6924 << (IsPartialSpecialization ? 1 : 0) 6925 << FixItHint::CreateRemoval( 6926 D.getDeclSpec().getModulePrivateSpecLoc()); 6927 else if (IsMemberSpecialization) 6928 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6929 << 2 6930 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6931 else if (NewVD->hasLocalStorage()) 6932 Diag(NewVD->getLocation(), diag::err_module_private_local) 6933 << 0 << NewVD->getDeclName() 6934 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6935 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6936 else { 6937 NewVD->setModulePrivate(); 6938 if (NewTemplate) 6939 NewTemplate->setModulePrivate(); 6940 for (auto *B : Bindings) 6941 B->setModulePrivate(); 6942 } 6943 } 6944 6945 // Handle attributes prior to checking for duplicates in MergeVarDecl 6946 ProcessDeclAttributes(S, NewVD, D); 6947 6948 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6949 if (EmitTLSUnsupportedError && 6950 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6951 (getLangOpts().OpenMPIsDevice && 6952 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 6953 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6954 diag::err_thread_unsupported); 6955 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6956 // storage [duration]." 6957 if (SC == SC_None && S->getFnParent() != nullptr && 6958 (NewVD->hasAttr<CUDASharedAttr>() || 6959 NewVD->hasAttr<CUDAConstantAttr>())) { 6960 NewVD->setStorageClass(SC_Static); 6961 } 6962 } 6963 6964 // Ensure that dllimport globals without explicit storage class are treated as 6965 // extern. The storage class is set above using parsed attributes. Now we can 6966 // check the VarDecl itself. 6967 assert(!NewVD->hasAttr<DLLImportAttr>() || 6968 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6969 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6970 6971 // In auto-retain/release, infer strong retension for variables of 6972 // retainable type. 6973 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6974 NewVD->setInvalidDecl(); 6975 6976 // Handle GNU asm-label extension (encoded as an attribute). 6977 if (Expr *E = (Expr*)D.getAsmLabel()) { 6978 // The parser guarantees this is a string. 6979 StringLiteral *SE = cast<StringLiteral>(E); 6980 StringRef Label = SE->getString(); 6981 if (S->getFnParent() != nullptr) { 6982 switch (SC) { 6983 case SC_None: 6984 case SC_Auto: 6985 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6986 break; 6987 case SC_Register: 6988 // Local Named register 6989 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6990 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6991 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6992 break; 6993 case SC_Static: 6994 case SC_Extern: 6995 case SC_PrivateExtern: 6996 break; 6997 } 6998 } else if (SC == SC_Register) { 6999 // Global Named register 7000 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7001 const auto &TI = Context.getTargetInfo(); 7002 bool HasSizeMismatch; 7003 7004 if (!TI.isValidGCCRegisterName(Label)) 7005 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7006 else if (!TI.validateGlobalRegisterVariable(Label, 7007 Context.getTypeSize(R), 7008 HasSizeMismatch)) 7009 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7010 else if (HasSizeMismatch) 7011 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7012 } 7013 7014 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7015 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7016 NewVD->setInvalidDecl(true); 7017 } 7018 } 7019 7020 NewVD->addAttr(::new (Context) AsmLabelAttr( 7021 Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true)); 7022 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7023 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7024 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7025 if (I != ExtnameUndeclaredIdentifiers.end()) { 7026 if (isDeclExternC(NewVD)) { 7027 NewVD->addAttr(I->second); 7028 ExtnameUndeclaredIdentifiers.erase(I); 7029 } else 7030 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7031 << /*Variable*/1 << NewVD; 7032 } 7033 } 7034 7035 // Find the shadowed declaration before filtering for scope. 7036 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7037 ? getShadowedDeclaration(NewVD, Previous) 7038 : nullptr; 7039 7040 // Don't consider existing declarations that are in a different 7041 // scope and are out-of-semantic-context declarations (if the new 7042 // declaration has linkage). 7043 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7044 D.getCXXScopeSpec().isNotEmpty() || 7045 IsMemberSpecialization || 7046 IsVariableTemplateSpecialization); 7047 7048 // Check whether the previous declaration is in the same block scope. This 7049 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7050 if (getLangOpts().CPlusPlus && 7051 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7052 NewVD->setPreviousDeclInSameBlockScope( 7053 Previous.isSingleResult() && !Previous.isShadowed() && 7054 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7055 7056 if (!getLangOpts().CPlusPlus) { 7057 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7058 } else { 7059 // If this is an explicit specialization of a static data member, check it. 7060 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7061 CheckMemberSpecialization(NewVD, Previous)) 7062 NewVD->setInvalidDecl(); 7063 7064 // Merge the decl with the existing one if appropriate. 7065 if (!Previous.empty()) { 7066 if (Previous.isSingleResult() && 7067 isa<FieldDecl>(Previous.getFoundDecl()) && 7068 D.getCXXScopeSpec().isSet()) { 7069 // The user tried to define a non-static data member 7070 // out-of-line (C++ [dcl.meaning]p1). 7071 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7072 << D.getCXXScopeSpec().getRange(); 7073 Previous.clear(); 7074 NewVD->setInvalidDecl(); 7075 } 7076 } else if (D.getCXXScopeSpec().isSet()) { 7077 // No previous declaration in the qualifying scope. 7078 Diag(D.getIdentifierLoc(), diag::err_no_member) 7079 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7080 << D.getCXXScopeSpec().getRange(); 7081 NewVD->setInvalidDecl(); 7082 } 7083 7084 if (!IsVariableTemplateSpecialization) 7085 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7086 7087 if (NewTemplate) { 7088 VarTemplateDecl *PrevVarTemplate = 7089 NewVD->getPreviousDecl() 7090 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7091 : nullptr; 7092 7093 // Check the template parameter list of this declaration, possibly 7094 // merging in the template parameter list from the previous variable 7095 // template declaration. 7096 if (CheckTemplateParameterList( 7097 TemplateParams, 7098 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7099 : nullptr, 7100 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7101 DC->isDependentContext()) 7102 ? TPC_ClassTemplateMember 7103 : TPC_VarTemplate)) 7104 NewVD->setInvalidDecl(); 7105 7106 // If we are providing an explicit specialization of a static variable 7107 // template, make a note of that. 7108 if (PrevVarTemplate && 7109 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7110 PrevVarTemplate->setMemberSpecialization(); 7111 } 7112 } 7113 7114 // Diagnose shadowed variables iff this isn't a redeclaration. 7115 if (ShadowedDecl && !D.isRedeclaration()) 7116 CheckShadow(NewVD, ShadowedDecl, Previous); 7117 7118 ProcessPragmaWeak(S, NewVD); 7119 7120 // If this is the first declaration of an extern C variable, update 7121 // the map of such variables. 7122 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7123 isIncompleteDeclExternC(*this, NewVD)) 7124 RegisterLocallyScopedExternCDecl(NewVD, S); 7125 7126 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7127 MangleNumberingContext *MCtx; 7128 Decl *ManglingContextDecl; 7129 std::tie(MCtx, ManglingContextDecl) = 7130 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7131 if (MCtx) { 7132 Context.setManglingNumber( 7133 NewVD, MCtx->getManglingNumber( 7134 NewVD, getMSManglingNumber(getLangOpts(), S))); 7135 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7136 } 7137 } 7138 7139 // Special handling of variable named 'main'. 7140 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7141 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7142 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7143 7144 // C++ [basic.start.main]p3 7145 // A program that declares a variable main at global scope is ill-formed. 7146 if (getLangOpts().CPlusPlus) 7147 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7148 7149 // In C, and external-linkage variable named main results in undefined 7150 // behavior. 7151 else if (NewVD->hasExternalFormalLinkage()) 7152 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7153 } 7154 7155 if (D.isRedeclaration() && !Previous.empty()) { 7156 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7157 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7158 D.isFunctionDefinition()); 7159 } 7160 7161 if (NewTemplate) { 7162 if (NewVD->isInvalidDecl()) 7163 NewTemplate->setInvalidDecl(); 7164 ActOnDocumentableDecl(NewTemplate); 7165 return NewTemplate; 7166 } 7167 7168 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7169 CompleteMemberSpecialization(NewVD, Previous); 7170 7171 return NewVD; 7172 } 7173 7174 /// Enum describing the %select options in diag::warn_decl_shadow. 7175 enum ShadowedDeclKind { 7176 SDK_Local, 7177 SDK_Global, 7178 SDK_StaticMember, 7179 SDK_Field, 7180 SDK_Typedef, 7181 SDK_Using 7182 }; 7183 7184 /// Determine what kind of declaration we're shadowing. 7185 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7186 const DeclContext *OldDC) { 7187 if (isa<TypeAliasDecl>(ShadowedDecl)) 7188 return SDK_Using; 7189 else if (isa<TypedefDecl>(ShadowedDecl)) 7190 return SDK_Typedef; 7191 else if (isa<RecordDecl>(OldDC)) 7192 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7193 7194 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7195 } 7196 7197 /// Return the location of the capture if the given lambda captures the given 7198 /// variable \p VD, or an invalid source location otherwise. 7199 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7200 const VarDecl *VD) { 7201 for (const Capture &Capture : LSI->Captures) { 7202 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7203 return Capture.getLocation(); 7204 } 7205 return SourceLocation(); 7206 } 7207 7208 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7209 const LookupResult &R) { 7210 // Only diagnose if we're shadowing an unambiguous field or variable. 7211 if (R.getResultKind() != LookupResult::Found) 7212 return false; 7213 7214 // Return false if warning is ignored. 7215 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7216 } 7217 7218 /// Return the declaration shadowed by the given variable \p D, or null 7219 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7220 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7221 const LookupResult &R) { 7222 if (!shouldWarnIfShadowedDecl(Diags, R)) 7223 return nullptr; 7224 7225 // Don't diagnose declarations at file scope. 7226 if (D->hasGlobalStorage()) 7227 return nullptr; 7228 7229 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7230 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7231 ? ShadowedDecl 7232 : nullptr; 7233 } 7234 7235 /// Return the declaration shadowed by the given typedef \p D, or null 7236 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7237 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7238 const LookupResult &R) { 7239 // Don't warn if typedef declaration is part of a class 7240 if (D->getDeclContext()->isRecord()) 7241 return nullptr; 7242 7243 if (!shouldWarnIfShadowedDecl(Diags, R)) 7244 return nullptr; 7245 7246 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7247 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7248 } 7249 7250 /// Diagnose variable or built-in function shadowing. Implements 7251 /// -Wshadow. 7252 /// 7253 /// This method is called whenever a VarDecl is added to a "useful" 7254 /// scope. 7255 /// 7256 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7257 /// \param R the lookup of the name 7258 /// 7259 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7260 const LookupResult &R) { 7261 DeclContext *NewDC = D->getDeclContext(); 7262 7263 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7264 // Fields are not shadowed by variables in C++ static methods. 7265 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7266 if (MD->isStatic()) 7267 return; 7268 7269 // Fields shadowed by constructor parameters are a special case. Usually 7270 // the constructor initializes the field with the parameter. 7271 if (isa<CXXConstructorDecl>(NewDC)) 7272 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7273 // Remember that this was shadowed so we can either warn about its 7274 // modification or its existence depending on warning settings. 7275 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7276 return; 7277 } 7278 } 7279 7280 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7281 if (shadowedVar->isExternC()) { 7282 // For shadowing external vars, make sure that we point to the global 7283 // declaration, not a locally scoped extern declaration. 7284 for (auto I : shadowedVar->redecls()) 7285 if (I->isFileVarDecl()) { 7286 ShadowedDecl = I; 7287 break; 7288 } 7289 } 7290 7291 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7292 7293 unsigned WarningDiag = diag::warn_decl_shadow; 7294 SourceLocation CaptureLoc; 7295 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7296 isa<CXXMethodDecl>(NewDC)) { 7297 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7298 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7299 if (RD->getLambdaCaptureDefault() == LCD_None) { 7300 // Try to avoid warnings for lambdas with an explicit capture list. 7301 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7302 // Warn only when the lambda captures the shadowed decl explicitly. 7303 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7304 if (CaptureLoc.isInvalid()) 7305 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7306 } else { 7307 // Remember that this was shadowed so we can avoid the warning if the 7308 // shadowed decl isn't captured and the warning settings allow it. 7309 cast<LambdaScopeInfo>(getCurFunction()) 7310 ->ShadowingDecls.push_back( 7311 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7312 return; 7313 } 7314 } 7315 7316 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7317 // A variable can't shadow a local variable in an enclosing scope, if 7318 // they are separated by a non-capturing declaration context. 7319 for (DeclContext *ParentDC = NewDC; 7320 ParentDC && !ParentDC->Equals(OldDC); 7321 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7322 // Only block literals, captured statements, and lambda expressions 7323 // can capture; other scopes don't. 7324 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7325 !isLambdaCallOperator(ParentDC)) { 7326 return; 7327 } 7328 } 7329 } 7330 } 7331 } 7332 7333 // Only warn about certain kinds of shadowing for class members. 7334 if (NewDC && NewDC->isRecord()) { 7335 // In particular, don't warn about shadowing non-class members. 7336 if (!OldDC->isRecord()) 7337 return; 7338 7339 // TODO: should we warn about static data members shadowing 7340 // static data members from base classes? 7341 7342 // TODO: don't diagnose for inaccessible shadowed members. 7343 // This is hard to do perfectly because we might friend the 7344 // shadowing context, but that's just a false negative. 7345 } 7346 7347 7348 DeclarationName Name = R.getLookupName(); 7349 7350 // Emit warning and note. 7351 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7352 return; 7353 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7354 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7355 if (!CaptureLoc.isInvalid()) 7356 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7357 << Name << /*explicitly*/ 1; 7358 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7359 } 7360 7361 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7362 /// when these variables are captured by the lambda. 7363 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7364 for (const auto &Shadow : LSI->ShadowingDecls) { 7365 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7366 // Try to avoid the warning when the shadowed decl isn't captured. 7367 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7368 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7369 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7370 ? diag::warn_decl_shadow_uncaptured_local 7371 : diag::warn_decl_shadow) 7372 << Shadow.VD->getDeclName() 7373 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7374 if (!CaptureLoc.isInvalid()) 7375 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7376 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7377 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7378 } 7379 } 7380 7381 /// Check -Wshadow without the advantage of a previous lookup. 7382 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7383 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7384 return; 7385 7386 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7387 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7388 LookupName(R, S); 7389 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7390 CheckShadow(D, ShadowedDecl, R); 7391 } 7392 7393 /// Check if 'E', which is an expression that is about to be modified, refers 7394 /// to a constructor parameter that shadows a field. 7395 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7396 // Quickly ignore expressions that can't be shadowing ctor parameters. 7397 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7398 return; 7399 E = E->IgnoreParenImpCasts(); 7400 auto *DRE = dyn_cast<DeclRefExpr>(E); 7401 if (!DRE) 7402 return; 7403 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7404 auto I = ShadowingDecls.find(D); 7405 if (I == ShadowingDecls.end()) 7406 return; 7407 const NamedDecl *ShadowedDecl = I->second; 7408 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7409 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7410 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7411 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7412 7413 // Avoid issuing multiple warnings about the same decl. 7414 ShadowingDecls.erase(I); 7415 } 7416 7417 /// Check for conflict between this global or extern "C" declaration and 7418 /// previous global or extern "C" declarations. This is only used in C++. 7419 template<typename T> 7420 static bool checkGlobalOrExternCConflict( 7421 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7422 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7423 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7424 7425 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7426 // The common case: this global doesn't conflict with any extern "C" 7427 // declaration. 7428 return false; 7429 } 7430 7431 if (Prev) { 7432 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7433 // Both the old and new declarations have C language linkage. This is a 7434 // redeclaration. 7435 Previous.clear(); 7436 Previous.addDecl(Prev); 7437 return true; 7438 } 7439 7440 // This is a global, non-extern "C" declaration, and there is a previous 7441 // non-global extern "C" declaration. Diagnose if this is a variable 7442 // declaration. 7443 if (!isa<VarDecl>(ND)) 7444 return false; 7445 } else { 7446 // The declaration is extern "C". Check for any declaration in the 7447 // translation unit which might conflict. 7448 if (IsGlobal) { 7449 // We have already performed the lookup into the translation unit. 7450 IsGlobal = false; 7451 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7452 I != E; ++I) { 7453 if (isa<VarDecl>(*I)) { 7454 Prev = *I; 7455 break; 7456 } 7457 } 7458 } else { 7459 DeclContext::lookup_result R = 7460 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7461 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7462 I != E; ++I) { 7463 if (isa<VarDecl>(*I)) { 7464 Prev = *I; 7465 break; 7466 } 7467 // FIXME: If we have any other entity with this name in global scope, 7468 // the declaration is ill-formed, but that is a defect: it breaks the 7469 // 'stat' hack, for instance. Only variables can have mangled name 7470 // clashes with extern "C" declarations, so only they deserve a 7471 // diagnostic. 7472 } 7473 } 7474 7475 if (!Prev) 7476 return false; 7477 } 7478 7479 // Use the first declaration's location to ensure we point at something which 7480 // is lexically inside an extern "C" linkage-spec. 7481 assert(Prev && "should have found a previous declaration to diagnose"); 7482 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7483 Prev = FD->getFirstDecl(); 7484 else 7485 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7486 7487 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7488 << IsGlobal << ND; 7489 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7490 << IsGlobal; 7491 return false; 7492 } 7493 7494 /// Apply special rules for handling extern "C" declarations. Returns \c true 7495 /// if we have found that this is a redeclaration of some prior entity. 7496 /// 7497 /// Per C++ [dcl.link]p6: 7498 /// Two declarations [for a function or variable] with C language linkage 7499 /// with the same name that appear in different scopes refer to the same 7500 /// [entity]. An entity with C language linkage shall not be declared with 7501 /// the same name as an entity in global scope. 7502 template<typename T> 7503 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7504 LookupResult &Previous) { 7505 if (!S.getLangOpts().CPlusPlus) { 7506 // In C, when declaring a global variable, look for a corresponding 'extern' 7507 // variable declared in function scope. We don't need this in C++, because 7508 // we find local extern decls in the surrounding file-scope DeclContext. 7509 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7510 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7511 Previous.clear(); 7512 Previous.addDecl(Prev); 7513 return true; 7514 } 7515 } 7516 return false; 7517 } 7518 7519 // A declaration in the translation unit can conflict with an extern "C" 7520 // declaration. 7521 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7522 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7523 7524 // An extern "C" declaration can conflict with a declaration in the 7525 // translation unit or can be a redeclaration of an extern "C" declaration 7526 // in another scope. 7527 if (isIncompleteDeclExternC(S,ND)) 7528 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7529 7530 // Neither global nor extern "C": nothing to do. 7531 return false; 7532 } 7533 7534 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7535 // If the decl is already known invalid, don't check it. 7536 if (NewVD->isInvalidDecl()) 7537 return; 7538 7539 QualType T = NewVD->getType(); 7540 7541 // Defer checking an 'auto' type until its initializer is attached. 7542 if (T->isUndeducedType()) 7543 return; 7544 7545 if (NewVD->hasAttrs()) 7546 CheckAlignasUnderalignment(NewVD); 7547 7548 if (T->isObjCObjectType()) { 7549 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7550 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7551 T = Context.getObjCObjectPointerType(T); 7552 NewVD->setType(T); 7553 } 7554 7555 // Emit an error if an address space was applied to decl with local storage. 7556 // This includes arrays of objects with address space qualifiers, but not 7557 // automatic variables that point to other address spaces. 7558 // ISO/IEC TR 18037 S5.1.2 7559 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7560 T.getAddressSpace() != LangAS::Default) { 7561 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7562 NewVD->setInvalidDecl(); 7563 return; 7564 } 7565 7566 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7567 // scope. 7568 if (getLangOpts().OpenCLVersion == 120 && 7569 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7570 NewVD->isStaticLocal()) { 7571 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7572 NewVD->setInvalidDecl(); 7573 return; 7574 } 7575 7576 if (getLangOpts().OpenCL) { 7577 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7578 if (NewVD->hasAttr<BlocksAttr>()) { 7579 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7580 return; 7581 } 7582 7583 if (T->isBlockPointerType()) { 7584 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7585 // can't use 'extern' storage class. 7586 if (!T.isConstQualified()) { 7587 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7588 << 0 /*const*/; 7589 NewVD->setInvalidDecl(); 7590 return; 7591 } 7592 if (NewVD->hasExternalStorage()) { 7593 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7594 NewVD->setInvalidDecl(); 7595 return; 7596 } 7597 } 7598 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7599 // __constant address space. 7600 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7601 // variables inside a function can also be declared in the global 7602 // address space. 7603 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7604 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7605 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7606 NewVD->hasExternalStorage()) { 7607 if (!T->isSamplerT() && 7608 !(T.getAddressSpace() == LangAS::opencl_constant || 7609 (T.getAddressSpace() == LangAS::opencl_global && 7610 (getLangOpts().OpenCLVersion == 200 || 7611 getLangOpts().OpenCLCPlusPlus)))) { 7612 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7613 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7614 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7615 << Scope << "global or constant"; 7616 else 7617 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7618 << Scope << "constant"; 7619 NewVD->setInvalidDecl(); 7620 return; 7621 } 7622 } else { 7623 if (T.getAddressSpace() == LangAS::opencl_global) { 7624 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7625 << 1 /*is any function*/ << "global"; 7626 NewVD->setInvalidDecl(); 7627 return; 7628 } 7629 if (T.getAddressSpace() == LangAS::opencl_constant || 7630 T.getAddressSpace() == LangAS::opencl_local) { 7631 FunctionDecl *FD = getCurFunctionDecl(); 7632 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7633 // in functions. 7634 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7635 if (T.getAddressSpace() == LangAS::opencl_constant) 7636 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7637 << 0 /*non-kernel only*/ << "constant"; 7638 else 7639 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7640 << 0 /*non-kernel only*/ << "local"; 7641 NewVD->setInvalidDecl(); 7642 return; 7643 } 7644 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7645 // in the outermost scope of a kernel function. 7646 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7647 if (!getCurScope()->isFunctionScope()) { 7648 if (T.getAddressSpace() == LangAS::opencl_constant) 7649 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7650 << "constant"; 7651 else 7652 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7653 << "local"; 7654 NewVD->setInvalidDecl(); 7655 return; 7656 } 7657 } 7658 } else if (T.getAddressSpace() != LangAS::opencl_private && 7659 // If we are parsing a template we didn't deduce an addr 7660 // space yet. 7661 T.getAddressSpace() != LangAS::Default) { 7662 // Do not allow other address spaces on automatic variable. 7663 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7664 NewVD->setInvalidDecl(); 7665 return; 7666 } 7667 } 7668 } 7669 7670 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7671 && !NewVD->hasAttr<BlocksAttr>()) { 7672 if (getLangOpts().getGC() != LangOptions::NonGC) 7673 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7674 else { 7675 assert(!getLangOpts().ObjCAutoRefCount); 7676 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7677 } 7678 } 7679 7680 bool isVM = T->isVariablyModifiedType(); 7681 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7682 NewVD->hasAttr<BlocksAttr>()) 7683 setFunctionHasBranchProtectedScope(); 7684 7685 if ((isVM && NewVD->hasLinkage()) || 7686 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7687 bool SizeIsNegative; 7688 llvm::APSInt Oversized; 7689 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7690 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7691 QualType FixedT; 7692 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7693 FixedT = FixedTInfo->getType(); 7694 else if (FixedTInfo) { 7695 // Type and type-as-written are canonically different. We need to fix up 7696 // both types separately. 7697 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7698 Oversized); 7699 } 7700 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7701 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7702 // FIXME: This won't give the correct result for 7703 // int a[10][n]; 7704 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7705 7706 if (NewVD->isFileVarDecl()) 7707 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7708 << SizeRange; 7709 else if (NewVD->isStaticLocal()) 7710 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7711 << SizeRange; 7712 else 7713 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7714 << SizeRange; 7715 NewVD->setInvalidDecl(); 7716 return; 7717 } 7718 7719 if (!FixedTInfo) { 7720 if (NewVD->isFileVarDecl()) 7721 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7722 else 7723 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7724 NewVD->setInvalidDecl(); 7725 return; 7726 } 7727 7728 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7729 NewVD->setType(FixedT); 7730 NewVD->setTypeSourceInfo(FixedTInfo); 7731 } 7732 7733 if (T->isVoidType()) { 7734 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7735 // of objects and functions. 7736 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7737 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7738 << T; 7739 NewVD->setInvalidDecl(); 7740 return; 7741 } 7742 } 7743 7744 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7745 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7746 NewVD->setInvalidDecl(); 7747 return; 7748 } 7749 7750 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7751 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7752 NewVD->setInvalidDecl(); 7753 return; 7754 } 7755 7756 if (NewVD->isConstexpr() && !T->isDependentType() && 7757 RequireLiteralType(NewVD->getLocation(), T, 7758 diag::err_constexpr_var_non_literal)) { 7759 NewVD->setInvalidDecl(); 7760 return; 7761 } 7762 } 7763 7764 /// Perform semantic checking on a newly-created variable 7765 /// declaration. 7766 /// 7767 /// This routine performs all of the type-checking required for a 7768 /// variable declaration once it has been built. It is used both to 7769 /// check variables after they have been parsed and their declarators 7770 /// have been translated into a declaration, and to check variables 7771 /// that have been instantiated from a template. 7772 /// 7773 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7774 /// 7775 /// Returns true if the variable declaration is a redeclaration. 7776 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7777 CheckVariableDeclarationType(NewVD); 7778 7779 // If the decl is already known invalid, don't check it. 7780 if (NewVD->isInvalidDecl()) 7781 return false; 7782 7783 // If we did not find anything by this name, look for a non-visible 7784 // extern "C" declaration with the same name. 7785 if (Previous.empty() && 7786 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7787 Previous.setShadowed(); 7788 7789 if (!Previous.empty()) { 7790 MergeVarDecl(NewVD, Previous); 7791 return true; 7792 } 7793 return false; 7794 } 7795 7796 namespace { 7797 struct FindOverriddenMethod { 7798 Sema *S; 7799 CXXMethodDecl *Method; 7800 7801 /// Member lookup function that determines whether a given C++ 7802 /// method overrides a method in a base class, to be used with 7803 /// CXXRecordDecl::lookupInBases(). 7804 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7805 RecordDecl *BaseRecord = 7806 Specifier->getType()->castAs<RecordType>()->getDecl(); 7807 7808 DeclarationName Name = Method->getDeclName(); 7809 7810 // FIXME: Do we care about other names here too? 7811 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7812 // We really want to find the base class destructor here. 7813 QualType T = S->Context.getTypeDeclType(BaseRecord); 7814 CanQualType CT = S->Context.getCanonicalType(T); 7815 7816 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7817 } 7818 7819 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7820 Path.Decls = Path.Decls.slice(1)) { 7821 NamedDecl *D = Path.Decls.front(); 7822 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7823 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7824 return true; 7825 } 7826 } 7827 7828 return false; 7829 } 7830 }; 7831 7832 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7833 } // end anonymous namespace 7834 7835 /// Report an error regarding overriding, along with any relevant 7836 /// overridden methods. 7837 /// 7838 /// \param DiagID the primary error to report. 7839 /// \param MD the overriding method. 7840 /// \param OEK which overrides to include as notes. 7841 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7842 OverrideErrorKind OEK = OEK_All) { 7843 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7844 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7845 // This check (& the OEK parameter) could be replaced by a predicate, but 7846 // without lambdas that would be overkill. This is still nicer than writing 7847 // out the diag loop 3 times. 7848 if ((OEK == OEK_All) || 7849 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7850 (OEK == OEK_Deleted && O->isDeleted())) 7851 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7852 } 7853 } 7854 7855 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7856 /// and if so, check that it's a valid override and remember it. 7857 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7858 // Look for methods in base classes that this method might override. 7859 CXXBasePaths Paths; 7860 FindOverriddenMethod FOM; 7861 FOM.Method = MD; 7862 FOM.S = this; 7863 bool hasDeletedOverridenMethods = false; 7864 bool hasNonDeletedOverridenMethods = false; 7865 bool AddedAny = false; 7866 if (DC->lookupInBases(FOM, Paths)) { 7867 for (auto *I : Paths.found_decls()) { 7868 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7869 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7870 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7871 !CheckOverridingFunctionAttributes(MD, OldMD) && 7872 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7873 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7874 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7875 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7876 AddedAny = true; 7877 } 7878 } 7879 } 7880 } 7881 7882 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7883 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7884 } 7885 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7886 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7887 } 7888 7889 return AddedAny; 7890 } 7891 7892 namespace { 7893 // Struct for holding all of the extra arguments needed by 7894 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7895 struct ActOnFDArgs { 7896 Scope *S; 7897 Declarator &D; 7898 MultiTemplateParamsArg TemplateParamLists; 7899 bool AddToScope; 7900 }; 7901 } // end anonymous namespace 7902 7903 namespace { 7904 7905 // Callback to only accept typo corrections that have a non-zero edit distance. 7906 // Also only accept corrections that have the same parent decl. 7907 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 7908 public: 7909 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7910 CXXRecordDecl *Parent) 7911 : Context(Context), OriginalFD(TypoFD), 7912 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7913 7914 bool ValidateCandidate(const TypoCorrection &candidate) override { 7915 if (candidate.getEditDistance() == 0) 7916 return false; 7917 7918 SmallVector<unsigned, 1> MismatchedParams; 7919 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7920 CDeclEnd = candidate.end(); 7921 CDecl != CDeclEnd; ++CDecl) { 7922 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7923 7924 if (FD && !FD->hasBody() && 7925 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7926 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7927 CXXRecordDecl *Parent = MD->getParent(); 7928 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7929 return true; 7930 } else if (!ExpectedParent) { 7931 return true; 7932 } 7933 } 7934 } 7935 7936 return false; 7937 } 7938 7939 std::unique_ptr<CorrectionCandidateCallback> clone() override { 7940 return std::make_unique<DifferentNameValidatorCCC>(*this); 7941 } 7942 7943 private: 7944 ASTContext &Context; 7945 FunctionDecl *OriginalFD; 7946 CXXRecordDecl *ExpectedParent; 7947 }; 7948 7949 } // end anonymous namespace 7950 7951 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7952 TypoCorrectedFunctionDefinitions.insert(F); 7953 } 7954 7955 /// Generate diagnostics for an invalid function redeclaration. 7956 /// 7957 /// This routine handles generating the diagnostic messages for an invalid 7958 /// function redeclaration, including finding possible similar declarations 7959 /// or performing typo correction if there are no previous declarations with 7960 /// the same name. 7961 /// 7962 /// Returns a NamedDecl iff typo correction was performed and substituting in 7963 /// the new declaration name does not cause new errors. 7964 static NamedDecl *DiagnoseInvalidRedeclaration( 7965 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7966 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7967 DeclarationName Name = NewFD->getDeclName(); 7968 DeclContext *NewDC = NewFD->getDeclContext(); 7969 SmallVector<unsigned, 1> MismatchedParams; 7970 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7971 TypoCorrection Correction; 7972 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7973 unsigned DiagMsg = 7974 IsLocalFriend ? diag::err_no_matching_local_friend : 7975 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7976 diag::err_member_decl_does_not_match; 7977 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7978 IsLocalFriend ? Sema::LookupLocalFriendName 7979 : Sema::LookupOrdinaryName, 7980 Sema::ForVisibleRedeclaration); 7981 7982 NewFD->setInvalidDecl(); 7983 if (IsLocalFriend) 7984 SemaRef.LookupName(Prev, S); 7985 else 7986 SemaRef.LookupQualifiedName(Prev, NewDC); 7987 assert(!Prev.isAmbiguous() && 7988 "Cannot have an ambiguity in previous-declaration lookup"); 7989 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7990 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 7991 MD ? MD->getParent() : nullptr); 7992 if (!Prev.empty()) { 7993 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7994 Func != FuncEnd; ++Func) { 7995 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7996 if (FD && 7997 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7998 // Add 1 to the index so that 0 can mean the mismatch didn't 7999 // involve a parameter 8000 unsigned ParamNum = 8001 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8002 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8003 } 8004 } 8005 // If the qualified name lookup yielded nothing, try typo correction 8006 } else if ((Correction = SemaRef.CorrectTypo( 8007 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8008 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8009 IsLocalFriend ? nullptr : NewDC))) { 8010 // Set up everything for the call to ActOnFunctionDeclarator 8011 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8012 ExtraArgs.D.getIdentifierLoc()); 8013 Previous.clear(); 8014 Previous.setLookupName(Correction.getCorrection()); 8015 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8016 CDeclEnd = Correction.end(); 8017 CDecl != CDeclEnd; ++CDecl) { 8018 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8019 if (FD && !FD->hasBody() && 8020 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8021 Previous.addDecl(FD); 8022 } 8023 } 8024 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8025 8026 NamedDecl *Result; 8027 // Retry building the function declaration with the new previous 8028 // declarations, and with errors suppressed. 8029 { 8030 // Trap errors. 8031 Sema::SFINAETrap Trap(SemaRef); 8032 8033 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8034 // pieces need to verify the typo-corrected C++ declaration and hopefully 8035 // eliminate the need for the parameter pack ExtraArgs. 8036 Result = SemaRef.ActOnFunctionDeclarator( 8037 ExtraArgs.S, ExtraArgs.D, 8038 Correction.getCorrectionDecl()->getDeclContext(), 8039 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8040 ExtraArgs.AddToScope); 8041 8042 if (Trap.hasErrorOccurred()) 8043 Result = nullptr; 8044 } 8045 8046 if (Result) { 8047 // Determine which correction we picked. 8048 Decl *Canonical = Result->getCanonicalDecl(); 8049 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8050 I != E; ++I) 8051 if ((*I)->getCanonicalDecl() == Canonical) 8052 Correction.setCorrectionDecl(*I); 8053 8054 // Let Sema know about the correction. 8055 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8056 SemaRef.diagnoseTypo( 8057 Correction, 8058 SemaRef.PDiag(IsLocalFriend 8059 ? diag::err_no_matching_local_friend_suggest 8060 : diag::err_member_decl_does_not_match_suggest) 8061 << Name << NewDC << IsDefinition); 8062 return Result; 8063 } 8064 8065 // Pretend the typo correction never occurred 8066 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8067 ExtraArgs.D.getIdentifierLoc()); 8068 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8069 Previous.clear(); 8070 Previous.setLookupName(Name); 8071 } 8072 8073 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8074 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8075 8076 bool NewFDisConst = false; 8077 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8078 NewFDisConst = NewMD->isConst(); 8079 8080 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8081 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8082 NearMatch != NearMatchEnd; ++NearMatch) { 8083 FunctionDecl *FD = NearMatch->first; 8084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8085 bool FDisConst = MD && MD->isConst(); 8086 bool IsMember = MD || !IsLocalFriend; 8087 8088 // FIXME: These notes are poorly worded for the local friend case. 8089 if (unsigned Idx = NearMatch->second) { 8090 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8091 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8092 if (Loc.isInvalid()) Loc = FD->getLocation(); 8093 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8094 : diag::note_local_decl_close_param_match) 8095 << Idx << FDParam->getType() 8096 << NewFD->getParamDecl(Idx - 1)->getType(); 8097 } else if (FDisConst != NewFDisConst) { 8098 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8099 << NewFDisConst << FD->getSourceRange().getEnd(); 8100 } else 8101 SemaRef.Diag(FD->getLocation(), 8102 IsMember ? diag::note_member_def_close_match 8103 : diag::note_local_decl_close_match); 8104 } 8105 return nullptr; 8106 } 8107 8108 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8109 switch (D.getDeclSpec().getStorageClassSpec()) { 8110 default: llvm_unreachable("Unknown storage class!"); 8111 case DeclSpec::SCS_auto: 8112 case DeclSpec::SCS_register: 8113 case DeclSpec::SCS_mutable: 8114 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8115 diag::err_typecheck_sclass_func); 8116 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8117 D.setInvalidType(); 8118 break; 8119 case DeclSpec::SCS_unspecified: break; 8120 case DeclSpec::SCS_extern: 8121 if (D.getDeclSpec().isExternInLinkageSpec()) 8122 return SC_None; 8123 return SC_Extern; 8124 case DeclSpec::SCS_static: { 8125 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8126 // C99 6.7.1p5: 8127 // The declaration of an identifier for a function that has 8128 // block scope shall have no explicit storage-class specifier 8129 // other than extern 8130 // See also (C++ [dcl.stc]p4). 8131 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8132 diag::err_static_block_func); 8133 break; 8134 } else 8135 return SC_Static; 8136 } 8137 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8138 } 8139 8140 // No explicit storage class has already been returned 8141 return SC_None; 8142 } 8143 8144 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8145 DeclContext *DC, QualType &R, 8146 TypeSourceInfo *TInfo, 8147 StorageClass SC, 8148 bool &IsVirtualOkay) { 8149 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8150 DeclarationName Name = NameInfo.getName(); 8151 8152 FunctionDecl *NewFD = nullptr; 8153 bool isInline = D.getDeclSpec().isInlineSpecified(); 8154 8155 if (!SemaRef.getLangOpts().CPlusPlus) { 8156 // Determine whether the function was written with a 8157 // prototype. This true when: 8158 // - there is a prototype in the declarator, or 8159 // - the type R of the function is some kind of typedef or other non- 8160 // attributed reference to a type name (which eventually refers to a 8161 // function type). 8162 bool HasPrototype = 8163 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8164 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8165 8166 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8167 R, TInfo, SC, isInline, HasPrototype, 8168 CSK_unspecified); 8169 if (D.isInvalidType()) 8170 NewFD->setInvalidDecl(); 8171 8172 return NewFD; 8173 } 8174 8175 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8176 8177 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8178 if (ConstexprKind == CSK_constinit) { 8179 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8180 diag::err_constexpr_wrong_decl_kind) 8181 << ConstexprKind; 8182 ConstexprKind = CSK_unspecified; 8183 D.getMutableDeclSpec().ClearConstexprSpec(); 8184 } 8185 8186 // Check that the return type is not an abstract class type. 8187 // For record types, this is done by the AbstractClassUsageDiagnoser once 8188 // the class has been completely parsed. 8189 if (!DC->isRecord() && 8190 SemaRef.RequireNonAbstractType( 8191 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8192 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8193 D.setInvalidType(); 8194 8195 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8196 // This is a C++ constructor declaration. 8197 assert(DC->isRecord() && 8198 "Constructors can only be declared in a member context"); 8199 8200 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8201 return CXXConstructorDecl::Create( 8202 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8203 TInfo, ExplicitSpecifier, isInline, 8204 /*isImplicitlyDeclared=*/false, ConstexprKind); 8205 8206 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8207 // This is a C++ destructor declaration. 8208 if (DC->isRecord()) { 8209 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8210 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8211 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8212 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8213 isInline, 8214 /*isImplicitlyDeclared=*/false, ConstexprKind); 8215 8216 // If the destructor needs an implicit exception specification, set it 8217 // now. FIXME: It'd be nice to be able to create the right type to start 8218 // with, but the type needs to reference the destructor declaration. 8219 if (SemaRef.getLangOpts().CPlusPlus11) 8220 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8221 8222 IsVirtualOkay = true; 8223 return NewDD; 8224 8225 } else { 8226 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8227 D.setInvalidType(); 8228 8229 // Create a FunctionDecl to satisfy the function definition parsing 8230 // code path. 8231 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8232 D.getIdentifierLoc(), Name, R, TInfo, SC, 8233 isInline, 8234 /*hasPrototype=*/true, ConstexprKind); 8235 } 8236 8237 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8238 if (!DC->isRecord()) { 8239 SemaRef.Diag(D.getIdentifierLoc(), 8240 diag::err_conv_function_not_member); 8241 return nullptr; 8242 } 8243 8244 SemaRef.CheckConversionDeclarator(D, R, SC); 8245 if (D.isInvalidType()) 8246 return nullptr; 8247 8248 IsVirtualOkay = true; 8249 return CXXConversionDecl::Create( 8250 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8251 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation()); 8252 8253 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8254 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8255 8256 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8257 ExplicitSpecifier, NameInfo, R, TInfo, 8258 D.getEndLoc()); 8259 } else if (DC->isRecord()) { 8260 // If the name of the function is the same as the name of the record, 8261 // then this must be an invalid constructor that has a return type. 8262 // (The parser checks for a return type and makes the declarator a 8263 // constructor if it has no return type). 8264 if (Name.getAsIdentifierInfo() && 8265 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8266 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8267 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8268 << SourceRange(D.getIdentifierLoc()); 8269 return nullptr; 8270 } 8271 8272 // This is a C++ method declaration. 8273 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8274 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8275 TInfo, SC, isInline, ConstexprKind, SourceLocation()); 8276 IsVirtualOkay = !Ret->isStatic(); 8277 return Ret; 8278 } else { 8279 bool isFriend = 8280 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8281 if (!isFriend && SemaRef.CurContext->isRecord()) 8282 return nullptr; 8283 8284 // Determine whether the function was written with a 8285 // prototype. This true when: 8286 // - we're in C++ (where every function has a prototype), 8287 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8288 R, TInfo, SC, isInline, true /*HasPrototype*/, 8289 ConstexprKind); 8290 } 8291 } 8292 8293 enum OpenCLParamType { 8294 ValidKernelParam, 8295 PtrPtrKernelParam, 8296 PtrKernelParam, 8297 InvalidAddrSpacePtrKernelParam, 8298 InvalidKernelParam, 8299 RecordKernelParam 8300 }; 8301 8302 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8303 // Size dependent types are just typedefs to normal integer types 8304 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8305 // integers other than by their names. 8306 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8307 8308 // Remove typedefs one by one until we reach a typedef 8309 // for a size dependent type. 8310 QualType DesugaredTy = Ty; 8311 do { 8312 ArrayRef<StringRef> Names(SizeTypeNames); 8313 auto Match = llvm::find(Names, DesugaredTy.getAsString()); 8314 if (Names.end() != Match) 8315 return true; 8316 8317 Ty = DesugaredTy; 8318 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8319 } while (DesugaredTy != Ty); 8320 8321 return false; 8322 } 8323 8324 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8325 if (PT->isPointerType()) { 8326 QualType PointeeType = PT->getPointeeType(); 8327 if (PointeeType->isPointerType()) 8328 return PtrPtrKernelParam; 8329 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8330 PointeeType.getAddressSpace() == LangAS::opencl_private || 8331 PointeeType.getAddressSpace() == LangAS::Default) 8332 return InvalidAddrSpacePtrKernelParam; 8333 return PtrKernelParam; 8334 } 8335 8336 // OpenCL v1.2 s6.9.k: 8337 // Arguments to kernel functions in a program cannot be declared with the 8338 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8339 // uintptr_t or a struct and/or union that contain fields declared to be one 8340 // of these built-in scalar types. 8341 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8342 return InvalidKernelParam; 8343 8344 if (PT->isImageType()) 8345 return PtrKernelParam; 8346 8347 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8348 return InvalidKernelParam; 8349 8350 // OpenCL extension spec v1.2 s9.5: 8351 // This extension adds support for half scalar and vector types as built-in 8352 // types that can be used for arithmetic operations, conversions etc. 8353 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8354 return InvalidKernelParam; 8355 8356 if (PT->isRecordType()) 8357 return RecordKernelParam; 8358 8359 // Look into an array argument to check if it has a forbidden type. 8360 if (PT->isArrayType()) { 8361 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8362 // Call ourself to check an underlying type of an array. Since the 8363 // getPointeeOrArrayElementType returns an innermost type which is not an 8364 // array, this recursive call only happens once. 8365 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8366 } 8367 8368 return ValidKernelParam; 8369 } 8370 8371 static void checkIsValidOpenCLKernelParameter( 8372 Sema &S, 8373 Declarator &D, 8374 ParmVarDecl *Param, 8375 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8376 QualType PT = Param->getType(); 8377 8378 // Cache the valid types we encounter to avoid rechecking structs that are 8379 // used again 8380 if (ValidTypes.count(PT.getTypePtr())) 8381 return; 8382 8383 switch (getOpenCLKernelParameterType(S, PT)) { 8384 case PtrPtrKernelParam: 8385 // OpenCL v1.2 s6.9.a: 8386 // A kernel function argument cannot be declared as a 8387 // pointer to a pointer type. 8388 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8389 D.setInvalidType(); 8390 return; 8391 8392 case InvalidAddrSpacePtrKernelParam: 8393 // OpenCL v1.0 s6.5: 8394 // __kernel function arguments declared to be a pointer of a type can point 8395 // to one of the following address spaces only : __global, __local or 8396 // __constant. 8397 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8398 D.setInvalidType(); 8399 return; 8400 8401 // OpenCL v1.2 s6.9.k: 8402 // Arguments to kernel functions in a program cannot be declared with the 8403 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8404 // uintptr_t or a struct and/or union that contain fields declared to be 8405 // one of these built-in scalar types. 8406 8407 case InvalidKernelParam: 8408 // OpenCL v1.2 s6.8 n: 8409 // A kernel function argument cannot be declared 8410 // of event_t type. 8411 // Do not diagnose half type since it is diagnosed as invalid argument 8412 // type for any function elsewhere. 8413 if (!PT->isHalfType()) { 8414 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8415 8416 // Explain what typedefs are involved. 8417 const TypedefType *Typedef = nullptr; 8418 while ((Typedef = PT->getAs<TypedefType>())) { 8419 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8420 // SourceLocation may be invalid for a built-in type. 8421 if (Loc.isValid()) 8422 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8423 PT = Typedef->desugar(); 8424 } 8425 } 8426 8427 D.setInvalidType(); 8428 return; 8429 8430 case PtrKernelParam: 8431 case ValidKernelParam: 8432 ValidTypes.insert(PT.getTypePtr()); 8433 return; 8434 8435 case RecordKernelParam: 8436 break; 8437 } 8438 8439 // Track nested structs we will inspect 8440 SmallVector<const Decl *, 4> VisitStack; 8441 8442 // Track where we are in the nested structs. Items will migrate from 8443 // VisitStack to HistoryStack as we do the DFS for bad field. 8444 SmallVector<const FieldDecl *, 4> HistoryStack; 8445 HistoryStack.push_back(nullptr); 8446 8447 // At this point we already handled everything except of a RecordType or 8448 // an ArrayType of a RecordType. 8449 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8450 const RecordType *RecTy = 8451 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8452 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8453 8454 VisitStack.push_back(RecTy->getDecl()); 8455 assert(VisitStack.back() && "First decl null?"); 8456 8457 do { 8458 const Decl *Next = VisitStack.pop_back_val(); 8459 if (!Next) { 8460 assert(!HistoryStack.empty()); 8461 // Found a marker, we have gone up a level 8462 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8463 ValidTypes.insert(Hist->getType().getTypePtr()); 8464 8465 continue; 8466 } 8467 8468 // Adds everything except the original parameter declaration (which is not a 8469 // field itself) to the history stack. 8470 const RecordDecl *RD; 8471 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8472 HistoryStack.push_back(Field); 8473 8474 QualType FieldTy = Field->getType(); 8475 // Other field types (known to be valid or invalid) are handled while we 8476 // walk around RecordDecl::fields(). 8477 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8478 "Unexpected type."); 8479 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8480 8481 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8482 } else { 8483 RD = cast<RecordDecl>(Next); 8484 } 8485 8486 // Add a null marker so we know when we've gone back up a level 8487 VisitStack.push_back(nullptr); 8488 8489 for (const auto *FD : RD->fields()) { 8490 QualType QT = FD->getType(); 8491 8492 if (ValidTypes.count(QT.getTypePtr())) 8493 continue; 8494 8495 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8496 if (ParamType == ValidKernelParam) 8497 continue; 8498 8499 if (ParamType == RecordKernelParam) { 8500 VisitStack.push_back(FD); 8501 continue; 8502 } 8503 8504 // OpenCL v1.2 s6.9.p: 8505 // Arguments to kernel functions that are declared to be a struct or union 8506 // do not allow OpenCL objects to be passed as elements of the struct or 8507 // union. 8508 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8509 ParamType == InvalidAddrSpacePtrKernelParam) { 8510 S.Diag(Param->getLocation(), 8511 diag::err_record_with_pointers_kernel_param) 8512 << PT->isUnionType() 8513 << PT; 8514 } else { 8515 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8516 } 8517 8518 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8519 << OrigRecDecl->getDeclName(); 8520 8521 // We have an error, now let's go back up through history and show where 8522 // the offending field came from 8523 for (ArrayRef<const FieldDecl *>::const_iterator 8524 I = HistoryStack.begin() + 1, 8525 E = HistoryStack.end(); 8526 I != E; ++I) { 8527 const FieldDecl *OuterField = *I; 8528 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8529 << OuterField->getType(); 8530 } 8531 8532 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8533 << QT->isPointerType() 8534 << QT; 8535 D.setInvalidType(); 8536 return; 8537 } 8538 } while (!VisitStack.empty()); 8539 } 8540 8541 /// Find the DeclContext in which a tag is implicitly declared if we see an 8542 /// elaborated type specifier in the specified context, and lookup finds 8543 /// nothing. 8544 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8545 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8546 DC = DC->getParent(); 8547 return DC; 8548 } 8549 8550 /// Find the Scope in which a tag is implicitly declared if we see an 8551 /// elaborated type specifier in the specified context, and lookup finds 8552 /// nothing. 8553 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8554 while (S->isClassScope() || 8555 (LangOpts.CPlusPlus && 8556 S->isFunctionPrototypeScope()) || 8557 ((S->getFlags() & Scope::DeclScope) == 0) || 8558 (S->getEntity() && S->getEntity()->isTransparentContext())) 8559 S = S->getParent(); 8560 return S; 8561 } 8562 8563 NamedDecl* 8564 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8565 TypeSourceInfo *TInfo, LookupResult &Previous, 8566 MultiTemplateParamsArg TemplateParamLists, 8567 bool &AddToScope) { 8568 QualType R = TInfo->getType(); 8569 8570 assert(R->isFunctionType()); 8571 8572 // TODO: consider using NameInfo for diagnostic. 8573 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8574 DeclarationName Name = NameInfo.getName(); 8575 StorageClass SC = getFunctionStorageClass(*this, D); 8576 8577 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8578 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8579 diag::err_invalid_thread) 8580 << DeclSpec::getSpecifierName(TSCS); 8581 8582 if (D.isFirstDeclarationOfMember()) 8583 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8584 D.getIdentifierLoc()); 8585 8586 bool isFriend = false; 8587 FunctionTemplateDecl *FunctionTemplate = nullptr; 8588 bool isMemberSpecialization = false; 8589 bool isFunctionTemplateSpecialization = false; 8590 8591 bool isDependentClassScopeExplicitSpecialization = false; 8592 bool HasExplicitTemplateArgs = false; 8593 TemplateArgumentListInfo TemplateArgs; 8594 8595 bool isVirtualOkay = false; 8596 8597 DeclContext *OriginalDC = DC; 8598 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8599 8600 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8601 isVirtualOkay); 8602 if (!NewFD) return nullptr; 8603 8604 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8605 NewFD->setTopLevelDeclInObjCContainer(); 8606 8607 // Set the lexical context. If this is a function-scope declaration, or has a 8608 // C++ scope specifier, or is the object of a friend declaration, the lexical 8609 // context will be different from the semantic context. 8610 NewFD->setLexicalDeclContext(CurContext); 8611 8612 if (IsLocalExternDecl) 8613 NewFD->setLocalExternDecl(); 8614 8615 if (getLangOpts().CPlusPlus) { 8616 bool isInline = D.getDeclSpec().isInlineSpecified(); 8617 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8618 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8619 isFriend = D.getDeclSpec().isFriendSpecified(); 8620 if (isFriend && !isInline && D.isFunctionDefinition()) { 8621 // C++ [class.friend]p5 8622 // A function can be defined in a friend declaration of a 8623 // class . . . . Such a function is implicitly inline. 8624 NewFD->setImplicitlyInline(); 8625 } 8626 8627 // If this is a method defined in an __interface, and is not a constructor 8628 // or an overloaded operator, then set the pure flag (isVirtual will already 8629 // return true). 8630 if (const CXXRecordDecl *Parent = 8631 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8632 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8633 NewFD->setPure(true); 8634 8635 // C++ [class.union]p2 8636 // A union can have member functions, but not virtual functions. 8637 if (isVirtual && Parent->isUnion()) 8638 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8639 } 8640 8641 SetNestedNameSpecifier(*this, NewFD, D); 8642 isMemberSpecialization = false; 8643 isFunctionTemplateSpecialization = false; 8644 if (D.isInvalidType()) 8645 NewFD->setInvalidDecl(); 8646 8647 // Match up the template parameter lists with the scope specifier, then 8648 // determine whether we have a template or a template specialization. 8649 bool Invalid = false; 8650 if (TemplateParameterList *TemplateParams = 8651 MatchTemplateParametersToScopeSpecifier( 8652 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8653 D.getCXXScopeSpec(), 8654 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8655 ? D.getName().TemplateId 8656 : nullptr, 8657 TemplateParamLists, isFriend, isMemberSpecialization, 8658 Invalid)) { 8659 if (TemplateParams->size() > 0) { 8660 // This is a function template 8661 8662 // Check that we can declare a template here. 8663 if (CheckTemplateDeclScope(S, TemplateParams)) 8664 NewFD->setInvalidDecl(); 8665 8666 // A destructor cannot be a template. 8667 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8668 Diag(NewFD->getLocation(), diag::err_destructor_template); 8669 NewFD->setInvalidDecl(); 8670 } 8671 8672 // If we're adding a template to a dependent context, we may need to 8673 // rebuilding some of the types used within the template parameter list, 8674 // now that we know what the current instantiation is. 8675 if (DC->isDependentContext()) { 8676 ContextRAII SavedContext(*this, DC); 8677 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8678 Invalid = true; 8679 } 8680 8681 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8682 NewFD->getLocation(), 8683 Name, TemplateParams, 8684 NewFD); 8685 FunctionTemplate->setLexicalDeclContext(CurContext); 8686 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8687 8688 // For source fidelity, store the other template param lists. 8689 if (TemplateParamLists.size() > 1) { 8690 NewFD->setTemplateParameterListsInfo(Context, 8691 TemplateParamLists.drop_back(1)); 8692 } 8693 } else { 8694 // This is a function template specialization. 8695 isFunctionTemplateSpecialization = true; 8696 // For source fidelity, store all the template param lists. 8697 if (TemplateParamLists.size() > 0) 8698 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8699 8700 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8701 if (isFriend) { 8702 // We want to remove the "template<>", found here. 8703 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8704 8705 // If we remove the template<> and the name is not a 8706 // template-id, we're actually silently creating a problem: 8707 // the friend declaration will refer to an untemplated decl, 8708 // and clearly the user wants a template specialization. So 8709 // we need to insert '<>' after the name. 8710 SourceLocation InsertLoc; 8711 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8712 InsertLoc = D.getName().getSourceRange().getEnd(); 8713 InsertLoc = getLocForEndOfToken(InsertLoc); 8714 } 8715 8716 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8717 << Name << RemoveRange 8718 << FixItHint::CreateRemoval(RemoveRange) 8719 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8720 } 8721 } 8722 } else { 8723 // All template param lists were matched against the scope specifier: 8724 // this is NOT (an explicit specialization of) a template. 8725 if (TemplateParamLists.size() > 0) 8726 // For source fidelity, store all the template param lists. 8727 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8728 } 8729 8730 if (Invalid) { 8731 NewFD->setInvalidDecl(); 8732 if (FunctionTemplate) 8733 FunctionTemplate->setInvalidDecl(); 8734 } 8735 8736 // C++ [dcl.fct.spec]p5: 8737 // The virtual specifier shall only be used in declarations of 8738 // nonstatic class member functions that appear within a 8739 // member-specification of a class declaration; see 10.3. 8740 // 8741 if (isVirtual && !NewFD->isInvalidDecl()) { 8742 if (!isVirtualOkay) { 8743 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8744 diag::err_virtual_non_function); 8745 } else if (!CurContext->isRecord()) { 8746 // 'virtual' was specified outside of the class. 8747 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8748 diag::err_virtual_out_of_class) 8749 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8750 } else if (NewFD->getDescribedFunctionTemplate()) { 8751 // C++ [temp.mem]p3: 8752 // A member function template shall not be virtual. 8753 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8754 diag::err_virtual_member_function_template) 8755 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8756 } else { 8757 // Okay: Add virtual to the method. 8758 NewFD->setVirtualAsWritten(true); 8759 } 8760 8761 if (getLangOpts().CPlusPlus14 && 8762 NewFD->getReturnType()->isUndeducedType()) 8763 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8764 } 8765 8766 if (getLangOpts().CPlusPlus14 && 8767 (NewFD->isDependentContext() || 8768 (isFriend && CurContext->isDependentContext())) && 8769 NewFD->getReturnType()->isUndeducedType()) { 8770 // If the function template is referenced directly (for instance, as a 8771 // member of the current instantiation), pretend it has a dependent type. 8772 // This is not really justified by the standard, but is the only sane 8773 // thing to do. 8774 // FIXME: For a friend function, we have not marked the function as being 8775 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8776 const FunctionProtoType *FPT = 8777 NewFD->getType()->castAs<FunctionProtoType>(); 8778 QualType Result = 8779 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8780 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8781 FPT->getExtProtoInfo())); 8782 } 8783 8784 // C++ [dcl.fct.spec]p3: 8785 // The inline specifier shall not appear on a block scope function 8786 // declaration. 8787 if (isInline && !NewFD->isInvalidDecl()) { 8788 if (CurContext->isFunctionOrMethod()) { 8789 // 'inline' is not allowed on block scope function declaration. 8790 Diag(D.getDeclSpec().getInlineSpecLoc(), 8791 diag::err_inline_declaration_block_scope) << Name 8792 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8793 } 8794 } 8795 8796 // C++ [dcl.fct.spec]p6: 8797 // The explicit specifier shall be used only in the declaration of a 8798 // constructor or conversion function within its class definition; 8799 // see 12.3.1 and 12.3.2. 8800 if (hasExplicit && !NewFD->isInvalidDecl() && 8801 !isa<CXXDeductionGuideDecl>(NewFD)) { 8802 if (!CurContext->isRecord()) { 8803 // 'explicit' was specified outside of the class. 8804 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8805 diag::err_explicit_out_of_class) 8806 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8807 } else if (!isa<CXXConstructorDecl>(NewFD) && 8808 !isa<CXXConversionDecl>(NewFD)) { 8809 // 'explicit' was specified on a function that wasn't a constructor 8810 // or conversion function. 8811 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8812 diag::err_explicit_non_ctor_or_conv_function) 8813 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8814 } 8815 } 8816 8817 if (ConstexprSpecKind ConstexprKind = 8818 D.getDeclSpec().getConstexprSpecifier()) { 8819 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8820 // are implicitly inline. 8821 NewFD->setImplicitlyInline(); 8822 8823 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8824 // be either constructors or to return a literal type. Therefore, 8825 // destructors cannot be declared constexpr. 8826 if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) { 8827 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 8828 << ConstexprKind; 8829 } 8830 } 8831 8832 // If __module_private__ was specified, mark the function accordingly. 8833 if (D.getDeclSpec().isModulePrivateSpecified()) { 8834 if (isFunctionTemplateSpecialization) { 8835 SourceLocation ModulePrivateLoc 8836 = D.getDeclSpec().getModulePrivateSpecLoc(); 8837 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8838 << 0 8839 << FixItHint::CreateRemoval(ModulePrivateLoc); 8840 } else { 8841 NewFD->setModulePrivate(); 8842 if (FunctionTemplate) 8843 FunctionTemplate->setModulePrivate(); 8844 } 8845 } 8846 8847 if (isFriend) { 8848 if (FunctionTemplate) { 8849 FunctionTemplate->setObjectOfFriendDecl(); 8850 FunctionTemplate->setAccess(AS_public); 8851 } 8852 NewFD->setObjectOfFriendDecl(); 8853 NewFD->setAccess(AS_public); 8854 } 8855 8856 // If a function is defined as defaulted or deleted, mark it as such now. 8857 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8858 // definition kind to FDK_Definition. 8859 switch (D.getFunctionDefinitionKind()) { 8860 case FDK_Declaration: 8861 case FDK_Definition: 8862 break; 8863 8864 case FDK_Defaulted: 8865 NewFD->setDefaulted(); 8866 break; 8867 8868 case FDK_Deleted: 8869 NewFD->setDeletedAsWritten(); 8870 break; 8871 } 8872 8873 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8874 D.isFunctionDefinition()) { 8875 // C++ [class.mfct]p2: 8876 // A member function may be defined (8.4) in its class definition, in 8877 // which case it is an inline member function (7.1.2) 8878 NewFD->setImplicitlyInline(); 8879 } 8880 8881 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8882 !CurContext->isRecord()) { 8883 // C++ [class.static]p1: 8884 // A data or function member of a class may be declared static 8885 // in a class definition, in which case it is a static member of 8886 // the class. 8887 8888 // Complain about the 'static' specifier if it's on an out-of-line 8889 // member function definition. 8890 8891 // MSVC permits the use of a 'static' storage specifier on an out-of-line 8892 // member function template declaration and class member template 8893 // declaration (MSVC versions before 2015), warn about this. 8894 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8895 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 8896 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 8897 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 8898 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 8899 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8900 } 8901 8902 // C++11 [except.spec]p15: 8903 // A deallocation function with no exception-specification is treated 8904 // as if it were specified with noexcept(true). 8905 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8906 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8907 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8908 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8909 NewFD->setType(Context.getFunctionType( 8910 FPT->getReturnType(), FPT->getParamTypes(), 8911 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8912 } 8913 8914 // Filter out previous declarations that don't match the scope. 8915 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8916 D.getCXXScopeSpec().isNotEmpty() || 8917 isMemberSpecialization || 8918 isFunctionTemplateSpecialization); 8919 8920 // Handle GNU asm-label extension (encoded as an attribute). 8921 if (Expr *E = (Expr*) D.getAsmLabel()) { 8922 // The parser guarantees this is a string. 8923 StringLiteral *SE = cast<StringLiteral>(E); 8924 NewFD->addAttr(::new (Context) 8925 AsmLabelAttr(Context, SE->getStrTokenLoc(0), 8926 SE->getString(), /*IsLiteralLabel=*/true)); 8927 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8928 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8929 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8930 if (I != ExtnameUndeclaredIdentifiers.end()) { 8931 if (isDeclExternC(NewFD)) { 8932 NewFD->addAttr(I->second); 8933 ExtnameUndeclaredIdentifiers.erase(I); 8934 } else 8935 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8936 << /*Variable*/0 << NewFD; 8937 } 8938 } 8939 8940 // Copy the parameter declarations from the declarator D to the function 8941 // declaration NewFD, if they are available. First scavenge them into Params. 8942 SmallVector<ParmVarDecl*, 16> Params; 8943 unsigned FTIIdx; 8944 if (D.isFunctionDeclarator(FTIIdx)) { 8945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8946 8947 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8948 // function that takes no arguments, not a function that takes a 8949 // single void argument. 8950 // We let through "const void" here because Sema::GetTypeForDeclarator 8951 // already checks for that case. 8952 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8953 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8954 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8955 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8956 Param->setDeclContext(NewFD); 8957 Params.push_back(Param); 8958 8959 if (Param->isInvalidDecl()) 8960 NewFD->setInvalidDecl(); 8961 } 8962 } 8963 8964 if (!getLangOpts().CPlusPlus) { 8965 // In C, find all the tag declarations from the prototype and move them 8966 // into the function DeclContext. Remove them from the surrounding tag 8967 // injection context of the function, which is typically but not always 8968 // the TU. 8969 DeclContext *PrototypeTagContext = 8970 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8971 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8972 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8973 8974 // We don't want to reparent enumerators. Look at their parent enum 8975 // instead. 8976 if (!TD) { 8977 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8978 TD = cast<EnumDecl>(ECD->getDeclContext()); 8979 } 8980 if (!TD) 8981 continue; 8982 DeclContext *TagDC = TD->getLexicalDeclContext(); 8983 if (!TagDC->containsDecl(TD)) 8984 continue; 8985 TagDC->removeDecl(TD); 8986 TD->setDeclContext(NewFD); 8987 NewFD->addDecl(TD); 8988 8989 // Preserve the lexical DeclContext if it is not the surrounding tag 8990 // injection context of the FD. In this example, the semantic context of 8991 // E will be f and the lexical context will be S, while both the 8992 // semantic and lexical contexts of S will be f: 8993 // void f(struct S { enum E { a } f; } s); 8994 if (TagDC != PrototypeTagContext) 8995 TD->setLexicalDeclContext(TagDC); 8996 } 8997 } 8998 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8999 // When we're declaring a function with a typedef, typeof, etc as in the 9000 // following example, we'll need to synthesize (unnamed) 9001 // parameters for use in the declaration. 9002 // 9003 // @code 9004 // typedef void fn(int); 9005 // fn f; 9006 // @endcode 9007 9008 // Synthesize a parameter for each argument type. 9009 for (const auto &AI : FT->param_types()) { 9010 ParmVarDecl *Param = 9011 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9012 Param->setScopeInfo(0, Params.size()); 9013 Params.push_back(Param); 9014 } 9015 } else { 9016 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9017 "Should not need args for typedef of non-prototype fn"); 9018 } 9019 9020 // Finally, we know we have the right number of parameters, install them. 9021 NewFD->setParams(Params); 9022 9023 if (D.getDeclSpec().isNoreturnSpecified()) 9024 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9025 D.getDeclSpec().getNoreturnSpecLoc(), 9026 AttributeCommonInfo::AS_Keyword)); 9027 9028 // Functions returning a variably modified type violate C99 6.7.5.2p2 9029 // because all functions have linkage. 9030 if (!NewFD->isInvalidDecl() && 9031 NewFD->getReturnType()->isVariablyModifiedType()) { 9032 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9033 NewFD->setInvalidDecl(); 9034 } 9035 9036 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9037 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9038 !NewFD->hasAttr<SectionAttr>()) 9039 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9040 Context, PragmaClangTextSection.SectionName, 9041 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9042 9043 // Apply an implicit SectionAttr if #pragma code_seg is active. 9044 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9045 !NewFD->hasAttr<SectionAttr>()) { 9046 NewFD->addAttr(SectionAttr::CreateImplicit( 9047 Context, CodeSegStack.CurrentValue->getString(), 9048 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9049 SectionAttr::Declspec_allocate)); 9050 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9051 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9052 ASTContext::PSF_Read, 9053 NewFD)) 9054 NewFD->dropAttr<SectionAttr>(); 9055 } 9056 9057 // Apply an implicit CodeSegAttr from class declspec or 9058 // apply an implicit SectionAttr from #pragma code_seg if active. 9059 if (!NewFD->hasAttr<CodeSegAttr>()) { 9060 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9061 D.isFunctionDefinition())) { 9062 NewFD->addAttr(SAttr); 9063 } 9064 } 9065 9066 // Handle attributes. 9067 ProcessDeclAttributes(S, NewFD, D); 9068 9069 if (getLangOpts().OpenCL) { 9070 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9071 // type declaration will generate a compilation error. 9072 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9073 if (AddressSpace != LangAS::Default) { 9074 Diag(NewFD->getLocation(), 9075 diag::err_opencl_return_value_with_address_space); 9076 NewFD->setInvalidDecl(); 9077 } 9078 } 9079 9080 if (!getLangOpts().CPlusPlus) { 9081 // Perform semantic checking on the function declaration. 9082 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9083 CheckMain(NewFD, D.getDeclSpec()); 9084 9085 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9086 CheckMSVCRTEntryPoint(NewFD); 9087 9088 if (!NewFD->isInvalidDecl()) 9089 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9090 isMemberSpecialization)); 9091 else if (!Previous.empty()) 9092 // Recover gracefully from an invalid redeclaration. 9093 D.setRedeclaration(true); 9094 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9095 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9096 "previous declaration set still overloaded"); 9097 9098 // Diagnose no-prototype function declarations with calling conventions that 9099 // don't support variadic calls. Only do this in C and do it after merging 9100 // possibly prototyped redeclarations. 9101 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9102 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9103 CallingConv CC = FT->getExtInfo().getCC(); 9104 if (!supportsVariadicCall(CC)) { 9105 // Windows system headers sometimes accidentally use stdcall without 9106 // (void) parameters, so we relax this to a warning. 9107 int DiagID = 9108 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9109 Diag(NewFD->getLocation(), DiagID) 9110 << FunctionType::getNameForCallConv(CC); 9111 } 9112 } 9113 9114 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9115 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9116 checkNonTrivialCUnion(NewFD->getReturnType(), 9117 NewFD->getReturnTypeSourceRange().getBegin(), 9118 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9119 } else { 9120 // C++11 [replacement.functions]p3: 9121 // The program's definitions shall not be specified as inline. 9122 // 9123 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9124 // 9125 // Suppress the diagnostic if the function is __attribute__((used)), since 9126 // that forces an external definition to be emitted. 9127 if (D.getDeclSpec().isInlineSpecified() && 9128 NewFD->isReplaceableGlobalAllocationFunction() && 9129 !NewFD->hasAttr<UsedAttr>()) 9130 Diag(D.getDeclSpec().getInlineSpecLoc(), 9131 diag::ext_operator_new_delete_declared_inline) 9132 << NewFD->getDeclName(); 9133 9134 // If the declarator is a template-id, translate the parser's template 9135 // argument list into our AST format. 9136 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9137 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9138 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9139 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9140 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9141 TemplateId->NumArgs); 9142 translateTemplateArguments(TemplateArgsPtr, 9143 TemplateArgs); 9144 9145 HasExplicitTemplateArgs = true; 9146 9147 if (NewFD->isInvalidDecl()) { 9148 HasExplicitTemplateArgs = false; 9149 } else if (FunctionTemplate) { 9150 // Function template with explicit template arguments. 9151 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9152 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9153 9154 HasExplicitTemplateArgs = false; 9155 } else { 9156 assert((isFunctionTemplateSpecialization || 9157 D.getDeclSpec().isFriendSpecified()) && 9158 "should have a 'template<>' for this decl"); 9159 // "friend void foo<>(int);" is an implicit specialization decl. 9160 isFunctionTemplateSpecialization = true; 9161 } 9162 } else if (isFriend && isFunctionTemplateSpecialization) { 9163 // This combination is only possible in a recovery case; the user 9164 // wrote something like: 9165 // template <> friend void foo(int); 9166 // which we're recovering from as if the user had written: 9167 // friend void foo<>(int); 9168 // Go ahead and fake up a template id. 9169 HasExplicitTemplateArgs = true; 9170 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9171 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9172 } 9173 9174 // We do not add HD attributes to specializations here because 9175 // they may have different constexpr-ness compared to their 9176 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9177 // may end up with different effective targets. Instead, a 9178 // specialization inherits its target attributes from its template 9179 // in the CheckFunctionTemplateSpecialization() call below. 9180 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9181 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9182 9183 // If it's a friend (and only if it's a friend), it's possible 9184 // that either the specialized function type or the specialized 9185 // template is dependent, and therefore matching will fail. In 9186 // this case, don't check the specialization yet. 9187 bool InstantiationDependent = false; 9188 if (isFunctionTemplateSpecialization && isFriend && 9189 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9190 TemplateSpecializationType::anyDependentTemplateArguments( 9191 TemplateArgs, 9192 InstantiationDependent))) { 9193 assert(HasExplicitTemplateArgs && 9194 "friend function specialization without template args"); 9195 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9196 Previous)) 9197 NewFD->setInvalidDecl(); 9198 } else if (isFunctionTemplateSpecialization) { 9199 if (CurContext->isDependentContext() && CurContext->isRecord() 9200 && !isFriend) { 9201 isDependentClassScopeExplicitSpecialization = true; 9202 } else if (!NewFD->isInvalidDecl() && 9203 CheckFunctionTemplateSpecialization( 9204 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9205 Previous)) 9206 NewFD->setInvalidDecl(); 9207 9208 // C++ [dcl.stc]p1: 9209 // A storage-class-specifier shall not be specified in an explicit 9210 // specialization (14.7.3) 9211 FunctionTemplateSpecializationInfo *Info = 9212 NewFD->getTemplateSpecializationInfo(); 9213 if (Info && SC != SC_None) { 9214 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9215 Diag(NewFD->getLocation(), 9216 diag::err_explicit_specialization_inconsistent_storage_class) 9217 << SC 9218 << FixItHint::CreateRemoval( 9219 D.getDeclSpec().getStorageClassSpecLoc()); 9220 9221 else 9222 Diag(NewFD->getLocation(), 9223 diag::ext_explicit_specialization_storage_class) 9224 << FixItHint::CreateRemoval( 9225 D.getDeclSpec().getStorageClassSpecLoc()); 9226 } 9227 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9228 if (CheckMemberSpecialization(NewFD, Previous)) 9229 NewFD->setInvalidDecl(); 9230 } 9231 9232 // Perform semantic checking on the function declaration. 9233 if (!isDependentClassScopeExplicitSpecialization) { 9234 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9235 CheckMain(NewFD, D.getDeclSpec()); 9236 9237 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9238 CheckMSVCRTEntryPoint(NewFD); 9239 9240 if (!NewFD->isInvalidDecl()) 9241 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9242 isMemberSpecialization)); 9243 else if (!Previous.empty()) 9244 // Recover gracefully from an invalid redeclaration. 9245 D.setRedeclaration(true); 9246 } 9247 9248 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9249 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9250 "previous declaration set still overloaded"); 9251 9252 NamedDecl *PrincipalDecl = (FunctionTemplate 9253 ? cast<NamedDecl>(FunctionTemplate) 9254 : NewFD); 9255 9256 if (isFriend && NewFD->getPreviousDecl()) { 9257 AccessSpecifier Access = AS_public; 9258 if (!NewFD->isInvalidDecl()) 9259 Access = NewFD->getPreviousDecl()->getAccess(); 9260 9261 NewFD->setAccess(Access); 9262 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9263 } 9264 9265 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9266 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9267 PrincipalDecl->setNonMemberOperator(); 9268 9269 // If we have a function template, check the template parameter 9270 // list. This will check and merge default template arguments. 9271 if (FunctionTemplate) { 9272 FunctionTemplateDecl *PrevTemplate = 9273 FunctionTemplate->getPreviousDecl(); 9274 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9275 PrevTemplate ? PrevTemplate->getTemplateParameters() 9276 : nullptr, 9277 D.getDeclSpec().isFriendSpecified() 9278 ? (D.isFunctionDefinition() 9279 ? TPC_FriendFunctionTemplateDefinition 9280 : TPC_FriendFunctionTemplate) 9281 : (D.getCXXScopeSpec().isSet() && 9282 DC && DC->isRecord() && 9283 DC->isDependentContext()) 9284 ? TPC_ClassTemplateMember 9285 : TPC_FunctionTemplate); 9286 } 9287 9288 if (NewFD->isInvalidDecl()) { 9289 // Ignore all the rest of this. 9290 } else if (!D.isRedeclaration()) { 9291 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9292 AddToScope }; 9293 // Fake up an access specifier if it's supposed to be a class member. 9294 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9295 NewFD->setAccess(AS_public); 9296 9297 // Qualified decls generally require a previous declaration. 9298 if (D.getCXXScopeSpec().isSet()) { 9299 // ...with the major exception of templated-scope or 9300 // dependent-scope friend declarations. 9301 9302 // TODO: we currently also suppress this check in dependent 9303 // contexts because (1) the parameter depth will be off when 9304 // matching friend templates and (2) we might actually be 9305 // selecting a friend based on a dependent factor. But there 9306 // are situations where these conditions don't apply and we 9307 // can actually do this check immediately. 9308 // 9309 // Unless the scope is dependent, it's always an error if qualified 9310 // redeclaration lookup found nothing at all. Diagnose that now; 9311 // nothing will diagnose that error later. 9312 if (isFriend && 9313 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9314 (!Previous.empty() && CurContext->isDependentContext()))) { 9315 // ignore these 9316 } else { 9317 // The user tried to provide an out-of-line definition for a 9318 // function that is a member of a class or namespace, but there 9319 // was no such member function declared (C++ [class.mfct]p2, 9320 // C++ [namespace.memdef]p2). For example: 9321 // 9322 // class X { 9323 // void f() const; 9324 // }; 9325 // 9326 // void X::f() { } // ill-formed 9327 // 9328 // Complain about this problem, and attempt to suggest close 9329 // matches (e.g., those that differ only in cv-qualifiers and 9330 // whether the parameter types are references). 9331 9332 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9333 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9334 AddToScope = ExtraArgs.AddToScope; 9335 return Result; 9336 } 9337 } 9338 9339 // Unqualified local friend declarations are required to resolve 9340 // to something. 9341 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9342 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9343 *this, Previous, NewFD, ExtraArgs, true, S)) { 9344 AddToScope = ExtraArgs.AddToScope; 9345 return Result; 9346 } 9347 } 9348 } else if (!D.isFunctionDefinition() && 9349 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9350 !isFriend && !isFunctionTemplateSpecialization && 9351 !isMemberSpecialization) { 9352 // An out-of-line member function declaration must also be a 9353 // definition (C++ [class.mfct]p2). 9354 // Note that this is not the case for explicit specializations of 9355 // function templates or member functions of class templates, per 9356 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9357 // extension for compatibility with old SWIG code which likes to 9358 // generate them. 9359 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9360 << D.getCXXScopeSpec().getRange(); 9361 } 9362 } 9363 9364 ProcessPragmaWeak(S, NewFD); 9365 checkAttributesAfterMerging(*this, *NewFD); 9366 9367 AddKnownFunctionAttributes(NewFD); 9368 9369 if (NewFD->hasAttr<OverloadableAttr>() && 9370 !NewFD->getType()->getAs<FunctionProtoType>()) { 9371 Diag(NewFD->getLocation(), 9372 diag::err_attribute_overloadable_no_prototype) 9373 << NewFD; 9374 9375 // Turn this into a variadic function with no parameters. 9376 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9377 FunctionProtoType::ExtProtoInfo EPI( 9378 Context.getDefaultCallingConvention(true, false)); 9379 EPI.Variadic = true; 9380 EPI.ExtInfo = FT->getExtInfo(); 9381 9382 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9383 NewFD->setType(R); 9384 } 9385 9386 // If there's a #pragma GCC visibility in scope, and this isn't a class 9387 // member, set the visibility of this function. 9388 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9389 AddPushedVisibilityAttribute(NewFD); 9390 9391 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9392 // marking the function. 9393 AddCFAuditedAttribute(NewFD); 9394 9395 // If this is a function definition, check if we have to apply optnone due to 9396 // a pragma. 9397 if(D.isFunctionDefinition()) 9398 AddRangeBasedOptnone(NewFD); 9399 9400 // If this is the first declaration of an extern C variable, update 9401 // the map of such variables. 9402 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9403 isIncompleteDeclExternC(*this, NewFD)) 9404 RegisterLocallyScopedExternCDecl(NewFD, S); 9405 9406 // Set this FunctionDecl's range up to the right paren. 9407 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9408 9409 if (D.isRedeclaration() && !Previous.empty()) { 9410 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9411 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9412 isMemberSpecialization || 9413 isFunctionTemplateSpecialization, 9414 D.isFunctionDefinition()); 9415 } 9416 9417 if (getLangOpts().CUDA) { 9418 IdentifierInfo *II = NewFD->getIdentifier(); 9419 if (II && II->isStr(getCudaConfigureFuncName()) && 9420 !NewFD->isInvalidDecl() && 9421 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9422 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9423 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9424 << getCudaConfigureFuncName(); 9425 Context.setcudaConfigureCallDecl(NewFD); 9426 } 9427 9428 // Variadic functions, other than a *declaration* of printf, are not allowed 9429 // in device-side CUDA code, unless someone passed 9430 // -fcuda-allow-variadic-functions. 9431 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9432 (NewFD->hasAttr<CUDADeviceAttr>() || 9433 NewFD->hasAttr<CUDAGlobalAttr>()) && 9434 !(II && II->isStr("printf") && NewFD->isExternC() && 9435 !D.isFunctionDefinition())) { 9436 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9437 } 9438 } 9439 9440 MarkUnusedFileScopedDecl(NewFD); 9441 9442 9443 9444 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9445 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9446 if ((getLangOpts().OpenCLVersion >= 120) 9447 && (SC == SC_Static)) { 9448 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9449 D.setInvalidType(); 9450 } 9451 9452 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9453 if (!NewFD->getReturnType()->isVoidType()) { 9454 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9455 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9456 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9457 : FixItHint()); 9458 D.setInvalidType(); 9459 } 9460 9461 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9462 for (auto Param : NewFD->parameters()) 9463 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9464 9465 if (getLangOpts().OpenCLCPlusPlus) { 9466 if (DC->isRecord()) { 9467 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9468 D.setInvalidType(); 9469 } 9470 if (FunctionTemplate) { 9471 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9472 D.setInvalidType(); 9473 } 9474 } 9475 } 9476 9477 if (getLangOpts().CPlusPlus) { 9478 if (FunctionTemplate) { 9479 if (NewFD->isInvalidDecl()) 9480 FunctionTemplate->setInvalidDecl(); 9481 return FunctionTemplate; 9482 } 9483 9484 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9485 CompleteMemberSpecialization(NewFD, Previous); 9486 } 9487 9488 for (const ParmVarDecl *Param : NewFD->parameters()) { 9489 QualType PT = Param->getType(); 9490 9491 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9492 // types. 9493 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9494 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9495 QualType ElemTy = PipeTy->getElementType(); 9496 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9497 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9498 D.setInvalidType(); 9499 } 9500 } 9501 } 9502 } 9503 9504 // Here we have an function template explicit specialization at class scope. 9505 // The actual specialization will be postponed to template instatiation 9506 // time via the ClassScopeFunctionSpecializationDecl node. 9507 if (isDependentClassScopeExplicitSpecialization) { 9508 ClassScopeFunctionSpecializationDecl *NewSpec = 9509 ClassScopeFunctionSpecializationDecl::Create( 9510 Context, CurContext, NewFD->getLocation(), 9511 cast<CXXMethodDecl>(NewFD), 9512 HasExplicitTemplateArgs, TemplateArgs); 9513 CurContext->addDecl(NewSpec); 9514 AddToScope = false; 9515 } 9516 9517 // Diagnose availability attributes. Availability cannot be used on functions 9518 // that are run during load/unload. 9519 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9520 if (NewFD->hasAttr<ConstructorAttr>()) { 9521 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9522 << 1; 9523 NewFD->dropAttr<AvailabilityAttr>(); 9524 } 9525 if (NewFD->hasAttr<DestructorAttr>()) { 9526 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9527 << 2; 9528 NewFD->dropAttr<AvailabilityAttr>(); 9529 } 9530 } 9531 9532 // Diagnose no_builtin attribute on function declaration that are not a 9533 // definition. 9534 // FIXME: We should really be doing this in 9535 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9536 // the FunctionDecl and at this point of the code 9537 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9538 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9539 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9540 switch (D.getFunctionDefinitionKind()) { 9541 case FDK_Defaulted: 9542 case FDK_Deleted: 9543 Diag(NBA->getLocation(), 9544 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9545 << NBA->getSpelling(); 9546 break; 9547 case FDK_Declaration: 9548 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9549 << NBA->getSpelling(); 9550 break; 9551 case FDK_Definition: 9552 break; 9553 } 9554 9555 return NewFD; 9556 } 9557 9558 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9559 /// when __declspec(code_seg) "is applied to a class, all member functions of 9560 /// the class and nested classes -- this includes compiler-generated special 9561 /// member functions -- are put in the specified segment." 9562 /// The actual behavior is a little more complicated. The Microsoft compiler 9563 /// won't check outer classes if there is an active value from #pragma code_seg. 9564 /// The CodeSeg is always applied from the direct parent but only from outer 9565 /// classes when the #pragma code_seg stack is empty. See: 9566 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9567 /// available since MS has removed the page. 9568 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9569 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9570 if (!Method) 9571 return nullptr; 9572 const CXXRecordDecl *Parent = Method->getParent(); 9573 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9574 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9575 NewAttr->setImplicit(true); 9576 return NewAttr; 9577 } 9578 9579 // The Microsoft compiler won't check outer classes for the CodeSeg 9580 // when the #pragma code_seg stack is active. 9581 if (S.CodeSegStack.CurrentValue) 9582 return nullptr; 9583 9584 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9585 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9586 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9587 NewAttr->setImplicit(true); 9588 return NewAttr; 9589 } 9590 } 9591 return nullptr; 9592 } 9593 9594 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9595 /// containing class. Otherwise it will return implicit SectionAttr if the 9596 /// function is a definition and there is an active value on CodeSegStack 9597 /// (from the current #pragma code-seg value). 9598 /// 9599 /// \param FD Function being declared. 9600 /// \param IsDefinition Whether it is a definition or just a declarartion. 9601 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9602 /// nullptr if no attribute should be added. 9603 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9604 bool IsDefinition) { 9605 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9606 return A; 9607 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9608 CodeSegStack.CurrentValue) 9609 return SectionAttr::CreateImplicit( 9610 getASTContext(), CodeSegStack.CurrentValue->getString(), 9611 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9612 SectionAttr::Declspec_allocate); 9613 return nullptr; 9614 } 9615 9616 /// Determines if we can perform a correct type check for \p D as a 9617 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9618 /// best-effort check. 9619 /// 9620 /// \param NewD The new declaration. 9621 /// \param OldD The old declaration. 9622 /// \param NewT The portion of the type of the new declaration to check. 9623 /// \param OldT The portion of the type of the old declaration to check. 9624 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9625 QualType NewT, QualType OldT) { 9626 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9627 return true; 9628 9629 // For dependently-typed local extern declarations and friends, we can't 9630 // perform a correct type check in general until instantiation: 9631 // 9632 // int f(); 9633 // template<typename T> void g() { T f(); } 9634 // 9635 // (valid if g() is only instantiated with T = int). 9636 if (NewT->isDependentType() && 9637 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9638 return false; 9639 9640 // Similarly, if the previous declaration was a dependent local extern 9641 // declaration, we don't really know its type yet. 9642 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9643 return false; 9644 9645 return true; 9646 } 9647 9648 /// Checks if the new declaration declared in dependent context must be 9649 /// put in the same redeclaration chain as the specified declaration. 9650 /// 9651 /// \param D Declaration that is checked. 9652 /// \param PrevDecl Previous declaration found with proper lookup method for the 9653 /// same declaration name. 9654 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9655 /// belongs to. 9656 /// 9657 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9658 if (!D->getLexicalDeclContext()->isDependentContext()) 9659 return true; 9660 9661 // Don't chain dependent friend function definitions until instantiation, to 9662 // permit cases like 9663 // 9664 // void func(); 9665 // template<typename T> class C1 { friend void func() {} }; 9666 // template<typename T> class C2 { friend void func() {} }; 9667 // 9668 // ... which is valid if only one of C1 and C2 is ever instantiated. 9669 // 9670 // FIXME: This need only apply to function definitions. For now, we proxy 9671 // this by checking for a file-scope function. We do not want this to apply 9672 // to friend declarations nominating member functions, because that gets in 9673 // the way of access checks. 9674 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9675 return false; 9676 9677 auto *VD = dyn_cast<ValueDecl>(D); 9678 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9679 return !VD || !PrevVD || 9680 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9681 PrevVD->getType()); 9682 } 9683 9684 /// Check the target attribute of the function for MultiVersion 9685 /// validity. 9686 /// 9687 /// Returns true if there was an error, false otherwise. 9688 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9689 const auto *TA = FD->getAttr<TargetAttr>(); 9690 assert(TA && "MultiVersion Candidate requires a target attribute"); 9691 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9692 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9693 enum ErrType { Feature = 0, Architecture = 1 }; 9694 9695 if (!ParseInfo.Architecture.empty() && 9696 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9697 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9698 << Architecture << ParseInfo.Architecture; 9699 return true; 9700 } 9701 9702 for (const auto &Feat : ParseInfo.Features) { 9703 auto BareFeat = StringRef{Feat}.substr(1); 9704 if (Feat[0] == '-') { 9705 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9706 << Feature << ("no-" + BareFeat).str(); 9707 return true; 9708 } 9709 9710 if (!TargetInfo.validateCpuSupports(BareFeat) || 9711 !TargetInfo.isValidFeatureName(BareFeat)) { 9712 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9713 << Feature << BareFeat; 9714 return true; 9715 } 9716 } 9717 return false; 9718 } 9719 9720 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9721 MultiVersionKind MVType) { 9722 for (const Attr *A : FD->attrs()) { 9723 switch (A->getKind()) { 9724 case attr::CPUDispatch: 9725 case attr::CPUSpecific: 9726 if (MVType != MultiVersionKind::CPUDispatch && 9727 MVType != MultiVersionKind::CPUSpecific) 9728 return true; 9729 break; 9730 case attr::Target: 9731 if (MVType != MultiVersionKind::Target) 9732 return true; 9733 break; 9734 default: 9735 return true; 9736 } 9737 } 9738 return false; 9739 } 9740 9741 bool Sema::areMultiversionVariantFunctionsCompatible( 9742 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9743 const PartialDiagnostic &NoProtoDiagID, 9744 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9745 const PartialDiagnosticAt &NoSupportDiagIDAt, 9746 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9747 bool ConstexprSupported, bool CLinkageMayDiffer) { 9748 enum DoesntSupport { 9749 FuncTemplates = 0, 9750 VirtFuncs = 1, 9751 DeducedReturn = 2, 9752 Constructors = 3, 9753 Destructors = 4, 9754 DeletedFuncs = 5, 9755 DefaultedFuncs = 6, 9756 ConstexprFuncs = 7, 9757 ConstevalFuncs = 8, 9758 }; 9759 enum Different { 9760 CallingConv = 0, 9761 ReturnType = 1, 9762 ConstexprSpec = 2, 9763 InlineSpec = 3, 9764 StorageClass = 4, 9765 Linkage = 5, 9766 }; 9767 9768 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9769 Diag(OldFD->getLocation(), NoProtoDiagID); 9770 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 9771 return true; 9772 } 9773 9774 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9775 return Diag(NewFD->getLocation(), NoProtoDiagID); 9776 9777 if (!TemplatesSupported && 9778 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9779 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9780 << FuncTemplates; 9781 9782 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9783 if (NewCXXFD->isVirtual()) 9784 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9785 << VirtFuncs; 9786 9787 if (isa<CXXConstructorDecl>(NewCXXFD)) 9788 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9789 << Constructors; 9790 9791 if (isa<CXXDestructorDecl>(NewCXXFD)) 9792 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9793 << Destructors; 9794 } 9795 9796 if (NewFD->isDeleted()) 9797 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9798 << DeletedFuncs; 9799 9800 if (NewFD->isDefaulted()) 9801 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9802 << DefaultedFuncs; 9803 9804 if (!ConstexprSupported && NewFD->isConstexpr()) 9805 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9806 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 9807 9808 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 9809 const auto *NewType = cast<FunctionType>(NewQType); 9810 QualType NewReturnType = NewType->getReturnType(); 9811 9812 if (NewReturnType->isUndeducedType()) 9813 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9814 << DeducedReturn; 9815 9816 // Ensure the return type is identical. 9817 if (OldFD) { 9818 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 9819 const auto *OldType = cast<FunctionType>(OldQType); 9820 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9821 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9822 9823 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9824 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 9825 9826 QualType OldReturnType = OldType->getReturnType(); 9827 9828 if (OldReturnType != NewReturnType) 9829 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 9830 9831 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 9832 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 9833 9834 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9835 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 9836 9837 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9838 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 9839 9840 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 9841 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 9842 9843 if (CheckEquivalentExceptionSpec( 9844 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9845 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9846 return true; 9847 } 9848 return false; 9849 } 9850 9851 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9852 const FunctionDecl *NewFD, 9853 bool CausesMV, 9854 MultiVersionKind MVType) { 9855 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9856 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9857 if (OldFD) 9858 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9859 return true; 9860 } 9861 9862 bool IsCPUSpecificCPUDispatchMVType = 9863 MVType == MultiVersionKind::CPUDispatch || 9864 MVType == MultiVersionKind::CPUSpecific; 9865 9866 // For now, disallow all other attributes. These should be opt-in, but 9867 // an analysis of all of them is a future FIXME. 9868 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9869 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9870 << IsCPUSpecificCPUDispatchMVType; 9871 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9872 return true; 9873 } 9874 9875 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9876 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9877 << IsCPUSpecificCPUDispatchMVType; 9878 9879 // Only allow transition to MultiVersion if it hasn't been used. 9880 if (OldFD && CausesMV && OldFD->isUsed(false)) 9881 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9882 9883 return S.areMultiversionVariantFunctionsCompatible( 9884 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 9885 PartialDiagnosticAt(NewFD->getLocation(), 9886 S.PDiag(diag::note_multiversioning_caused_here)), 9887 PartialDiagnosticAt(NewFD->getLocation(), 9888 S.PDiag(diag::err_multiversion_doesnt_support) 9889 << IsCPUSpecificCPUDispatchMVType), 9890 PartialDiagnosticAt(NewFD->getLocation(), 9891 S.PDiag(diag::err_multiversion_diff)), 9892 /*TemplatesSupported=*/false, 9893 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 9894 /*CLinkageMayDiffer=*/false); 9895 } 9896 9897 /// Check the validity of a multiversion function declaration that is the 9898 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9899 /// 9900 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9901 /// 9902 /// Returns true if there was an error, false otherwise. 9903 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9904 MultiVersionKind MVType, 9905 const TargetAttr *TA) { 9906 assert(MVType != MultiVersionKind::None && 9907 "Function lacks multiversion attribute"); 9908 9909 // Target only causes MV if it is default, otherwise this is a normal 9910 // function. 9911 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9912 return false; 9913 9914 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9915 FD->setInvalidDecl(); 9916 return true; 9917 } 9918 9919 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9920 FD->setInvalidDecl(); 9921 return true; 9922 } 9923 9924 FD->setIsMultiVersion(); 9925 return false; 9926 } 9927 9928 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9929 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9930 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9931 return true; 9932 } 9933 9934 return false; 9935 } 9936 9937 static bool CheckTargetCausesMultiVersioning( 9938 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9939 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9940 LookupResult &Previous) { 9941 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9942 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9943 // Sort order doesn't matter, it just needs to be consistent. 9944 llvm::sort(NewParsed.Features); 9945 9946 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9947 // to change, this is a simple redeclaration. 9948 if (!NewTA->isDefaultVersion() && 9949 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9950 return false; 9951 9952 // Otherwise, this decl causes MultiVersioning. 9953 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9954 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9955 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9956 NewFD->setInvalidDecl(); 9957 return true; 9958 } 9959 9960 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9961 MultiVersionKind::Target)) { 9962 NewFD->setInvalidDecl(); 9963 return true; 9964 } 9965 9966 if (CheckMultiVersionValue(S, NewFD)) { 9967 NewFD->setInvalidDecl(); 9968 return true; 9969 } 9970 9971 // If this is 'default', permit the forward declaration. 9972 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9973 Redeclaration = true; 9974 OldDecl = OldFD; 9975 OldFD->setIsMultiVersion(); 9976 NewFD->setIsMultiVersion(); 9977 return false; 9978 } 9979 9980 if (CheckMultiVersionValue(S, OldFD)) { 9981 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9982 NewFD->setInvalidDecl(); 9983 return true; 9984 } 9985 9986 TargetAttr::ParsedTargetAttr OldParsed = 9987 OldTA->parse(std::less<std::string>()); 9988 9989 if (OldParsed == NewParsed) { 9990 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9991 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9992 NewFD->setInvalidDecl(); 9993 return true; 9994 } 9995 9996 for (const auto *FD : OldFD->redecls()) { 9997 const auto *CurTA = FD->getAttr<TargetAttr>(); 9998 // We allow forward declarations before ANY multiversioning attributes, but 9999 // nothing after the fact. 10000 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10001 (!CurTA || CurTA->isInherited())) { 10002 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10003 << 0; 10004 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10005 NewFD->setInvalidDecl(); 10006 return true; 10007 } 10008 } 10009 10010 OldFD->setIsMultiVersion(); 10011 NewFD->setIsMultiVersion(); 10012 Redeclaration = false; 10013 MergeTypeWithPrevious = false; 10014 OldDecl = nullptr; 10015 Previous.clear(); 10016 return false; 10017 } 10018 10019 /// Check the validity of a new function declaration being added to an existing 10020 /// multiversioned declaration collection. 10021 static bool CheckMultiVersionAdditionalDecl( 10022 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10023 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10024 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10025 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10026 LookupResult &Previous) { 10027 10028 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10029 // Disallow mixing of multiversioning types. 10030 if ((OldMVType == MultiVersionKind::Target && 10031 NewMVType != MultiVersionKind::Target) || 10032 (NewMVType == MultiVersionKind::Target && 10033 OldMVType != MultiVersionKind::Target)) { 10034 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10035 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10036 NewFD->setInvalidDecl(); 10037 return true; 10038 } 10039 10040 TargetAttr::ParsedTargetAttr NewParsed; 10041 if (NewTA) { 10042 NewParsed = NewTA->parse(); 10043 llvm::sort(NewParsed.Features); 10044 } 10045 10046 bool UseMemberUsingDeclRules = 10047 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10048 10049 // Next, check ALL non-overloads to see if this is a redeclaration of a 10050 // previous member of the MultiVersion set. 10051 for (NamedDecl *ND : Previous) { 10052 FunctionDecl *CurFD = ND->getAsFunction(); 10053 if (!CurFD) 10054 continue; 10055 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10056 continue; 10057 10058 if (NewMVType == MultiVersionKind::Target) { 10059 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10060 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10061 NewFD->setIsMultiVersion(); 10062 Redeclaration = true; 10063 OldDecl = ND; 10064 return false; 10065 } 10066 10067 TargetAttr::ParsedTargetAttr CurParsed = 10068 CurTA->parse(std::less<std::string>()); 10069 if (CurParsed == NewParsed) { 10070 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10071 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10072 NewFD->setInvalidDecl(); 10073 return true; 10074 } 10075 } else { 10076 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10077 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10078 // Handle CPUDispatch/CPUSpecific versions. 10079 // Only 1 CPUDispatch function is allowed, this will make it go through 10080 // the redeclaration errors. 10081 if (NewMVType == MultiVersionKind::CPUDispatch && 10082 CurFD->hasAttr<CPUDispatchAttr>()) { 10083 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10084 std::equal( 10085 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10086 NewCPUDisp->cpus_begin(), 10087 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10088 return Cur->getName() == New->getName(); 10089 })) { 10090 NewFD->setIsMultiVersion(); 10091 Redeclaration = true; 10092 OldDecl = ND; 10093 return false; 10094 } 10095 10096 // If the declarations don't match, this is an error condition. 10097 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10098 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10099 NewFD->setInvalidDecl(); 10100 return true; 10101 } 10102 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10103 10104 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10105 std::equal( 10106 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10107 NewCPUSpec->cpus_begin(), 10108 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10109 return Cur->getName() == New->getName(); 10110 })) { 10111 NewFD->setIsMultiVersion(); 10112 Redeclaration = true; 10113 OldDecl = ND; 10114 return false; 10115 } 10116 10117 // Only 1 version of CPUSpecific is allowed for each CPU. 10118 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10119 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10120 if (CurII == NewII) { 10121 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10122 << NewII; 10123 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10124 NewFD->setInvalidDecl(); 10125 return true; 10126 } 10127 } 10128 } 10129 } 10130 // If the two decls aren't the same MVType, there is no possible error 10131 // condition. 10132 } 10133 } 10134 10135 // Else, this is simply a non-redecl case. Checking the 'value' is only 10136 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10137 // handled in the attribute adding step. 10138 if (NewMVType == MultiVersionKind::Target && 10139 CheckMultiVersionValue(S, NewFD)) { 10140 NewFD->setInvalidDecl(); 10141 return true; 10142 } 10143 10144 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10145 !OldFD->isMultiVersion(), NewMVType)) { 10146 NewFD->setInvalidDecl(); 10147 return true; 10148 } 10149 10150 // Permit forward declarations in the case where these two are compatible. 10151 if (!OldFD->isMultiVersion()) { 10152 OldFD->setIsMultiVersion(); 10153 NewFD->setIsMultiVersion(); 10154 Redeclaration = true; 10155 OldDecl = OldFD; 10156 return false; 10157 } 10158 10159 NewFD->setIsMultiVersion(); 10160 Redeclaration = false; 10161 MergeTypeWithPrevious = false; 10162 OldDecl = nullptr; 10163 Previous.clear(); 10164 return false; 10165 } 10166 10167 10168 /// Check the validity of a mulitversion function declaration. 10169 /// Also sets the multiversion'ness' of the function itself. 10170 /// 10171 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10172 /// 10173 /// Returns true if there was an error, false otherwise. 10174 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10175 bool &Redeclaration, NamedDecl *&OldDecl, 10176 bool &MergeTypeWithPrevious, 10177 LookupResult &Previous) { 10178 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10179 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10180 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10181 10182 // Mixing Multiversioning types is prohibited. 10183 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10184 (NewCPUDisp && NewCPUSpec)) { 10185 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10186 NewFD->setInvalidDecl(); 10187 return true; 10188 } 10189 10190 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10191 10192 // Main isn't allowed to become a multiversion function, however it IS 10193 // permitted to have 'main' be marked with the 'target' optimization hint. 10194 if (NewFD->isMain()) { 10195 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10196 MVType == MultiVersionKind::CPUDispatch || 10197 MVType == MultiVersionKind::CPUSpecific) { 10198 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10199 NewFD->setInvalidDecl(); 10200 return true; 10201 } 10202 return false; 10203 } 10204 10205 if (!OldDecl || !OldDecl->getAsFunction() || 10206 OldDecl->getDeclContext()->getRedeclContext() != 10207 NewFD->getDeclContext()->getRedeclContext()) { 10208 // If there's no previous declaration, AND this isn't attempting to cause 10209 // multiversioning, this isn't an error condition. 10210 if (MVType == MultiVersionKind::None) 10211 return false; 10212 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10213 } 10214 10215 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10216 10217 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10218 return false; 10219 10220 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10221 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10222 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10223 NewFD->setInvalidDecl(); 10224 return true; 10225 } 10226 10227 // Handle the target potentially causes multiversioning case. 10228 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10229 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10230 Redeclaration, OldDecl, 10231 MergeTypeWithPrevious, Previous); 10232 10233 // At this point, we have a multiversion function decl (in OldFD) AND an 10234 // appropriate attribute in the current function decl. Resolve that these are 10235 // still compatible with previous declarations. 10236 return CheckMultiVersionAdditionalDecl( 10237 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10238 OldDecl, MergeTypeWithPrevious, Previous); 10239 } 10240 10241 /// Perform semantic checking of a new function declaration. 10242 /// 10243 /// Performs semantic analysis of the new function declaration 10244 /// NewFD. This routine performs all semantic checking that does not 10245 /// require the actual declarator involved in the declaration, and is 10246 /// used both for the declaration of functions as they are parsed 10247 /// (called via ActOnDeclarator) and for the declaration of functions 10248 /// that have been instantiated via C++ template instantiation (called 10249 /// via InstantiateDecl). 10250 /// 10251 /// \param IsMemberSpecialization whether this new function declaration is 10252 /// a member specialization (that replaces any definition provided by the 10253 /// previous declaration). 10254 /// 10255 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10256 /// 10257 /// \returns true if the function declaration is a redeclaration. 10258 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10259 LookupResult &Previous, 10260 bool IsMemberSpecialization) { 10261 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10262 "Variably modified return types are not handled here"); 10263 10264 // Determine whether the type of this function should be merged with 10265 // a previous visible declaration. This never happens for functions in C++, 10266 // and always happens in C if the previous declaration was visible. 10267 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10268 !Previous.isShadowed(); 10269 10270 bool Redeclaration = false; 10271 NamedDecl *OldDecl = nullptr; 10272 bool MayNeedOverloadableChecks = false; 10273 10274 // Merge or overload the declaration with an existing declaration of 10275 // the same name, if appropriate. 10276 if (!Previous.empty()) { 10277 // Determine whether NewFD is an overload of PrevDecl or 10278 // a declaration that requires merging. If it's an overload, 10279 // there's no more work to do here; we'll just add the new 10280 // function to the scope. 10281 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10282 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10283 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10284 Redeclaration = true; 10285 OldDecl = Candidate; 10286 } 10287 } else { 10288 MayNeedOverloadableChecks = true; 10289 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10290 /*NewIsUsingDecl*/ false)) { 10291 case Ovl_Match: 10292 Redeclaration = true; 10293 break; 10294 10295 case Ovl_NonFunction: 10296 Redeclaration = true; 10297 break; 10298 10299 case Ovl_Overload: 10300 Redeclaration = false; 10301 break; 10302 } 10303 } 10304 } 10305 10306 // Check for a previous extern "C" declaration with this name. 10307 if (!Redeclaration && 10308 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10309 if (!Previous.empty()) { 10310 // This is an extern "C" declaration with the same name as a previous 10311 // declaration, and thus redeclares that entity... 10312 Redeclaration = true; 10313 OldDecl = Previous.getFoundDecl(); 10314 MergeTypeWithPrevious = false; 10315 10316 // ... except in the presence of __attribute__((overloadable)). 10317 if (OldDecl->hasAttr<OverloadableAttr>() || 10318 NewFD->hasAttr<OverloadableAttr>()) { 10319 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10320 MayNeedOverloadableChecks = true; 10321 Redeclaration = false; 10322 OldDecl = nullptr; 10323 } 10324 } 10325 } 10326 } 10327 10328 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10329 MergeTypeWithPrevious, Previous)) 10330 return Redeclaration; 10331 10332 // C++11 [dcl.constexpr]p8: 10333 // A constexpr specifier for a non-static member function that is not 10334 // a constructor declares that member function to be const. 10335 // 10336 // This needs to be delayed until we know whether this is an out-of-line 10337 // definition of a static member function. 10338 // 10339 // This rule is not present in C++1y, so we produce a backwards 10340 // compatibility warning whenever it happens in C++11. 10341 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10342 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10343 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10344 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10345 CXXMethodDecl *OldMD = nullptr; 10346 if (OldDecl) 10347 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10348 if (!OldMD || !OldMD->isStatic()) { 10349 const FunctionProtoType *FPT = 10350 MD->getType()->castAs<FunctionProtoType>(); 10351 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10352 EPI.TypeQuals.addConst(); 10353 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10354 FPT->getParamTypes(), EPI)); 10355 10356 // Warn that we did this, if we're not performing template instantiation. 10357 // In that case, we'll have warned already when the template was defined. 10358 if (!inTemplateInstantiation()) { 10359 SourceLocation AddConstLoc; 10360 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10361 .IgnoreParens().getAs<FunctionTypeLoc>()) 10362 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10363 10364 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10365 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10366 } 10367 } 10368 } 10369 10370 if (Redeclaration) { 10371 // NewFD and OldDecl represent declarations that need to be 10372 // merged. 10373 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10374 NewFD->setInvalidDecl(); 10375 return Redeclaration; 10376 } 10377 10378 Previous.clear(); 10379 Previous.addDecl(OldDecl); 10380 10381 if (FunctionTemplateDecl *OldTemplateDecl = 10382 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10383 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10384 FunctionTemplateDecl *NewTemplateDecl 10385 = NewFD->getDescribedFunctionTemplate(); 10386 assert(NewTemplateDecl && "Template/non-template mismatch"); 10387 10388 // The call to MergeFunctionDecl above may have created some state in 10389 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10390 // can add it as a redeclaration. 10391 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10392 10393 NewFD->setPreviousDeclaration(OldFD); 10394 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10395 if (NewFD->isCXXClassMember()) { 10396 NewFD->setAccess(OldTemplateDecl->getAccess()); 10397 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10398 } 10399 10400 // If this is an explicit specialization of a member that is a function 10401 // template, mark it as a member specialization. 10402 if (IsMemberSpecialization && 10403 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10404 NewTemplateDecl->setMemberSpecialization(); 10405 assert(OldTemplateDecl->isMemberSpecialization()); 10406 // Explicit specializations of a member template do not inherit deleted 10407 // status from the parent member template that they are specializing. 10408 if (OldFD->isDeleted()) { 10409 // FIXME: This assert will not hold in the presence of modules. 10410 assert(OldFD->getCanonicalDecl() == OldFD); 10411 // FIXME: We need an update record for this AST mutation. 10412 OldFD->setDeletedAsWritten(false); 10413 } 10414 } 10415 10416 } else { 10417 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10418 auto *OldFD = cast<FunctionDecl>(OldDecl); 10419 // This needs to happen first so that 'inline' propagates. 10420 NewFD->setPreviousDeclaration(OldFD); 10421 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10422 if (NewFD->isCXXClassMember()) 10423 NewFD->setAccess(OldFD->getAccess()); 10424 } 10425 } 10426 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10427 !NewFD->getAttr<OverloadableAttr>()) { 10428 assert((Previous.empty() || 10429 llvm::any_of(Previous, 10430 [](const NamedDecl *ND) { 10431 return ND->hasAttr<OverloadableAttr>(); 10432 })) && 10433 "Non-redecls shouldn't happen without overloadable present"); 10434 10435 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10436 const auto *FD = dyn_cast<FunctionDecl>(ND); 10437 return FD && !FD->hasAttr<OverloadableAttr>(); 10438 }); 10439 10440 if (OtherUnmarkedIter != Previous.end()) { 10441 Diag(NewFD->getLocation(), 10442 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10443 Diag((*OtherUnmarkedIter)->getLocation(), 10444 diag::note_attribute_overloadable_prev_overload) 10445 << false; 10446 10447 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10448 } 10449 } 10450 10451 // Semantic checking for this function declaration (in isolation). 10452 10453 if (getLangOpts().CPlusPlus) { 10454 // C++-specific checks. 10455 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10456 CheckConstructor(Constructor); 10457 } else if (CXXDestructorDecl *Destructor = 10458 dyn_cast<CXXDestructorDecl>(NewFD)) { 10459 CXXRecordDecl *Record = Destructor->getParent(); 10460 QualType ClassType = Context.getTypeDeclType(Record); 10461 10462 // FIXME: Shouldn't we be able to perform this check even when the class 10463 // type is dependent? Both gcc and edg can handle that. 10464 if (!ClassType->isDependentType()) { 10465 DeclarationName Name 10466 = Context.DeclarationNames.getCXXDestructorName( 10467 Context.getCanonicalType(ClassType)); 10468 if (NewFD->getDeclName() != Name) { 10469 Diag(NewFD->getLocation(), diag::err_destructor_name); 10470 NewFD->setInvalidDecl(); 10471 return Redeclaration; 10472 } 10473 } 10474 } else if (CXXConversionDecl *Conversion 10475 = dyn_cast<CXXConversionDecl>(NewFD)) { 10476 ActOnConversionDeclarator(Conversion); 10477 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10478 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10479 CheckDeductionGuideTemplate(TD); 10480 10481 // A deduction guide is not on the list of entities that can be 10482 // explicitly specialized. 10483 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10484 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10485 << /*explicit specialization*/ 1; 10486 } 10487 10488 // Find any virtual functions that this function overrides. 10489 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10490 if (!Method->isFunctionTemplateSpecialization() && 10491 !Method->getDescribedFunctionTemplate() && 10492 Method->isCanonicalDecl()) { 10493 if (AddOverriddenMethods(Method->getParent(), Method)) { 10494 // If the function was marked as "static", we have a problem. 10495 if (NewFD->getStorageClass() == SC_Static) { 10496 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10497 } 10498 } 10499 } 10500 10501 if (Method->isStatic()) 10502 checkThisInStaticMemberFunctionType(Method); 10503 } 10504 10505 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10506 if (NewFD->isOverloadedOperator() && 10507 CheckOverloadedOperatorDeclaration(NewFD)) { 10508 NewFD->setInvalidDecl(); 10509 return Redeclaration; 10510 } 10511 10512 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10513 if (NewFD->getLiteralIdentifier() && 10514 CheckLiteralOperatorDeclaration(NewFD)) { 10515 NewFD->setInvalidDecl(); 10516 return Redeclaration; 10517 } 10518 10519 // In C++, check default arguments now that we have merged decls. Unless 10520 // the lexical context is the class, because in this case this is done 10521 // during delayed parsing anyway. 10522 if (!CurContext->isRecord()) 10523 CheckCXXDefaultArguments(NewFD); 10524 10525 // If this function declares a builtin function, check the type of this 10526 // declaration against the expected type for the builtin. 10527 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10528 ASTContext::GetBuiltinTypeError Error; 10529 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10530 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10531 // If the type of the builtin differs only in its exception 10532 // specification, that's OK. 10533 // FIXME: If the types do differ in this way, it would be better to 10534 // retain the 'noexcept' form of the type. 10535 if (!T.isNull() && 10536 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10537 NewFD->getType())) 10538 // The type of this function differs from the type of the builtin, 10539 // so forget about the builtin entirely. 10540 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10541 } 10542 10543 // If this function is declared as being extern "C", then check to see if 10544 // the function returns a UDT (class, struct, or union type) that is not C 10545 // compatible, and if it does, warn the user. 10546 // But, issue any diagnostic on the first declaration only. 10547 if (Previous.empty() && NewFD->isExternC()) { 10548 QualType R = NewFD->getReturnType(); 10549 if (R->isIncompleteType() && !R->isVoidType()) 10550 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10551 << NewFD << R; 10552 else if (!R.isPODType(Context) && !R->isVoidType() && 10553 !R->isObjCObjectPointerType()) 10554 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10555 } 10556 10557 // C++1z [dcl.fct]p6: 10558 // [...] whether the function has a non-throwing exception-specification 10559 // [is] part of the function type 10560 // 10561 // This results in an ABI break between C++14 and C++17 for functions whose 10562 // declared type includes an exception-specification in a parameter or 10563 // return type. (Exception specifications on the function itself are OK in 10564 // most cases, and exception specifications are not permitted in most other 10565 // contexts where they could make it into a mangling.) 10566 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10567 auto HasNoexcept = [&](QualType T) -> bool { 10568 // Strip off declarator chunks that could be between us and a function 10569 // type. We don't need to look far, exception specifications are very 10570 // restricted prior to C++17. 10571 if (auto *RT = T->getAs<ReferenceType>()) 10572 T = RT->getPointeeType(); 10573 else if (T->isAnyPointerType()) 10574 T = T->getPointeeType(); 10575 else if (auto *MPT = T->getAs<MemberPointerType>()) 10576 T = MPT->getPointeeType(); 10577 if (auto *FPT = T->getAs<FunctionProtoType>()) 10578 if (FPT->isNothrow()) 10579 return true; 10580 return false; 10581 }; 10582 10583 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10584 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10585 for (QualType T : FPT->param_types()) 10586 AnyNoexcept |= HasNoexcept(T); 10587 if (AnyNoexcept) 10588 Diag(NewFD->getLocation(), 10589 diag::warn_cxx17_compat_exception_spec_in_signature) 10590 << NewFD; 10591 } 10592 10593 if (!Redeclaration && LangOpts.CUDA) 10594 checkCUDATargetOverload(NewFD, Previous); 10595 } 10596 return Redeclaration; 10597 } 10598 10599 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10600 // C++11 [basic.start.main]p3: 10601 // A program that [...] declares main to be inline, static or 10602 // constexpr is ill-formed. 10603 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10604 // appear in a declaration of main. 10605 // static main is not an error under C99, but we should warn about it. 10606 // We accept _Noreturn main as an extension. 10607 if (FD->getStorageClass() == SC_Static) 10608 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10609 ? diag::err_static_main : diag::warn_static_main) 10610 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10611 if (FD->isInlineSpecified()) 10612 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10613 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10614 if (DS.isNoreturnSpecified()) { 10615 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10616 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10617 Diag(NoreturnLoc, diag::ext_noreturn_main); 10618 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10619 << FixItHint::CreateRemoval(NoreturnRange); 10620 } 10621 if (FD->isConstexpr()) { 10622 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10623 << FD->isConsteval() 10624 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10625 FD->setConstexprKind(CSK_unspecified); 10626 } 10627 10628 if (getLangOpts().OpenCL) { 10629 Diag(FD->getLocation(), diag::err_opencl_no_main) 10630 << FD->hasAttr<OpenCLKernelAttr>(); 10631 FD->setInvalidDecl(); 10632 return; 10633 } 10634 10635 QualType T = FD->getType(); 10636 assert(T->isFunctionType() && "function decl is not of function type"); 10637 const FunctionType* FT = T->castAs<FunctionType>(); 10638 10639 // Set default calling convention for main() 10640 if (FT->getCallConv() != CC_C) { 10641 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10642 FD->setType(QualType(FT, 0)); 10643 T = Context.getCanonicalType(FD->getType()); 10644 } 10645 10646 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10647 // In C with GNU extensions we allow main() to have non-integer return 10648 // type, but we should warn about the extension, and we disable the 10649 // implicit-return-zero rule. 10650 10651 // GCC in C mode accepts qualified 'int'. 10652 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10653 FD->setHasImplicitReturnZero(true); 10654 else { 10655 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10656 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10657 if (RTRange.isValid()) 10658 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10659 << FixItHint::CreateReplacement(RTRange, "int"); 10660 } 10661 } else { 10662 // In C and C++, main magically returns 0 if you fall off the end; 10663 // set the flag which tells us that. 10664 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10665 10666 // All the standards say that main() should return 'int'. 10667 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10668 FD->setHasImplicitReturnZero(true); 10669 else { 10670 // Otherwise, this is just a flat-out error. 10671 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10672 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10673 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10674 : FixItHint()); 10675 FD->setInvalidDecl(true); 10676 } 10677 } 10678 10679 // Treat protoless main() as nullary. 10680 if (isa<FunctionNoProtoType>(FT)) return; 10681 10682 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10683 unsigned nparams = FTP->getNumParams(); 10684 assert(FD->getNumParams() == nparams); 10685 10686 bool HasExtraParameters = (nparams > 3); 10687 10688 if (FTP->isVariadic()) { 10689 Diag(FD->getLocation(), diag::ext_variadic_main); 10690 // FIXME: if we had information about the location of the ellipsis, we 10691 // could add a FixIt hint to remove it as a parameter. 10692 } 10693 10694 // Darwin passes an undocumented fourth argument of type char**. If 10695 // other platforms start sprouting these, the logic below will start 10696 // getting shifty. 10697 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10698 HasExtraParameters = false; 10699 10700 if (HasExtraParameters) { 10701 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10702 FD->setInvalidDecl(true); 10703 nparams = 3; 10704 } 10705 10706 // FIXME: a lot of the following diagnostics would be improved 10707 // if we had some location information about types. 10708 10709 QualType CharPP = 10710 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10711 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10712 10713 for (unsigned i = 0; i < nparams; ++i) { 10714 QualType AT = FTP->getParamType(i); 10715 10716 bool mismatch = true; 10717 10718 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10719 mismatch = false; 10720 else if (Expected[i] == CharPP) { 10721 // As an extension, the following forms are okay: 10722 // char const ** 10723 // char const * const * 10724 // char * const * 10725 10726 QualifierCollector qs; 10727 const PointerType* PT; 10728 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10729 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10730 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10731 Context.CharTy)) { 10732 qs.removeConst(); 10733 mismatch = !qs.empty(); 10734 } 10735 } 10736 10737 if (mismatch) { 10738 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10739 // TODO: suggest replacing given type with expected type 10740 FD->setInvalidDecl(true); 10741 } 10742 } 10743 10744 if (nparams == 1 && !FD->isInvalidDecl()) { 10745 Diag(FD->getLocation(), diag::warn_main_one_arg); 10746 } 10747 10748 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10749 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10750 FD->setInvalidDecl(); 10751 } 10752 } 10753 10754 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10755 QualType T = FD->getType(); 10756 assert(T->isFunctionType() && "function decl is not of function type"); 10757 const FunctionType *FT = T->castAs<FunctionType>(); 10758 10759 // Set an implicit return of 'zero' if the function can return some integral, 10760 // enumeration, pointer or nullptr type. 10761 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10762 FT->getReturnType()->isAnyPointerType() || 10763 FT->getReturnType()->isNullPtrType()) 10764 // DllMain is exempt because a return value of zero means it failed. 10765 if (FD->getName() != "DllMain") 10766 FD->setHasImplicitReturnZero(true); 10767 10768 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10769 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10770 FD->setInvalidDecl(); 10771 } 10772 } 10773 10774 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10775 // FIXME: Need strict checking. In C89, we need to check for 10776 // any assignment, increment, decrement, function-calls, or 10777 // commas outside of a sizeof. In C99, it's the same list, 10778 // except that the aforementioned are allowed in unevaluated 10779 // expressions. Everything else falls under the 10780 // "may accept other forms of constant expressions" exception. 10781 // (We never end up here for C++, so the constant expression 10782 // rules there don't matter.) 10783 const Expr *Culprit; 10784 if (Init->isConstantInitializer(Context, false, &Culprit)) 10785 return false; 10786 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10787 << Culprit->getSourceRange(); 10788 return true; 10789 } 10790 10791 namespace { 10792 // Visits an initialization expression to see if OrigDecl is evaluated in 10793 // its own initialization and throws a warning if it does. 10794 class SelfReferenceChecker 10795 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10796 Sema &S; 10797 Decl *OrigDecl; 10798 bool isRecordType; 10799 bool isPODType; 10800 bool isReferenceType; 10801 10802 bool isInitList; 10803 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10804 10805 public: 10806 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10807 10808 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10809 S(S), OrigDecl(OrigDecl) { 10810 isPODType = false; 10811 isRecordType = false; 10812 isReferenceType = false; 10813 isInitList = false; 10814 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10815 isPODType = VD->getType().isPODType(S.Context); 10816 isRecordType = VD->getType()->isRecordType(); 10817 isReferenceType = VD->getType()->isReferenceType(); 10818 } 10819 } 10820 10821 // For most expressions, just call the visitor. For initializer lists, 10822 // track the index of the field being initialized since fields are 10823 // initialized in order allowing use of previously initialized fields. 10824 void CheckExpr(Expr *E) { 10825 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10826 if (!InitList) { 10827 Visit(E); 10828 return; 10829 } 10830 10831 // Track and increment the index here. 10832 isInitList = true; 10833 InitFieldIndex.push_back(0); 10834 for (auto Child : InitList->children()) { 10835 CheckExpr(cast<Expr>(Child)); 10836 ++InitFieldIndex.back(); 10837 } 10838 InitFieldIndex.pop_back(); 10839 } 10840 10841 // Returns true if MemberExpr is checked and no further checking is needed. 10842 // Returns false if additional checking is required. 10843 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10844 llvm::SmallVector<FieldDecl*, 4> Fields; 10845 Expr *Base = E; 10846 bool ReferenceField = false; 10847 10848 // Get the field members used. 10849 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10850 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10851 if (!FD) 10852 return false; 10853 Fields.push_back(FD); 10854 if (FD->getType()->isReferenceType()) 10855 ReferenceField = true; 10856 Base = ME->getBase()->IgnoreParenImpCasts(); 10857 } 10858 10859 // Keep checking only if the base Decl is the same. 10860 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10861 if (!DRE || DRE->getDecl() != OrigDecl) 10862 return false; 10863 10864 // A reference field can be bound to an unininitialized field. 10865 if (CheckReference && !ReferenceField) 10866 return true; 10867 10868 // Convert FieldDecls to their index number. 10869 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10870 for (const FieldDecl *I : llvm::reverse(Fields)) 10871 UsedFieldIndex.push_back(I->getFieldIndex()); 10872 10873 // See if a warning is needed by checking the first difference in index 10874 // numbers. If field being used has index less than the field being 10875 // initialized, then the use is safe. 10876 for (auto UsedIter = UsedFieldIndex.begin(), 10877 UsedEnd = UsedFieldIndex.end(), 10878 OrigIter = InitFieldIndex.begin(), 10879 OrigEnd = InitFieldIndex.end(); 10880 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10881 if (*UsedIter < *OrigIter) 10882 return true; 10883 if (*UsedIter > *OrigIter) 10884 break; 10885 } 10886 10887 // TODO: Add a different warning which will print the field names. 10888 HandleDeclRefExpr(DRE); 10889 return true; 10890 } 10891 10892 // For most expressions, the cast is directly above the DeclRefExpr. 10893 // For conditional operators, the cast can be outside the conditional 10894 // operator if both expressions are DeclRefExpr's. 10895 void HandleValue(Expr *E) { 10896 E = E->IgnoreParens(); 10897 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10898 HandleDeclRefExpr(DRE); 10899 return; 10900 } 10901 10902 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10903 Visit(CO->getCond()); 10904 HandleValue(CO->getTrueExpr()); 10905 HandleValue(CO->getFalseExpr()); 10906 return; 10907 } 10908 10909 if (BinaryConditionalOperator *BCO = 10910 dyn_cast<BinaryConditionalOperator>(E)) { 10911 Visit(BCO->getCond()); 10912 HandleValue(BCO->getFalseExpr()); 10913 return; 10914 } 10915 10916 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10917 HandleValue(OVE->getSourceExpr()); 10918 return; 10919 } 10920 10921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10922 if (BO->getOpcode() == BO_Comma) { 10923 Visit(BO->getLHS()); 10924 HandleValue(BO->getRHS()); 10925 return; 10926 } 10927 } 10928 10929 if (isa<MemberExpr>(E)) { 10930 if (isInitList) { 10931 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10932 false /*CheckReference*/)) 10933 return; 10934 } 10935 10936 Expr *Base = E->IgnoreParenImpCasts(); 10937 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10938 // Check for static member variables and don't warn on them. 10939 if (!isa<FieldDecl>(ME->getMemberDecl())) 10940 return; 10941 Base = ME->getBase()->IgnoreParenImpCasts(); 10942 } 10943 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10944 HandleDeclRefExpr(DRE); 10945 return; 10946 } 10947 10948 Visit(E); 10949 } 10950 10951 // Reference types not handled in HandleValue are handled here since all 10952 // uses of references are bad, not just r-value uses. 10953 void VisitDeclRefExpr(DeclRefExpr *E) { 10954 if (isReferenceType) 10955 HandleDeclRefExpr(E); 10956 } 10957 10958 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10959 if (E->getCastKind() == CK_LValueToRValue) { 10960 HandleValue(E->getSubExpr()); 10961 return; 10962 } 10963 10964 Inherited::VisitImplicitCastExpr(E); 10965 } 10966 10967 void VisitMemberExpr(MemberExpr *E) { 10968 if (isInitList) { 10969 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10970 return; 10971 } 10972 10973 // Don't warn on arrays since they can be treated as pointers. 10974 if (E->getType()->canDecayToPointerType()) return; 10975 10976 // Warn when a non-static method call is followed by non-static member 10977 // field accesses, which is followed by a DeclRefExpr. 10978 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10979 bool Warn = (MD && !MD->isStatic()); 10980 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10981 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10982 if (!isa<FieldDecl>(ME->getMemberDecl())) 10983 Warn = false; 10984 Base = ME->getBase()->IgnoreParenImpCasts(); 10985 } 10986 10987 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10988 if (Warn) 10989 HandleDeclRefExpr(DRE); 10990 return; 10991 } 10992 10993 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10994 // Visit that expression. 10995 Visit(Base); 10996 } 10997 10998 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10999 Expr *Callee = E->getCallee(); 11000 11001 if (isa<UnresolvedLookupExpr>(Callee)) 11002 return Inherited::VisitCXXOperatorCallExpr(E); 11003 11004 Visit(Callee); 11005 for (auto Arg: E->arguments()) 11006 HandleValue(Arg->IgnoreParenImpCasts()); 11007 } 11008 11009 void VisitUnaryOperator(UnaryOperator *E) { 11010 // For POD record types, addresses of its own members are well-defined. 11011 if (E->getOpcode() == UO_AddrOf && isRecordType && 11012 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11013 if (!isPODType) 11014 HandleValue(E->getSubExpr()); 11015 return; 11016 } 11017 11018 if (E->isIncrementDecrementOp()) { 11019 HandleValue(E->getSubExpr()); 11020 return; 11021 } 11022 11023 Inherited::VisitUnaryOperator(E); 11024 } 11025 11026 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11027 11028 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11029 if (E->getConstructor()->isCopyConstructor()) { 11030 Expr *ArgExpr = E->getArg(0); 11031 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11032 if (ILE->getNumInits() == 1) 11033 ArgExpr = ILE->getInit(0); 11034 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11035 if (ICE->getCastKind() == CK_NoOp) 11036 ArgExpr = ICE->getSubExpr(); 11037 HandleValue(ArgExpr); 11038 return; 11039 } 11040 Inherited::VisitCXXConstructExpr(E); 11041 } 11042 11043 void VisitCallExpr(CallExpr *E) { 11044 // Treat std::move as a use. 11045 if (E->isCallToStdMove()) { 11046 HandleValue(E->getArg(0)); 11047 return; 11048 } 11049 11050 Inherited::VisitCallExpr(E); 11051 } 11052 11053 void VisitBinaryOperator(BinaryOperator *E) { 11054 if (E->isCompoundAssignmentOp()) { 11055 HandleValue(E->getLHS()); 11056 Visit(E->getRHS()); 11057 return; 11058 } 11059 11060 Inherited::VisitBinaryOperator(E); 11061 } 11062 11063 // A custom visitor for BinaryConditionalOperator is needed because the 11064 // regular visitor would check the condition and true expression separately 11065 // but both point to the same place giving duplicate diagnostics. 11066 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11067 Visit(E->getCond()); 11068 Visit(E->getFalseExpr()); 11069 } 11070 11071 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11072 Decl* ReferenceDecl = DRE->getDecl(); 11073 if (OrigDecl != ReferenceDecl) return; 11074 unsigned diag; 11075 if (isReferenceType) { 11076 diag = diag::warn_uninit_self_reference_in_reference_init; 11077 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11078 diag = diag::warn_static_self_reference_in_init; 11079 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11080 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11081 DRE->getDecl()->getType()->isRecordType()) { 11082 diag = diag::warn_uninit_self_reference_in_init; 11083 } else { 11084 // Local variables will be handled by the CFG analysis. 11085 return; 11086 } 11087 11088 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11089 S.PDiag(diag) 11090 << DRE->getDecl() << OrigDecl->getLocation() 11091 << DRE->getSourceRange()); 11092 } 11093 }; 11094 11095 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11096 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11097 bool DirectInit) { 11098 // Parameters arguments are occassionially constructed with itself, 11099 // for instance, in recursive functions. Skip them. 11100 if (isa<ParmVarDecl>(OrigDecl)) 11101 return; 11102 11103 E = E->IgnoreParens(); 11104 11105 // Skip checking T a = a where T is not a record or reference type. 11106 // Doing so is a way to silence uninitialized warnings. 11107 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11108 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11109 if (ICE->getCastKind() == CK_LValueToRValue) 11110 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11111 if (DRE->getDecl() == OrigDecl) 11112 return; 11113 11114 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11115 } 11116 } // end anonymous namespace 11117 11118 namespace { 11119 // Simple wrapper to add the name of a variable or (if no variable is 11120 // available) a DeclarationName into a diagnostic. 11121 struct VarDeclOrName { 11122 VarDecl *VDecl; 11123 DeclarationName Name; 11124 11125 friend const Sema::SemaDiagnosticBuilder & 11126 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11127 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11128 } 11129 }; 11130 } // end anonymous namespace 11131 11132 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11133 DeclarationName Name, QualType Type, 11134 TypeSourceInfo *TSI, 11135 SourceRange Range, bool DirectInit, 11136 Expr *Init) { 11137 bool IsInitCapture = !VDecl; 11138 assert((!VDecl || !VDecl->isInitCapture()) && 11139 "init captures are expected to be deduced prior to initialization"); 11140 11141 VarDeclOrName VN{VDecl, Name}; 11142 11143 DeducedType *Deduced = Type->getContainedDeducedType(); 11144 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11145 11146 // C++11 [dcl.spec.auto]p3 11147 if (!Init) { 11148 assert(VDecl && "no init for init capture deduction?"); 11149 11150 // Except for class argument deduction, and then for an initializing 11151 // declaration only, i.e. no static at class scope or extern. 11152 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11153 VDecl->hasExternalStorage() || 11154 VDecl->isStaticDataMember()) { 11155 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11156 << VDecl->getDeclName() << Type; 11157 return QualType(); 11158 } 11159 } 11160 11161 ArrayRef<Expr*> DeduceInits; 11162 if (Init) 11163 DeduceInits = Init; 11164 11165 if (DirectInit) { 11166 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11167 DeduceInits = PL->exprs(); 11168 } 11169 11170 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11171 assert(VDecl && "non-auto type for init capture deduction?"); 11172 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11173 InitializationKind Kind = InitializationKind::CreateForInit( 11174 VDecl->getLocation(), DirectInit, Init); 11175 // FIXME: Initialization should not be taking a mutable list of inits. 11176 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11177 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11178 InitsCopy); 11179 } 11180 11181 if (DirectInit) { 11182 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11183 DeduceInits = IL->inits(); 11184 } 11185 11186 // Deduction only works if we have exactly one source expression. 11187 if (DeduceInits.empty()) { 11188 // It isn't possible to write this directly, but it is possible to 11189 // end up in this situation with "auto x(some_pack...);" 11190 Diag(Init->getBeginLoc(), IsInitCapture 11191 ? diag::err_init_capture_no_expression 11192 : diag::err_auto_var_init_no_expression) 11193 << VN << Type << Range; 11194 return QualType(); 11195 } 11196 11197 if (DeduceInits.size() > 1) { 11198 Diag(DeduceInits[1]->getBeginLoc(), 11199 IsInitCapture ? diag::err_init_capture_multiple_expressions 11200 : diag::err_auto_var_init_multiple_expressions) 11201 << VN << Type << Range; 11202 return QualType(); 11203 } 11204 11205 Expr *DeduceInit = DeduceInits[0]; 11206 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11207 Diag(Init->getBeginLoc(), IsInitCapture 11208 ? diag::err_init_capture_paren_braces 11209 : diag::err_auto_var_init_paren_braces) 11210 << isa<InitListExpr>(Init) << VN << Type << Range; 11211 return QualType(); 11212 } 11213 11214 // Expressions default to 'id' when we're in a debugger. 11215 bool DefaultedAnyToId = false; 11216 if (getLangOpts().DebuggerCastResultToId && 11217 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11218 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11219 if (Result.isInvalid()) { 11220 return QualType(); 11221 } 11222 Init = Result.get(); 11223 DefaultedAnyToId = true; 11224 } 11225 11226 // C++ [dcl.decomp]p1: 11227 // If the assignment-expression [...] has array type A and no ref-qualifier 11228 // is present, e has type cv A 11229 if (VDecl && isa<DecompositionDecl>(VDecl) && 11230 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11231 DeduceInit->getType()->isConstantArrayType()) 11232 return Context.getQualifiedType(DeduceInit->getType(), 11233 Type.getQualifiers()); 11234 11235 QualType DeducedType; 11236 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11237 if (!IsInitCapture) 11238 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11239 else if (isa<InitListExpr>(Init)) 11240 Diag(Range.getBegin(), 11241 diag::err_init_capture_deduction_failure_from_init_list) 11242 << VN 11243 << (DeduceInit->getType().isNull() ? TSI->getType() 11244 : DeduceInit->getType()) 11245 << DeduceInit->getSourceRange(); 11246 else 11247 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11248 << VN << TSI->getType() 11249 << (DeduceInit->getType().isNull() ? TSI->getType() 11250 : DeduceInit->getType()) 11251 << DeduceInit->getSourceRange(); 11252 } 11253 11254 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11255 // 'id' instead of a specific object type prevents most of our usual 11256 // checks. 11257 // We only want to warn outside of template instantiations, though: 11258 // inside a template, the 'id' could have come from a parameter. 11259 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11260 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11261 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11262 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11263 } 11264 11265 return DeducedType; 11266 } 11267 11268 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11269 Expr *Init) { 11270 QualType DeducedType = deduceVarTypeFromInitializer( 11271 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11272 VDecl->getSourceRange(), DirectInit, Init); 11273 if (DeducedType.isNull()) { 11274 VDecl->setInvalidDecl(); 11275 return true; 11276 } 11277 11278 VDecl->setType(DeducedType); 11279 assert(VDecl->isLinkageValid()); 11280 11281 // In ARC, infer lifetime. 11282 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11283 VDecl->setInvalidDecl(); 11284 11285 // If this is a redeclaration, check that the type we just deduced matches 11286 // the previously declared type. 11287 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11288 // We never need to merge the type, because we cannot form an incomplete 11289 // array of auto, nor deduce such a type. 11290 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11291 } 11292 11293 // Check the deduced type is valid for a variable declaration. 11294 CheckVariableDeclarationType(VDecl); 11295 return VDecl->isInvalidDecl(); 11296 } 11297 11298 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11299 SourceLocation Loc) { 11300 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11301 Init = CE->getSubExpr(); 11302 11303 QualType InitType = Init->getType(); 11304 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11305 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11306 "shouldn't be called if type doesn't have a non-trivial C struct"); 11307 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11308 for (auto I : ILE->inits()) { 11309 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11310 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11311 continue; 11312 SourceLocation SL = I->getExprLoc(); 11313 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11314 } 11315 return; 11316 } 11317 11318 if (isa<ImplicitValueInitExpr>(Init)) { 11319 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11320 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11321 NTCUK_Init); 11322 } else { 11323 // Assume all other explicit initializers involving copying some existing 11324 // object. 11325 // TODO: ignore any explicit initializers where we can guarantee 11326 // copy-elision. 11327 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11328 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11329 } 11330 } 11331 11332 namespace { 11333 11334 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11335 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11336 // in the source code or implicitly by the compiler if it is in a union 11337 // defined in a system header and has non-trivial ObjC ownership 11338 // qualifications. We don't want those fields to participate in determining 11339 // whether the containing union is non-trivial. 11340 return FD->hasAttr<UnavailableAttr>(); 11341 } 11342 11343 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11344 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11345 void> { 11346 using Super = 11347 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11348 void>; 11349 11350 DiagNonTrivalCUnionDefaultInitializeVisitor( 11351 QualType OrigTy, SourceLocation OrigLoc, 11352 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11353 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11354 11355 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11356 const FieldDecl *FD, bool InNonTrivialUnion) { 11357 if (const auto *AT = S.Context.getAsArrayType(QT)) 11358 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11359 InNonTrivialUnion); 11360 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11361 } 11362 11363 void visitARCStrong(QualType QT, const FieldDecl *FD, 11364 bool InNonTrivialUnion) { 11365 if (InNonTrivialUnion) 11366 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11367 << 1 << 0 << QT << FD->getName(); 11368 } 11369 11370 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11371 if (InNonTrivialUnion) 11372 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11373 << 1 << 0 << QT << FD->getName(); 11374 } 11375 11376 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11377 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11378 if (RD->isUnion()) { 11379 if (OrigLoc.isValid()) { 11380 bool IsUnion = false; 11381 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11382 IsUnion = OrigRD->isUnion(); 11383 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11384 << 0 << OrigTy << IsUnion << UseContext; 11385 // Reset OrigLoc so that this diagnostic is emitted only once. 11386 OrigLoc = SourceLocation(); 11387 } 11388 InNonTrivialUnion = true; 11389 } 11390 11391 if (InNonTrivialUnion) 11392 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11393 << 0 << 0 << QT.getUnqualifiedType() << ""; 11394 11395 for (const FieldDecl *FD : RD->fields()) 11396 if (!shouldIgnoreForRecordTriviality(FD)) 11397 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11398 } 11399 11400 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11401 11402 // The non-trivial C union type or the struct/union type that contains a 11403 // non-trivial C union. 11404 QualType OrigTy; 11405 SourceLocation OrigLoc; 11406 Sema::NonTrivialCUnionContext UseContext; 11407 Sema &S; 11408 }; 11409 11410 struct DiagNonTrivalCUnionDestructedTypeVisitor 11411 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11412 using Super = 11413 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11414 11415 DiagNonTrivalCUnionDestructedTypeVisitor( 11416 QualType OrigTy, SourceLocation OrigLoc, 11417 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11418 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11419 11420 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11421 const FieldDecl *FD, bool InNonTrivialUnion) { 11422 if (const auto *AT = S.Context.getAsArrayType(QT)) 11423 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11424 InNonTrivialUnion); 11425 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11426 } 11427 11428 void visitARCStrong(QualType QT, const FieldDecl *FD, 11429 bool InNonTrivialUnion) { 11430 if (InNonTrivialUnion) 11431 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11432 << 1 << 1 << QT << FD->getName(); 11433 } 11434 11435 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11436 if (InNonTrivialUnion) 11437 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11438 << 1 << 1 << QT << FD->getName(); 11439 } 11440 11441 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11442 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11443 if (RD->isUnion()) { 11444 if (OrigLoc.isValid()) { 11445 bool IsUnion = false; 11446 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11447 IsUnion = OrigRD->isUnion(); 11448 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11449 << 1 << OrigTy << IsUnion << UseContext; 11450 // Reset OrigLoc so that this diagnostic is emitted only once. 11451 OrigLoc = SourceLocation(); 11452 } 11453 InNonTrivialUnion = true; 11454 } 11455 11456 if (InNonTrivialUnion) 11457 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11458 << 0 << 1 << QT.getUnqualifiedType() << ""; 11459 11460 for (const FieldDecl *FD : RD->fields()) 11461 if (!shouldIgnoreForRecordTriviality(FD)) 11462 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11463 } 11464 11465 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11466 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11467 bool InNonTrivialUnion) {} 11468 11469 // The non-trivial C union type or the struct/union type that contains a 11470 // non-trivial C union. 11471 QualType OrigTy; 11472 SourceLocation OrigLoc; 11473 Sema::NonTrivialCUnionContext UseContext; 11474 Sema &S; 11475 }; 11476 11477 struct DiagNonTrivalCUnionCopyVisitor 11478 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11479 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11480 11481 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11482 Sema::NonTrivialCUnionContext UseContext, 11483 Sema &S) 11484 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11485 11486 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11487 const FieldDecl *FD, bool InNonTrivialUnion) { 11488 if (const auto *AT = S.Context.getAsArrayType(QT)) 11489 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11490 InNonTrivialUnion); 11491 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11492 } 11493 11494 void visitARCStrong(QualType QT, const FieldDecl *FD, 11495 bool InNonTrivialUnion) { 11496 if (InNonTrivialUnion) 11497 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11498 << 1 << 2 << QT << FD->getName(); 11499 } 11500 11501 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11502 if (InNonTrivialUnion) 11503 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11504 << 1 << 2 << QT << FD->getName(); 11505 } 11506 11507 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11508 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11509 if (RD->isUnion()) { 11510 if (OrigLoc.isValid()) { 11511 bool IsUnion = false; 11512 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11513 IsUnion = OrigRD->isUnion(); 11514 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11515 << 2 << OrigTy << IsUnion << UseContext; 11516 // Reset OrigLoc so that this diagnostic is emitted only once. 11517 OrigLoc = SourceLocation(); 11518 } 11519 InNonTrivialUnion = true; 11520 } 11521 11522 if (InNonTrivialUnion) 11523 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11524 << 0 << 2 << QT.getUnqualifiedType() << ""; 11525 11526 for (const FieldDecl *FD : RD->fields()) 11527 if (!shouldIgnoreForRecordTriviality(FD)) 11528 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11529 } 11530 11531 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11532 const FieldDecl *FD, bool InNonTrivialUnion) {} 11533 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11534 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11535 bool InNonTrivialUnion) {} 11536 11537 // The non-trivial C union type or the struct/union type that contains a 11538 // non-trivial C union. 11539 QualType OrigTy; 11540 SourceLocation OrigLoc; 11541 Sema::NonTrivialCUnionContext UseContext; 11542 Sema &S; 11543 }; 11544 11545 } // namespace 11546 11547 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11548 NonTrivialCUnionContext UseContext, 11549 unsigned NonTrivialKind) { 11550 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11551 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11552 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11553 "shouldn't be called if type doesn't have a non-trivial C union"); 11554 11555 if ((NonTrivialKind & NTCUK_Init) && 11556 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11557 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11558 .visit(QT, nullptr, false); 11559 if ((NonTrivialKind & NTCUK_Destruct) && 11560 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11561 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11562 .visit(QT, nullptr, false); 11563 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11564 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11565 .visit(QT, nullptr, false); 11566 } 11567 11568 /// AddInitializerToDecl - Adds the initializer Init to the 11569 /// declaration dcl. If DirectInit is true, this is C++ direct 11570 /// initialization rather than copy initialization. 11571 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11572 // If there is no declaration, there was an error parsing it. Just ignore 11573 // the initializer. 11574 if (!RealDecl || RealDecl->isInvalidDecl()) { 11575 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11576 return; 11577 } 11578 11579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11580 // Pure-specifiers are handled in ActOnPureSpecifier. 11581 Diag(Method->getLocation(), diag::err_member_function_initialization) 11582 << Method->getDeclName() << Init->getSourceRange(); 11583 Method->setInvalidDecl(); 11584 return; 11585 } 11586 11587 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11588 if (!VDecl) { 11589 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11590 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11591 RealDecl->setInvalidDecl(); 11592 return; 11593 } 11594 11595 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11596 if (VDecl->getType()->isUndeducedType()) { 11597 // Attempt typo correction early so that the type of the init expression can 11598 // be deduced based on the chosen correction if the original init contains a 11599 // TypoExpr. 11600 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11601 if (!Res.isUsable()) { 11602 RealDecl->setInvalidDecl(); 11603 return; 11604 } 11605 Init = Res.get(); 11606 11607 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11608 return; 11609 } 11610 11611 // dllimport cannot be used on variable definitions. 11612 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11613 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11614 VDecl->setInvalidDecl(); 11615 return; 11616 } 11617 11618 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11619 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11620 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11621 VDecl->setInvalidDecl(); 11622 return; 11623 } 11624 11625 if (!VDecl->getType()->isDependentType()) { 11626 // A definition must end up with a complete type, which means it must be 11627 // complete with the restriction that an array type might be completed by 11628 // the initializer; note that later code assumes this restriction. 11629 QualType BaseDeclType = VDecl->getType(); 11630 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11631 BaseDeclType = Array->getElementType(); 11632 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11633 diag::err_typecheck_decl_incomplete_type)) { 11634 RealDecl->setInvalidDecl(); 11635 return; 11636 } 11637 11638 // The variable can not have an abstract class type. 11639 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11640 diag::err_abstract_type_in_decl, 11641 AbstractVariableType)) 11642 VDecl->setInvalidDecl(); 11643 } 11644 11645 // If adding the initializer will turn this declaration into a definition, 11646 // and we already have a definition for this variable, diagnose or otherwise 11647 // handle the situation. 11648 VarDecl *Def; 11649 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11650 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11651 !VDecl->isThisDeclarationADemotedDefinition() && 11652 checkVarDeclRedefinition(Def, VDecl)) 11653 return; 11654 11655 if (getLangOpts().CPlusPlus) { 11656 // C++ [class.static.data]p4 11657 // If a static data member is of const integral or const 11658 // enumeration type, its declaration in the class definition can 11659 // specify a constant-initializer which shall be an integral 11660 // constant expression (5.19). In that case, the member can appear 11661 // in integral constant expressions. The member shall still be 11662 // defined in a namespace scope if it is used in the program and the 11663 // namespace scope definition shall not contain an initializer. 11664 // 11665 // We already performed a redefinition check above, but for static 11666 // data members we also need to check whether there was an in-class 11667 // declaration with an initializer. 11668 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11669 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11670 << VDecl->getDeclName(); 11671 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11672 diag::note_previous_initializer) 11673 << 0; 11674 return; 11675 } 11676 11677 if (VDecl->hasLocalStorage()) 11678 setFunctionHasBranchProtectedScope(); 11679 11680 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11681 VDecl->setInvalidDecl(); 11682 return; 11683 } 11684 } 11685 11686 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11687 // a kernel function cannot be initialized." 11688 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11689 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11690 VDecl->setInvalidDecl(); 11691 return; 11692 } 11693 11694 // Get the decls type and save a reference for later, since 11695 // CheckInitializerTypes may change it. 11696 QualType DclT = VDecl->getType(), SavT = DclT; 11697 11698 // Expressions default to 'id' when we're in a debugger 11699 // and we are assigning it to a variable of Objective-C pointer type. 11700 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11701 Init->getType() == Context.UnknownAnyTy) { 11702 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11703 if (Result.isInvalid()) { 11704 VDecl->setInvalidDecl(); 11705 return; 11706 } 11707 Init = Result.get(); 11708 } 11709 11710 // Perform the initialization. 11711 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11712 if (!VDecl->isInvalidDecl()) { 11713 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11714 InitializationKind Kind = InitializationKind::CreateForInit( 11715 VDecl->getLocation(), DirectInit, Init); 11716 11717 MultiExprArg Args = Init; 11718 if (CXXDirectInit) 11719 Args = MultiExprArg(CXXDirectInit->getExprs(), 11720 CXXDirectInit->getNumExprs()); 11721 11722 // Try to correct any TypoExprs in the initialization arguments. 11723 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11724 ExprResult Res = CorrectDelayedTyposInExpr( 11725 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11726 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11727 return Init.Failed() ? ExprError() : E; 11728 }); 11729 if (Res.isInvalid()) { 11730 VDecl->setInvalidDecl(); 11731 } else if (Res.get() != Args[Idx]) { 11732 Args[Idx] = Res.get(); 11733 } 11734 } 11735 if (VDecl->isInvalidDecl()) 11736 return; 11737 11738 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11739 /*TopLevelOfInitList=*/false, 11740 /*TreatUnavailableAsInvalid=*/false); 11741 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11742 if (Result.isInvalid()) { 11743 VDecl->setInvalidDecl(); 11744 return; 11745 } 11746 11747 Init = Result.getAs<Expr>(); 11748 } 11749 11750 // Check for self-references within variable initializers. 11751 // Variables declared within a function/method body (except for references) 11752 // are handled by a dataflow analysis. 11753 // This is undefined behavior in C++, but valid in C. 11754 if (getLangOpts().CPlusPlus) { 11755 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11756 VDecl->getType()->isReferenceType()) { 11757 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11758 } 11759 } 11760 11761 // If the type changed, it means we had an incomplete type that was 11762 // completed by the initializer. For example: 11763 // int ary[] = { 1, 3, 5 }; 11764 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11765 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11766 VDecl->setType(DclT); 11767 11768 if (!VDecl->isInvalidDecl()) { 11769 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11770 11771 if (VDecl->hasAttr<BlocksAttr>()) 11772 checkRetainCycles(VDecl, Init); 11773 11774 // It is safe to assign a weak reference into a strong variable. 11775 // Although this code can still have problems: 11776 // id x = self.weakProp; 11777 // id y = self.weakProp; 11778 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11779 // paths through the function. This should be revisited if 11780 // -Wrepeated-use-of-weak is made flow-sensitive. 11781 if (FunctionScopeInfo *FSI = getCurFunction()) 11782 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11783 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11784 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11785 Init->getBeginLoc())) 11786 FSI->markSafeWeakUse(Init); 11787 } 11788 11789 // The initialization is usually a full-expression. 11790 // 11791 // FIXME: If this is a braced initialization of an aggregate, it is not 11792 // an expression, and each individual field initializer is a separate 11793 // full-expression. For instance, in: 11794 // 11795 // struct Temp { ~Temp(); }; 11796 // struct S { S(Temp); }; 11797 // struct T { S a, b; } t = { Temp(), Temp() } 11798 // 11799 // we should destroy the first Temp before constructing the second. 11800 ExprResult Result = 11801 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11802 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11803 if (Result.isInvalid()) { 11804 VDecl->setInvalidDecl(); 11805 return; 11806 } 11807 Init = Result.get(); 11808 11809 // Attach the initializer to the decl. 11810 VDecl->setInit(Init); 11811 11812 if (VDecl->isLocalVarDecl()) { 11813 // Don't check the initializer if the declaration is malformed. 11814 if (VDecl->isInvalidDecl()) { 11815 // do nothing 11816 11817 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11818 // This is true even in C++ for OpenCL. 11819 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11820 CheckForConstantInitializer(Init, DclT); 11821 11822 // Otherwise, C++ does not restrict the initializer. 11823 } else if (getLangOpts().CPlusPlus) { 11824 // do nothing 11825 11826 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11827 // static storage duration shall be constant expressions or string literals. 11828 } else if (VDecl->getStorageClass() == SC_Static) { 11829 CheckForConstantInitializer(Init, DclT); 11830 11831 // C89 is stricter than C99 for aggregate initializers. 11832 // C89 6.5.7p3: All the expressions [...] in an initializer list 11833 // for an object that has aggregate or union type shall be 11834 // constant expressions. 11835 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11836 isa<InitListExpr>(Init)) { 11837 const Expr *Culprit; 11838 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11839 Diag(Culprit->getExprLoc(), 11840 diag::ext_aggregate_init_not_constant) 11841 << Culprit->getSourceRange(); 11842 } 11843 } 11844 11845 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 11846 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 11847 if (VDecl->hasLocalStorage()) 11848 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 11849 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11850 VDecl->getLexicalDeclContext()->isRecord()) { 11851 // This is an in-class initialization for a static data member, e.g., 11852 // 11853 // struct S { 11854 // static const int value = 17; 11855 // }; 11856 11857 // C++ [class.mem]p4: 11858 // A member-declarator can contain a constant-initializer only 11859 // if it declares a static member (9.4) of const integral or 11860 // const enumeration type, see 9.4.2. 11861 // 11862 // C++11 [class.static.data]p3: 11863 // If a non-volatile non-inline const static data member is of integral 11864 // or enumeration type, its declaration in the class definition can 11865 // specify a brace-or-equal-initializer in which every initializer-clause 11866 // that is an assignment-expression is a constant expression. A static 11867 // data member of literal type can be declared in the class definition 11868 // with the constexpr specifier; if so, its declaration shall specify a 11869 // brace-or-equal-initializer in which every initializer-clause that is 11870 // an assignment-expression is a constant expression. 11871 11872 // Do nothing on dependent types. 11873 if (DclT->isDependentType()) { 11874 11875 // Allow any 'static constexpr' members, whether or not they are of literal 11876 // type. We separately check that every constexpr variable is of literal 11877 // type. 11878 } else if (VDecl->isConstexpr()) { 11879 11880 // Require constness. 11881 } else if (!DclT.isConstQualified()) { 11882 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11883 << Init->getSourceRange(); 11884 VDecl->setInvalidDecl(); 11885 11886 // We allow integer constant expressions in all cases. 11887 } else if (DclT->isIntegralOrEnumerationType()) { 11888 // Check whether the expression is a constant expression. 11889 SourceLocation Loc; 11890 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11891 // In C++11, a non-constexpr const static data member with an 11892 // in-class initializer cannot be volatile. 11893 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11894 else if (Init->isValueDependent()) 11895 ; // Nothing to check. 11896 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11897 ; // Ok, it's an ICE! 11898 else if (Init->getType()->isScopedEnumeralType() && 11899 Init->isCXX11ConstantExpr(Context)) 11900 ; // Ok, it is a scoped-enum constant expression. 11901 else if (Init->isEvaluatable(Context)) { 11902 // If we can constant fold the initializer through heroics, accept it, 11903 // but report this as a use of an extension for -pedantic. 11904 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11905 << Init->getSourceRange(); 11906 } else { 11907 // Otherwise, this is some crazy unknown case. Report the issue at the 11908 // location provided by the isIntegerConstantExpr failed check. 11909 Diag(Loc, diag::err_in_class_initializer_non_constant) 11910 << Init->getSourceRange(); 11911 VDecl->setInvalidDecl(); 11912 } 11913 11914 // We allow foldable floating-point constants as an extension. 11915 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11916 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11917 // it anyway and provide a fixit to add the 'constexpr'. 11918 if (getLangOpts().CPlusPlus11) { 11919 Diag(VDecl->getLocation(), 11920 diag::ext_in_class_initializer_float_type_cxx11) 11921 << DclT << Init->getSourceRange(); 11922 Diag(VDecl->getBeginLoc(), 11923 diag::note_in_class_initializer_float_type_cxx11) 11924 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11925 } else { 11926 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11927 << DclT << Init->getSourceRange(); 11928 11929 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11930 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11931 << Init->getSourceRange(); 11932 VDecl->setInvalidDecl(); 11933 } 11934 } 11935 11936 // Suggest adding 'constexpr' in C++11 for literal types. 11937 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11938 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11939 << DclT << Init->getSourceRange() 11940 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11941 VDecl->setConstexpr(true); 11942 11943 } else { 11944 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11945 << DclT << Init->getSourceRange(); 11946 VDecl->setInvalidDecl(); 11947 } 11948 } else if (VDecl->isFileVarDecl()) { 11949 // In C, extern is typically used to avoid tentative definitions when 11950 // declaring variables in headers, but adding an intializer makes it a 11951 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11952 // In C++, extern is often used to give implictly static const variables 11953 // external linkage, so don't warn in that case. If selectany is present, 11954 // this might be header code intended for C and C++ inclusion, so apply the 11955 // C++ rules. 11956 if (VDecl->getStorageClass() == SC_Extern && 11957 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11958 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11959 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11960 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11961 Diag(VDecl->getLocation(), diag::warn_extern_init); 11962 11963 // In Microsoft C++ mode, a const variable defined in namespace scope has 11964 // external linkage by default if the variable is declared with 11965 // __declspec(dllexport). 11966 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 11967 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 11968 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 11969 VDecl->setStorageClass(SC_Extern); 11970 11971 // C99 6.7.8p4. All file scoped initializers need to be constant. 11972 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11973 CheckForConstantInitializer(Init, DclT); 11974 } 11975 11976 QualType InitType = Init->getType(); 11977 if (!InitType.isNull() && 11978 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11979 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 11980 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 11981 11982 // We will represent direct-initialization similarly to copy-initialization: 11983 // int x(1); -as-> int x = 1; 11984 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11985 // 11986 // Clients that want to distinguish between the two forms, can check for 11987 // direct initializer using VarDecl::getInitStyle(). 11988 // A major benefit is that clients that don't particularly care about which 11989 // exactly form was it (like the CodeGen) can handle both cases without 11990 // special case code. 11991 11992 // C++ 8.5p11: 11993 // The form of initialization (using parentheses or '=') is generally 11994 // insignificant, but does matter when the entity being initialized has a 11995 // class type. 11996 if (CXXDirectInit) { 11997 assert(DirectInit && "Call-style initializer must be direct init."); 11998 VDecl->setInitStyle(VarDecl::CallInit); 11999 } else if (DirectInit) { 12000 // This must be list-initialization. No other way is direct-initialization. 12001 VDecl->setInitStyle(VarDecl::ListInit); 12002 } 12003 12004 CheckCompleteVariableDeclaration(VDecl); 12005 } 12006 12007 /// ActOnInitializerError - Given that there was an error parsing an 12008 /// initializer for the given declaration, try to return to some form 12009 /// of sanity. 12010 void Sema::ActOnInitializerError(Decl *D) { 12011 // Our main concern here is re-establishing invariants like "a 12012 // variable's type is either dependent or complete". 12013 if (!D || D->isInvalidDecl()) return; 12014 12015 VarDecl *VD = dyn_cast<VarDecl>(D); 12016 if (!VD) return; 12017 12018 // Bindings are not usable if we can't make sense of the initializer. 12019 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12020 for (auto *BD : DD->bindings()) 12021 BD->setInvalidDecl(); 12022 12023 // Auto types are meaningless if we can't make sense of the initializer. 12024 if (ParsingInitForAutoVars.count(D)) { 12025 D->setInvalidDecl(); 12026 return; 12027 } 12028 12029 QualType Ty = VD->getType(); 12030 if (Ty->isDependentType()) return; 12031 12032 // Require a complete type. 12033 if (RequireCompleteType(VD->getLocation(), 12034 Context.getBaseElementType(Ty), 12035 diag::err_typecheck_decl_incomplete_type)) { 12036 VD->setInvalidDecl(); 12037 return; 12038 } 12039 12040 // Require a non-abstract type. 12041 if (RequireNonAbstractType(VD->getLocation(), Ty, 12042 diag::err_abstract_type_in_decl, 12043 AbstractVariableType)) { 12044 VD->setInvalidDecl(); 12045 return; 12046 } 12047 12048 // Don't bother complaining about constructors or destructors, 12049 // though. 12050 } 12051 12052 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12053 // If there is no declaration, there was an error parsing it. Just ignore it. 12054 if (!RealDecl) 12055 return; 12056 12057 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12058 QualType Type = Var->getType(); 12059 12060 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12061 if (isa<DecompositionDecl>(RealDecl)) { 12062 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12063 Var->setInvalidDecl(); 12064 return; 12065 } 12066 12067 if (Type->isUndeducedType() && 12068 DeduceVariableDeclarationType(Var, false, nullptr)) 12069 return; 12070 12071 // C++11 [class.static.data]p3: A static data member can be declared with 12072 // the constexpr specifier; if so, its declaration shall specify 12073 // a brace-or-equal-initializer. 12074 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12075 // the definition of a variable [...] or the declaration of a static data 12076 // member. 12077 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12078 !Var->isThisDeclarationADemotedDefinition()) { 12079 if (Var->isStaticDataMember()) { 12080 // C++1z removes the relevant rule; the in-class declaration is always 12081 // a definition there. 12082 if (!getLangOpts().CPlusPlus17 && 12083 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12084 Diag(Var->getLocation(), 12085 diag::err_constexpr_static_mem_var_requires_init) 12086 << Var->getDeclName(); 12087 Var->setInvalidDecl(); 12088 return; 12089 } 12090 } else { 12091 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12092 Var->setInvalidDecl(); 12093 return; 12094 } 12095 } 12096 12097 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12098 // be initialized. 12099 if (!Var->isInvalidDecl() && 12100 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12101 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12102 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12103 Var->setInvalidDecl(); 12104 return; 12105 } 12106 12107 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12108 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12109 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12110 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12111 NTCUC_DefaultInitializedObject, NTCUK_Init); 12112 12113 12114 switch (DefKind) { 12115 case VarDecl::Definition: 12116 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12117 break; 12118 12119 // We have an out-of-line definition of a static data member 12120 // that has an in-class initializer, so we type-check this like 12121 // a declaration. 12122 // 12123 LLVM_FALLTHROUGH; 12124 12125 case VarDecl::DeclarationOnly: 12126 // It's only a declaration. 12127 12128 // Block scope. C99 6.7p7: If an identifier for an object is 12129 // declared with no linkage (C99 6.2.2p6), the type for the 12130 // object shall be complete. 12131 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12132 !Var->hasLinkage() && !Var->isInvalidDecl() && 12133 RequireCompleteType(Var->getLocation(), Type, 12134 diag::err_typecheck_decl_incomplete_type)) 12135 Var->setInvalidDecl(); 12136 12137 // Make sure that the type is not abstract. 12138 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12139 RequireNonAbstractType(Var->getLocation(), Type, 12140 diag::err_abstract_type_in_decl, 12141 AbstractVariableType)) 12142 Var->setInvalidDecl(); 12143 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12144 Var->getStorageClass() == SC_PrivateExtern) { 12145 Diag(Var->getLocation(), diag::warn_private_extern); 12146 Diag(Var->getLocation(), diag::note_private_extern); 12147 } 12148 12149 return; 12150 12151 case VarDecl::TentativeDefinition: 12152 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12153 // object that has file scope without an initializer, and without a 12154 // storage-class specifier or with the storage-class specifier "static", 12155 // constitutes a tentative definition. Note: A tentative definition with 12156 // external linkage is valid (C99 6.2.2p5). 12157 if (!Var->isInvalidDecl()) { 12158 if (const IncompleteArrayType *ArrayT 12159 = Context.getAsIncompleteArrayType(Type)) { 12160 if (RequireCompleteType(Var->getLocation(), 12161 ArrayT->getElementType(), 12162 diag::err_illegal_decl_array_incomplete_type)) 12163 Var->setInvalidDecl(); 12164 } else if (Var->getStorageClass() == SC_Static) { 12165 // C99 6.9.2p3: If the declaration of an identifier for an object is 12166 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12167 // declared type shall not be an incomplete type. 12168 // NOTE: code such as the following 12169 // static struct s; 12170 // struct s { int a; }; 12171 // is accepted by gcc. Hence here we issue a warning instead of 12172 // an error and we do not invalidate the static declaration. 12173 // NOTE: to avoid multiple warnings, only check the first declaration. 12174 if (Var->isFirstDecl()) 12175 RequireCompleteType(Var->getLocation(), Type, 12176 diag::ext_typecheck_decl_incomplete_type); 12177 } 12178 } 12179 12180 // Record the tentative definition; we're done. 12181 if (!Var->isInvalidDecl()) 12182 TentativeDefinitions.push_back(Var); 12183 return; 12184 } 12185 12186 // Provide a specific diagnostic for uninitialized variable 12187 // definitions with incomplete array type. 12188 if (Type->isIncompleteArrayType()) { 12189 Diag(Var->getLocation(), 12190 diag::err_typecheck_incomplete_array_needs_initializer); 12191 Var->setInvalidDecl(); 12192 return; 12193 } 12194 12195 // Provide a specific diagnostic for uninitialized variable 12196 // definitions with reference type. 12197 if (Type->isReferenceType()) { 12198 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12199 << Var->getDeclName() 12200 << SourceRange(Var->getLocation(), Var->getLocation()); 12201 Var->setInvalidDecl(); 12202 return; 12203 } 12204 12205 // Do not attempt to type-check the default initializer for a 12206 // variable with dependent type. 12207 if (Type->isDependentType()) 12208 return; 12209 12210 if (Var->isInvalidDecl()) 12211 return; 12212 12213 if (!Var->hasAttr<AliasAttr>()) { 12214 if (RequireCompleteType(Var->getLocation(), 12215 Context.getBaseElementType(Type), 12216 diag::err_typecheck_decl_incomplete_type)) { 12217 Var->setInvalidDecl(); 12218 return; 12219 } 12220 } else { 12221 return; 12222 } 12223 12224 // The variable can not have an abstract class type. 12225 if (RequireNonAbstractType(Var->getLocation(), Type, 12226 diag::err_abstract_type_in_decl, 12227 AbstractVariableType)) { 12228 Var->setInvalidDecl(); 12229 return; 12230 } 12231 12232 // Check for jumps past the implicit initializer. C++0x 12233 // clarifies that this applies to a "variable with automatic 12234 // storage duration", not a "local variable". 12235 // C++11 [stmt.dcl]p3 12236 // A program that jumps from a point where a variable with automatic 12237 // storage duration is not in scope to a point where it is in scope is 12238 // ill-formed unless the variable has scalar type, class type with a 12239 // trivial default constructor and a trivial destructor, a cv-qualified 12240 // version of one of these types, or an array of one of the preceding 12241 // types and is declared without an initializer. 12242 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12243 if (const RecordType *Record 12244 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12245 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12246 // Mark the function (if we're in one) for further checking even if the 12247 // looser rules of C++11 do not require such checks, so that we can 12248 // diagnose incompatibilities with C++98. 12249 if (!CXXRecord->isPOD()) 12250 setFunctionHasBranchProtectedScope(); 12251 } 12252 } 12253 // In OpenCL, we can't initialize objects in the __local address space, 12254 // even implicitly, so don't synthesize an implicit initializer. 12255 if (getLangOpts().OpenCL && 12256 Var->getType().getAddressSpace() == LangAS::opencl_local) 12257 return; 12258 // C++03 [dcl.init]p9: 12259 // If no initializer is specified for an object, and the 12260 // object is of (possibly cv-qualified) non-POD class type (or 12261 // array thereof), the object shall be default-initialized; if 12262 // the object is of const-qualified type, the underlying class 12263 // type shall have a user-declared default 12264 // constructor. Otherwise, if no initializer is specified for 12265 // a non- static object, the object and its subobjects, if 12266 // any, have an indeterminate initial value); if the object 12267 // or any of its subobjects are of const-qualified type, the 12268 // program is ill-formed. 12269 // C++0x [dcl.init]p11: 12270 // If no initializer is specified for an object, the object is 12271 // default-initialized; [...]. 12272 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12273 InitializationKind Kind 12274 = InitializationKind::CreateDefault(Var->getLocation()); 12275 12276 InitializationSequence InitSeq(*this, Entity, Kind, None); 12277 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12278 if (Init.isInvalid()) 12279 Var->setInvalidDecl(); 12280 else if (Init.get()) { 12281 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12282 // This is important for template substitution. 12283 Var->setInitStyle(VarDecl::CallInit); 12284 } 12285 12286 CheckCompleteVariableDeclaration(Var); 12287 } 12288 } 12289 12290 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12291 // If there is no declaration, there was an error parsing it. Ignore it. 12292 if (!D) 12293 return; 12294 12295 VarDecl *VD = dyn_cast<VarDecl>(D); 12296 if (!VD) { 12297 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12298 D->setInvalidDecl(); 12299 return; 12300 } 12301 12302 VD->setCXXForRangeDecl(true); 12303 12304 // for-range-declaration cannot be given a storage class specifier. 12305 int Error = -1; 12306 switch (VD->getStorageClass()) { 12307 case SC_None: 12308 break; 12309 case SC_Extern: 12310 Error = 0; 12311 break; 12312 case SC_Static: 12313 Error = 1; 12314 break; 12315 case SC_PrivateExtern: 12316 Error = 2; 12317 break; 12318 case SC_Auto: 12319 Error = 3; 12320 break; 12321 case SC_Register: 12322 Error = 4; 12323 break; 12324 } 12325 if (Error != -1) { 12326 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12327 << VD->getDeclName() << Error; 12328 D->setInvalidDecl(); 12329 } 12330 } 12331 12332 StmtResult 12333 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12334 IdentifierInfo *Ident, 12335 ParsedAttributes &Attrs, 12336 SourceLocation AttrEnd) { 12337 // C++1y [stmt.iter]p1: 12338 // A range-based for statement of the form 12339 // for ( for-range-identifier : for-range-initializer ) statement 12340 // is equivalent to 12341 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12342 DeclSpec DS(Attrs.getPool().getFactory()); 12343 12344 const char *PrevSpec; 12345 unsigned DiagID; 12346 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12347 getPrintingPolicy()); 12348 12349 Declarator D(DS, DeclaratorContext::ForContext); 12350 D.SetIdentifier(Ident, IdentLoc); 12351 D.takeAttributes(Attrs, AttrEnd); 12352 12353 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12354 IdentLoc); 12355 Decl *Var = ActOnDeclarator(S, D); 12356 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12357 FinalizeDeclaration(Var); 12358 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12359 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12360 } 12361 12362 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12363 if (var->isInvalidDecl()) return; 12364 12365 if (getLangOpts().OpenCL) { 12366 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12367 // initialiser 12368 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12369 !var->hasInit()) { 12370 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12371 << 1 /*Init*/; 12372 var->setInvalidDecl(); 12373 return; 12374 } 12375 } 12376 12377 // In Objective-C, don't allow jumps past the implicit initialization of a 12378 // local retaining variable. 12379 if (getLangOpts().ObjC && 12380 var->hasLocalStorage()) { 12381 switch (var->getType().getObjCLifetime()) { 12382 case Qualifiers::OCL_None: 12383 case Qualifiers::OCL_ExplicitNone: 12384 case Qualifiers::OCL_Autoreleasing: 12385 break; 12386 12387 case Qualifiers::OCL_Weak: 12388 case Qualifiers::OCL_Strong: 12389 setFunctionHasBranchProtectedScope(); 12390 break; 12391 } 12392 } 12393 12394 if (var->hasLocalStorage() && 12395 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12396 setFunctionHasBranchProtectedScope(); 12397 12398 // Warn about externally-visible variables being defined without a 12399 // prior declaration. We only want to do this for global 12400 // declarations, but we also specifically need to avoid doing it for 12401 // class members because the linkage of an anonymous class can 12402 // change if it's later given a typedef name. 12403 if (var->isThisDeclarationADefinition() && 12404 var->getDeclContext()->getRedeclContext()->isFileContext() && 12405 var->isExternallyVisible() && var->hasLinkage() && 12406 !var->isInline() && !var->getDescribedVarTemplate() && 12407 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12408 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12409 var->getLocation())) { 12410 // Find a previous declaration that's not a definition. 12411 VarDecl *prev = var->getPreviousDecl(); 12412 while (prev && prev->isThisDeclarationADefinition()) 12413 prev = prev->getPreviousDecl(); 12414 12415 if (!prev) { 12416 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12417 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12418 << /* variable */ 0; 12419 } 12420 } 12421 12422 // Cache the result of checking for constant initialization. 12423 Optional<bool> CacheHasConstInit; 12424 const Expr *CacheCulprit = nullptr; 12425 auto checkConstInit = [&]() mutable { 12426 if (!CacheHasConstInit) 12427 CacheHasConstInit = var->getInit()->isConstantInitializer( 12428 Context, var->getType()->isReferenceType(), &CacheCulprit); 12429 return *CacheHasConstInit; 12430 }; 12431 12432 if (var->getTLSKind() == VarDecl::TLS_Static) { 12433 if (var->getType().isDestructedType()) { 12434 // GNU C++98 edits for __thread, [basic.start.term]p3: 12435 // The type of an object with thread storage duration shall not 12436 // have a non-trivial destructor. 12437 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12438 if (getLangOpts().CPlusPlus11) 12439 Diag(var->getLocation(), diag::note_use_thread_local); 12440 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12441 if (!checkConstInit()) { 12442 // GNU C++98 edits for __thread, [basic.start.init]p4: 12443 // An object of thread storage duration shall not require dynamic 12444 // initialization. 12445 // FIXME: Need strict checking here. 12446 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12447 << CacheCulprit->getSourceRange(); 12448 if (getLangOpts().CPlusPlus11) 12449 Diag(var->getLocation(), diag::note_use_thread_local); 12450 } 12451 } 12452 } 12453 12454 // Apply section attributes and pragmas to global variables. 12455 bool GlobalStorage = var->hasGlobalStorage(); 12456 if (GlobalStorage && var->isThisDeclarationADefinition() && 12457 !inTemplateInstantiation()) { 12458 PragmaStack<StringLiteral *> *Stack = nullptr; 12459 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12460 if (var->getType().isConstQualified()) 12461 Stack = &ConstSegStack; 12462 else if (!var->getInit()) { 12463 Stack = &BSSSegStack; 12464 SectionFlags |= ASTContext::PSF_Write; 12465 } else { 12466 Stack = &DataSegStack; 12467 SectionFlags |= ASTContext::PSF_Write; 12468 } 12469 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12470 var->addAttr(SectionAttr::CreateImplicit( 12471 Context, Stack->CurrentValue->getString(), 12472 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12473 SectionAttr::Declspec_allocate)); 12474 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12475 if (UnifySection(SA->getName(), SectionFlags, var)) 12476 var->dropAttr<SectionAttr>(); 12477 12478 // Apply the init_seg attribute if this has an initializer. If the 12479 // initializer turns out to not be dynamic, we'll end up ignoring this 12480 // attribute. 12481 if (CurInitSeg && var->getInit()) 12482 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12483 CurInitSegLoc, 12484 AttributeCommonInfo::AS_Pragma)); 12485 } 12486 12487 // All the following checks are C++ only. 12488 if (!getLangOpts().CPlusPlus) { 12489 // If this variable must be emitted, add it as an initializer for the 12490 // current module. 12491 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12492 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12493 return; 12494 } 12495 12496 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12497 CheckCompleteDecompositionDeclaration(DD); 12498 12499 QualType type = var->getType(); 12500 if (type->isDependentType()) return; 12501 12502 if (var->hasAttr<BlocksAttr>()) 12503 getCurFunction()->addByrefBlockVar(var); 12504 12505 Expr *Init = var->getInit(); 12506 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12507 QualType baseType = Context.getBaseElementType(type); 12508 12509 if (Init && !Init->isValueDependent()) { 12510 if (var->isConstexpr()) { 12511 SmallVector<PartialDiagnosticAt, 8> Notes; 12512 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12513 SourceLocation DiagLoc = var->getLocation(); 12514 // If the note doesn't add any useful information other than a source 12515 // location, fold it into the primary diagnostic. 12516 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12517 diag::note_invalid_subexpr_in_const_expr) { 12518 DiagLoc = Notes[0].first; 12519 Notes.clear(); 12520 } 12521 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12522 << var << Init->getSourceRange(); 12523 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12524 Diag(Notes[I].first, Notes[I].second); 12525 } 12526 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12527 // Check whether the initializer of a const variable of integral or 12528 // enumeration type is an ICE now, since we can't tell whether it was 12529 // initialized by a constant expression if we check later. 12530 var->checkInitIsICE(); 12531 } 12532 12533 // Don't emit further diagnostics about constexpr globals since they 12534 // were just diagnosed. 12535 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12536 // FIXME: Need strict checking in C++03 here. 12537 bool DiagErr = getLangOpts().CPlusPlus11 12538 ? !var->checkInitIsICE() : !checkConstInit(); 12539 if (DiagErr) { 12540 auto *Attr = var->getAttr<ConstInitAttr>(); 12541 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12542 << Init->getSourceRange(); 12543 Diag(Attr->getLocation(), 12544 diag::note_declared_required_constant_init_here) 12545 << Attr->getRange() << Attr->isConstinit(); 12546 if (getLangOpts().CPlusPlus11) { 12547 APValue Value; 12548 SmallVector<PartialDiagnosticAt, 8> Notes; 12549 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12550 for (auto &it : Notes) 12551 Diag(it.first, it.second); 12552 } else { 12553 Diag(CacheCulprit->getExprLoc(), 12554 diag::note_invalid_subexpr_in_const_expr) 12555 << CacheCulprit->getSourceRange(); 12556 } 12557 } 12558 } 12559 else if (!var->isConstexpr() && IsGlobal && 12560 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12561 var->getLocation())) { 12562 // Warn about globals which don't have a constant initializer. Don't 12563 // warn about globals with a non-trivial destructor because we already 12564 // warned about them. 12565 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12566 if (!(RD && !RD->hasTrivialDestructor())) { 12567 if (!checkConstInit()) 12568 Diag(var->getLocation(), diag::warn_global_constructor) 12569 << Init->getSourceRange(); 12570 } 12571 } 12572 } 12573 12574 // Require the destructor. 12575 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12576 FinalizeVarWithDestructor(var, recordType); 12577 12578 // If this variable must be emitted, add it as an initializer for the current 12579 // module. 12580 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12581 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12582 } 12583 12584 /// Determines if a variable's alignment is dependent. 12585 static bool hasDependentAlignment(VarDecl *VD) { 12586 if (VD->getType()->isDependentType()) 12587 return true; 12588 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12589 if (I->isAlignmentDependent()) 12590 return true; 12591 return false; 12592 } 12593 12594 /// Check if VD needs to be dllexport/dllimport due to being in a 12595 /// dllexport/import function. 12596 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12597 assert(VD->isStaticLocal()); 12598 12599 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12600 12601 // Find outermost function when VD is in lambda function. 12602 while (FD && !getDLLAttr(FD) && 12603 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12604 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12605 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12606 } 12607 12608 if (!FD) 12609 return; 12610 12611 // Static locals inherit dll attributes from their function. 12612 if (Attr *A = getDLLAttr(FD)) { 12613 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12614 NewAttr->setInherited(true); 12615 VD->addAttr(NewAttr); 12616 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12617 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12618 NewAttr->setInherited(true); 12619 VD->addAttr(NewAttr); 12620 12621 // Export this function to enforce exporting this static variable even 12622 // if it is not used in this compilation unit. 12623 if (!FD->hasAttr<DLLExportAttr>()) 12624 FD->addAttr(NewAttr); 12625 12626 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12627 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12628 NewAttr->setInherited(true); 12629 VD->addAttr(NewAttr); 12630 } 12631 } 12632 12633 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12634 /// any semantic actions necessary after any initializer has been attached. 12635 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12636 // Note that we are no longer parsing the initializer for this declaration. 12637 ParsingInitForAutoVars.erase(ThisDecl); 12638 12639 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12640 if (!VD) 12641 return; 12642 12643 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12644 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12645 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12646 if (PragmaClangBSSSection.Valid) 12647 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12648 Context, PragmaClangBSSSection.SectionName, 12649 PragmaClangBSSSection.PragmaLocation, 12650 AttributeCommonInfo::AS_Pragma)); 12651 if (PragmaClangDataSection.Valid) 12652 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12653 Context, PragmaClangDataSection.SectionName, 12654 PragmaClangDataSection.PragmaLocation, 12655 AttributeCommonInfo::AS_Pragma)); 12656 if (PragmaClangRodataSection.Valid) 12657 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12658 Context, PragmaClangRodataSection.SectionName, 12659 PragmaClangRodataSection.PragmaLocation, 12660 AttributeCommonInfo::AS_Pragma)); 12661 if (PragmaClangRelroSection.Valid) 12662 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12663 Context, PragmaClangRelroSection.SectionName, 12664 PragmaClangRelroSection.PragmaLocation, 12665 AttributeCommonInfo::AS_Pragma)); 12666 } 12667 12668 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12669 for (auto *BD : DD->bindings()) { 12670 FinalizeDeclaration(BD); 12671 } 12672 } 12673 12674 checkAttributesAfterMerging(*this, *VD); 12675 12676 // Perform TLS alignment check here after attributes attached to the variable 12677 // which may affect the alignment have been processed. Only perform the check 12678 // if the target has a maximum TLS alignment (zero means no constraints). 12679 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12680 // Protect the check so that it's not performed on dependent types and 12681 // dependent alignments (we can't determine the alignment in that case). 12682 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12683 !VD->isInvalidDecl()) { 12684 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12685 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12686 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12687 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12688 << (unsigned)MaxAlignChars.getQuantity(); 12689 } 12690 } 12691 } 12692 12693 if (VD->isStaticLocal()) { 12694 CheckStaticLocalForDllExport(VD); 12695 12696 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12697 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12698 // function, only __shared__ variables or variables without any device 12699 // memory qualifiers may be declared with static storage class. 12700 // Note: It is unclear how a function-scope non-const static variable 12701 // without device memory qualifier is implemented, therefore only static 12702 // const variable without device memory qualifier is allowed. 12703 [&]() { 12704 if (!getLangOpts().CUDA) 12705 return; 12706 if (VD->hasAttr<CUDASharedAttr>()) 12707 return; 12708 if (VD->getType().isConstQualified() && 12709 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12710 return; 12711 if (CUDADiagIfDeviceCode(VD->getLocation(), 12712 diag::err_device_static_local_var) 12713 << CurrentCUDATarget()) 12714 VD->setInvalidDecl(); 12715 }(); 12716 } 12717 } 12718 12719 // Perform check for initializers of device-side global variables. 12720 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12721 // 7.5). We must also apply the same checks to all __shared__ 12722 // variables whether they are local or not. CUDA also allows 12723 // constant initializers for __constant__ and __device__ variables. 12724 if (getLangOpts().CUDA) 12725 checkAllowedCUDAInitializer(VD); 12726 12727 // Grab the dllimport or dllexport attribute off of the VarDecl. 12728 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12729 12730 // Imported static data members cannot be defined out-of-line. 12731 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12732 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12733 VD->isThisDeclarationADefinition()) { 12734 // We allow definitions of dllimport class template static data members 12735 // with a warning. 12736 CXXRecordDecl *Context = 12737 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12738 bool IsClassTemplateMember = 12739 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12740 Context->getDescribedClassTemplate(); 12741 12742 Diag(VD->getLocation(), 12743 IsClassTemplateMember 12744 ? diag::warn_attribute_dllimport_static_field_definition 12745 : diag::err_attribute_dllimport_static_field_definition); 12746 Diag(IA->getLocation(), diag::note_attribute); 12747 if (!IsClassTemplateMember) 12748 VD->setInvalidDecl(); 12749 } 12750 } 12751 12752 // dllimport/dllexport variables cannot be thread local, their TLS index 12753 // isn't exported with the variable. 12754 if (DLLAttr && VD->getTLSKind()) { 12755 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12756 if (F && getDLLAttr(F)) { 12757 assert(VD->isStaticLocal()); 12758 // But if this is a static local in a dlimport/dllexport function, the 12759 // function will never be inlined, which means the var would never be 12760 // imported, so having it marked import/export is safe. 12761 } else { 12762 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12763 << DLLAttr; 12764 VD->setInvalidDecl(); 12765 } 12766 } 12767 12768 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12769 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12770 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12771 VD->dropAttr<UsedAttr>(); 12772 } 12773 } 12774 12775 const DeclContext *DC = VD->getDeclContext(); 12776 // If there's a #pragma GCC visibility in scope, and this isn't a class 12777 // member, set the visibility of this variable. 12778 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12779 AddPushedVisibilityAttribute(VD); 12780 12781 // FIXME: Warn on unused var template partial specializations. 12782 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12783 MarkUnusedFileScopedDecl(VD); 12784 12785 // Now we have parsed the initializer and can update the table of magic 12786 // tag values. 12787 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12788 !VD->getType()->isIntegralOrEnumerationType()) 12789 return; 12790 12791 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12792 const Expr *MagicValueExpr = VD->getInit(); 12793 if (!MagicValueExpr) { 12794 continue; 12795 } 12796 llvm::APSInt MagicValueInt; 12797 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12798 Diag(I->getRange().getBegin(), 12799 diag::err_type_tag_for_datatype_not_ice) 12800 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12801 continue; 12802 } 12803 if (MagicValueInt.getActiveBits() > 64) { 12804 Diag(I->getRange().getBegin(), 12805 diag::err_type_tag_for_datatype_too_large) 12806 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12807 continue; 12808 } 12809 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12810 RegisterTypeTagForDatatype(I->getArgumentKind(), 12811 MagicValue, 12812 I->getMatchingCType(), 12813 I->getLayoutCompatible(), 12814 I->getMustBeNull()); 12815 } 12816 } 12817 12818 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12819 auto *VD = dyn_cast<VarDecl>(DD); 12820 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12821 } 12822 12823 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12824 ArrayRef<Decl *> Group) { 12825 SmallVector<Decl*, 8> Decls; 12826 12827 if (DS.isTypeSpecOwned()) 12828 Decls.push_back(DS.getRepAsDecl()); 12829 12830 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12831 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12832 bool DiagnosedMultipleDecomps = false; 12833 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12834 bool DiagnosedNonDeducedAuto = false; 12835 12836 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12837 if (Decl *D = Group[i]) { 12838 // For declarators, there are some additional syntactic-ish checks we need 12839 // to perform. 12840 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12841 if (!FirstDeclaratorInGroup) 12842 FirstDeclaratorInGroup = DD; 12843 if (!FirstDecompDeclaratorInGroup) 12844 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12845 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12846 !hasDeducedAuto(DD)) 12847 FirstNonDeducedAutoInGroup = DD; 12848 12849 if (FirstDeclaratorInGroup != DD) { 12850 // A decomposition declaration cannot be combined with any other 12851 // declaration in the same group. 12852 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12853 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12854 diag::err_decomp_decl_not_alone) 12855 << FirstDeclaratorInGroup->getSourceRange() 12856 << DD->getSourceRange(); 12857 DiagnosedMultipleDecomps = true; 12858 } 12859 12860 // A declarator that uses 'auto' in any way other than to declare a 12861 // variable with a deduced type cannot be combined with any other 12862 // declarator in the same group. 12863 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12864 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12865 diag::err_auto_non_deduced_not_alone) 12866 << FirstNonDeducedAutoInGroup->getType() 12867 ->hasAutoForTrailingReturnType() 12868 << FirstDeclaratorInGroup->getSourceRange() 12869 << DD->getSourceRange(); 12870 DiagnosedNonDeducedAuto = true; 12871 } 12872 } 12873 } 12874 12875 Decls.push_back(D); 12876 } 12877 } 12878 12879 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12880 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12881 handleTagNumbering(Tag, S); 12882 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12883 getLangOpts().CPlusPlus) 12884 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12885 } 12886 } 12887 12888 return BuildDeclaratorGroup(Decls); 12889 } 12890 12891 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12892 /// group, performing any necessary semantic checking. 12893 Sema::DeclGroupPtrTy 12894 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12895 // C++14 [dcl.spec.auto]p7: (DR1347) 12896 // If the type that replaces the placeholder type is not the same in each 12897 // deduction, the program is ill-formed. 12898 if (Group.size() > 1) { 12899 QualType Deduced; 12900 VarDecl *DeducedDecl = nullptr; 12901 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12902 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12903 if (!D || D->isInvalidDecl()) 12904 break; 12905 DeducedType *DT = D->getType()->getContainedDeducedType(); 12906 if (!DT || DT->getDeducedType().isNull()) 12907 continue; 12908 if (Deduced.isNull()) { 12909 Deduced = DT->getDeducedType(); 12910 DeducedDecl = D; 12911 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12912 auto *AT = dyn_cast<AutoType>(DT); 12913 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12914 diag::err_auto_different_deductions) 12915 << (AT ? (unsigned)AT->getKeyword() : 3) 12916 << Deduced << DeducedDecl->getDeclName() 12917 << DT->getDeducedType() << D->getDeclName() 12918 << DeducedDecl->getInit()->getSourceRange() 12919 << D->getInit()->getSourceRange(); 12920 D->setInvalidDecl(); 12921 break; 12922 } 12923 } 12924 } 12925 12926 ActOnDocumentableDecls(Group); 12927 12928 return DeclGroupPtrTy::make( 12929 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12930 } 12931 12932 void Sema::ActOnDocumentableDecl(Decl *D) { 12933 ActOnDocumentableDecls(D); 12934 } 12935 12936 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12937 // Don't parse the comment if Doxygen diagnostics are ignored. 12938 if (Group.empty() || !Group[0]) 12939 return; 12940 12941 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12942 Group[0]->getLocation()) && 12943 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12944 Group[0]->getLocation())) 12945 return; 12946 12947 if (Group.size() >= 2) { 12948 // This is a decl group. Normally it will contain only declarations 12949 // produced from declarator list. But in case we have any definitions or 12950 // additional declaration references: 12951 // 'typedef struct S {} S;' 12952 // 'typedef struct S *S;' 12953 // 'struct S *pS;' 12954 // FinalizeDeclaratorGroup adds these as separate declarations. 12955 Decl *MaybeTagDecl = Group[0]; 12956 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12957 Group = Group.slice(1); 12958 } 12959 } 12960 12961 // FIMXE: We assume every Decl in the group is in the same file. 12962 // This is false when preprocessor constructs the group from decls in 12963 // different files (e. g. macros or #include). 12964 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 12965 } 12966 12967 /// Common checks for a parameter-declaration that should apply to both function 12968 /// parameters and non-type template parameters. 12969 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 12970 // Check that there are no default arguments inside the type of this 12971 // parameter. 12972 if (getLangOpts().CPlusPlus) 12973 CheckExtraCXXDefaultArguments(D); 12974 12975 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12976 if (D.getCXXScopeSpec().isSet()) { 12977 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12978 << D.getCXXScopeSpec().getRange(); 12979 } 12980 12981 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 12982 // simple identifier except [...irrelevant cases...]. 12983 switch (D.getName().getKind()) { 12984 case UnqualifiedIdKind::IK_Identifier: 12985 break; 12986 12987 case UnqualifiedIdKind::IK_OperatorFunctionId: 12988 case UnqualifiedIdKind::IK_ConversionFunctionId: 12989 case UnqualifiedIdKind::IK_LiteralOperatorId: 12990 case UnqualifiedIdKind::IK_ConstructorName: 12991 case UnqualifiedIdKind::IK_DestructorName: 12992 case UnqualifiedIdKind::IK_ImplicitSelfParam: 12993 case UnqualifiedIdKind::IK_DeductionGuideName: 12994 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12995 << GetNameForDeclarator(D).getName(); 12996 break; 12997 12998 case UnqualifiedIdKind::IK_TemplateId: 12999 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13000 // GetNameForDeclarator would not produce a useful name in this case. 13001 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13002 break; 13003 } 13004 } 13005 13006 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13007 /// to introduce parameters into function prototype scope. 13008 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13009 const DeclSpec &DS = D.getDeclSpec(); 13010 13011 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13012 13013 // C++03 [dcl.stc]p2 also permits 'auto'. 13014 StorageClass SC = SC_None; 13015 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13016 SC = SC_Register; 13017 // In C++11, the 'register' storage class specifier is deprecated. 13018 // In C++17, it is not allowed, but we tolerate it as an extension. 13019 if (getLangOpts().CPlusPlus11) { 13020 Diag(DS.getStorageClassSpecLoc(), 13021 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13022 : diag::warn_deprecated_register) 13023 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13024 } 13025 } else if (getLangOpts().CPlusPlus && 13026 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13027 SC = SC_Auto; 13028 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13029 Diag(DS.getStorageClassSpecLoc(), 13030 diag::err_invalid_storage_class_in_func_decl); 13031 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13032 } 13033 13034 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13035 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13036 << DeclSpec::getSpecifierName(TSCS); 13037 if (DS.isInlineSpecified()) 13038 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13039 << getLangOpts().CPlusPlus17; 13040 if (DS.hasConstexprSpecifier()) 13041 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13042 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13043 13044 DiagnoseFunctionSpecifiers(DS); 13045 13046 CheckFunctionOrTemplateParamDeclarator(S, D); 13047 13048 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13049 QualType parmDeclType = TInfo->getType(); 13050 13051 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13052 IdentifierInfo *II = D.getIdentifier(); 13053 if (II) { 13054 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13055 ForVisibleRedeclaration); 13056 LookupName(R, S); 13057 if (R.isSingleResult()) { 13058 NamedDecl *PrevDecl = R.getFoundDecl(); 13059 if (PrevDecl->isTemplateParameter()) { 13060 // Maybe we will complain about the shadowed template parameter. 13061 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13062 // Just pretend that we didn't see the previous declaration. 13063 PrevDecl = nullptr; 13064 } else if (S->isDeclScope(PrevDecl)) { 13065 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13066 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13067 13068 // Recover by removing the name 13069 II = nullptr; 13070 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13071 D.setInvalidType(true); 13072 } 13073 } 13074 } 13075 13076 // Temporarily put parameter variables in the translation unit, not 13077 // the enclosing context. This prevents them from accidentally 13078 // looking like class members in C++. 13079 ParmVarDecl *New = 13080 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13081 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13082 13083 if (D.isInvalidType()) 13084 New->setInvalidDecl(); 13085 13086 assert(S->isFunctionPrototypeScope()); 13087 assert(S->getFunctionPrototypeDepth() >= 1); 13088 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13089 S->getNextFunctionPrototypeIndex()); 13090 13091 // Add the parameter declaration into this scope. 13092 S->AddDecl(New); 13093 if (II) 13094 IdResolver.AddDecl(New); 13095 13096 ProcessDeclAttributes(S, New, D); 13097 13098 if (D.getDeclSpec().isModulePrivateSpecified()) 13099 Diag(New->getLocation(), diag::err_module_private_local) 13100 << 1 << New->getDeclName() 13101 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13102 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13103 13104 if (New->hasAttr<BlocksAttr>()) { 13105 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13106 } 13107 return New; 13108 } 13109 13110 /// Synthesizes a variable for a parameter arising from a 13111 /// typedef. 13112 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13113 SourceLocation Loc, 13114 QualType T) { 13115 /* FIXME: setting StartLoc == Loc. 13116 Would it be worth to modify callers so as to provide proper source 13117 location for the unnamed parameters, embedding the parameter's type? */ 13118 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13119 T, Context.getTrivialTypeSourceInfo(T, Loc), 13120 SC_None, nullptr); 13121 Param->setImplicit(); 13122 return Param; 13123 } 13124 13125 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13126 // Don't diagnose unused-parameter errors in template instantiations; we 13127 // will already have done so in the template itself. 13128 if (inTemplateInstantiation()) 13129 return; 13130 13131 for (const ParmVarDecl *Parameter : Parameters) { 13132 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13133 !Parameter->hasAttr<UnusedAttr>()) { 13134 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13135 << Parameter->getDeclName(); 13136 } 13137 } 13138 } 13139 13140 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13141 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13142 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13143 return; 13144 13145 // Warn if the return value is pass-by-value and larger than the specified 13146 // threshold. 13147 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13148 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13149 if (Size > LangOpts.NumLargeByValueCopy) 13150 Diag(D->getLocation(), diag::warn_return_value_size) 13151 << D->getDeclName() << Size; 13152 } 13153 13154 // Warn if any parameter is pass-by-value and larger than the specified 13155 // threshold. 13156 for (const ParmVarDecl *Parameter : Parameters) { 13157 QualType T = Parameter->getType(); 13158 if (T->isDependentType() || !T.isPODType(Context)) 13159 continue; 13160 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13161 if (Size > LangOpts.NumLargeByValueCopy) 13162 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13163 << Parameter->getDeclName() << Size; 13164 } 13165 } 13166 13167 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13168 SourceLocation NameLoc, IdentifierInfo *Name, 13169 QualType T, TypeSourceInfo *TSInfo, 13170 StorageClass SC) { 13171 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13172 if (getLangOpts().ObjCAutoRefCount && 13173 T.getObjCLifetime() == Qualifiers::OCL_None && 13174 T->isObjCLifetimeType()) { 13175 13176 Qualifiers::ObjCLifetime lifetime; 13177 13178 // Special cases for arrays: 13179 // - if it's const, use __unsafe_unretained 13180 // - otherwise, it's an error 13181 if (T->isArrayType()) { 13182 if (!T.isConstQualified()) { 13183 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13184 DelayedDiagnostics.add( 13185 sema::DelayedDiagnostic::makeForbiddenType( 13186 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13187 else 13188 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13189 << TSInfo->getTypeLoc().getSourceRange(); 13190 } 13191 lifetime = Qualifiers::OCL_ExplicitNone; 13192 } else { 13193 lifetime = T->getObjCARCImplicitLifetime(); 13194 } 13195 T = Context.getLifetimeQualifiedType(T, lifetime); 13196 } 13197 13198 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13199 Context.getAdjustedParameterType(T), 13200 TSInfo, SC, nullptr); 13201 13202 // Make a note if we created a new pack in the scope of a lambda, so that 13203 // we know that references to that pack must also be expanded within the 13204 // lambda scope. 13205 if (New->isParameterPack()) 13206 if (auto *LSI = getEnclosingLambda()) 13207 LSI->LocalPacks.push_back(New); 13208 13209 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13210 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13211 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13212 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13213 13214 // Parameters can not be abstract class types. 13215 // For record types, this is done by the AbstractClassUsageDiagnoser once 13216 // the class has been completely parsed. 13217 if (!CurContext->isRecord() && 13218 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13219 AbstractParamType)) 13220 New->setInvalidDecl(); 13221 13222 // Parameter declarators cannot be interface types. All ObjC objects are 13223 // passed by reference. 13224 if (T->isObjCObjectType()) { 13225 SourceLocation TypeEndLoc = 13226 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13227 Diag(NameLoc, 13228 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13229 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13230 T = Context.getObjCObjectPointerType(T); 13231 New->setType(T); 13232 } 13233 13234 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13235 // duration shall not be qualified by an address-space qualifier." 13236 // Since all parameters have automatic store duration, they can not have 13237 // an address space. 13238 if (T.getAddressSpace() != LangAS::Default && 13239 // OpenCL allows function arguments declared to be an array of a type 13240 // to be qualified with an address space. 13241 !(getLangOpts().OpenCL && 13242 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13243 Diag(NameLoc, diag::err_arg_with_address_space); 13244 New->setInvalidDecl(); 13245 } 13246 13247 return New; 13248 } 13249 13250 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13251 SourceLocation LocAfterDecls) { 13252 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13253 13254 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13255 // for a K&R function. 13256 if (!FTI.hasPrototype) { 13257 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13258 --i; 13259 if (FTI.Params[i].Param == nullptr) { 13260 SmallString<256> Code; 13261 llvm::raw_svector_ostream(Code) 13262 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13263 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13264 << FTI.Params[i].Ident 13265 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13266 13267 // Implicitly declare the argument as type 'int' for lack of a better 13268 // type. 13269 AttributeFactory attrs; 13270 DeclSpec DS(attrs); 13271 const char* PrevSpec; // unused 13272 unsigned DiagID; // unused 13273 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13274 DiagID, Context.getPrintingPolicy()); 13275 // Use the identifier location for the type source range. 13276 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13277 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13278 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13279 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13280 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13281 } 13282 } 13283 } 13284 } 13285 13286 Decl * 13287 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13288 MultiTemplateParamsArg TemplateParameterLists, 13289 SkipBodyInfo *SkipBody) { 13290 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13291 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13292 Scope *ParentScope = FnBodyScope->getParent(); 13293 13294 D.setFunctionDefinitionKind(FDK_Definition); 13295 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13296 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13297 } 13298 13299 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13300 Consumer.HandleInlineFunctionDefinition(D); 13301 } 13302 13303 static bool 13304 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13305 const FunctionDecl *&PossiblePrototype) { 13306 // Don't warn about invalid declarations. 13307 if (FD->isInvalidDecl()) 13308 return false; 13309 13310 // Or declarations that aren't global. 13311 if (!FD->isGlobal()) 13312 return false; 13313 13314 // Don't warn about C++ member functions. 13315 if (isa<CXXMethodDecl>(FD)) 13316 return false; 13317 13318 // Don't warn about 'main'. 13319 if (FD->isMain()) 13320 return false; 13321 13322 // Don't warn about inline functions. 13323 if (FD->isInlined()) 13324 return false; 13325 13326 // Don't warn about function templates. 13327 if (FD->getDescribedFunctionTemplate()) 13328 return false; 13329 13330 // Don't warn about function template specializations. 13331 if (FD->isFunctionTemplateSpecialization()) 13332 return false; 13333 13334 // Don't warn for OpenCL kernels. 13335 if (FD->hasAttr<OpenCLKernelAttr>()) 13336 return false; 13337 13338 // Don't warn on explicitly deleted functions. 13339 if (FD->isDeleted()) 13340 return false; 13341 13342 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13343 Prev; Prev = Prev->getPreviousDecl()) { 13344 // Ignore any declarations that occur in function or method 13345 // scope, because they aren't visible from the header. 13346 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13347 continue; 13348 13349 PossiblePrototype = Prev; 13350 return Prev->getType()->isFunctionNoProtoType(); 13351 } 13352 13353 return true; 13354 } 13355 13356 void 13357 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13358 const FunctionDecl *EffectiveDefinition, 13359 SkipBodyInfo *SkipBody) { 13360 const FunctionDecl *Definition = EffectiveDefinition; 13361 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13362 // If this is a friend function defined in a class template, it does not 13363 // have a body until it is used, nevertheless it is a definition, see 13364 // [temp.inst]p2: 13365 // 13366 // ... for the purpose of determining whether an instantiated redeclaration 13367 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13368 // corresponds to a definition in the template is considered to be a 13369 // definition. 13370 // 13371 // The following code must produce redefinition error: 13372 // 13373 // template<typename T> struct C20 { friend void func_20() {} }; 13374 // C20<int> c20i; 13375 // void func_20() {} 13376 // 13377 for (auto I : FD->redecls()) { 13378 if (I != FD && !I->isInvalidDecl() && 13379 I->getFriendObjectKind() != Decl::FOK_None) { 13380 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13381 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13382 // A merged copy of the same function, instantiated as a member of 13383 // the same class, is OK. 13384 if (declaresSameEntity(OrigFD, Original) && 13385 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13386 cast<Decl>(FD->getLexicalDeclContext()))) 13387 continue; 13388 } 13389 13390 if (Original->isThisDeclarationADefinition()) { 13391 Definition = I; 13392 break; 13393 } 13394 } 13395 } 13396 } 13397 } 13398 13399 if (!Definition) 13400 // Similar to friend functions a friend function template may be a 13401 // definition and do not have a body if it is instantiated in a class 13402 // template. 13403 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13404 for (auto I : FTD->redecls()) { 13405 auto D = cast<FunctionTemplateDecl>(I); 13406 if (D != FTD) { 13407 assert(!D->isThisDeclarationADefinition() && 13408 "More than one definition in redeclaration chain"); 13409 if (D->getFriendObjectKind() != Decl::FOK_None) 13410 if (FunctionTemplateDecl *FT = 13411 D->getInstantiatedFromMemberTemplate()) { 13412 if (FT->isThisDeclarationADefinition()) { 13413 Definition = D->getTemplatedDecl(); 13414 break; 13415 } 13416 } 13417 } 13418 } 13419 } 13420 13421 if (!Definition) 13422 return; 13423 13424 if (canRedefineFunction(Definition, getLangOpts())) 13425 return; 13426 13427 // Don't emit an error when this is redefinition of a typo-corrected 13428 // definition. 13429 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13430 return; 13431 13432 // If we don't have a visible definition of the function, and it's inline or 13433 // a template, skip the new definition. 13434 if (SkipBody && !hasVisibleDefinition(Definition) && 13435 (Definition->getFormalLinkage() == InternalLinkage || 13436 Definition->isInlined() || 13437 Definition->getDescribedFunctionTemplate() || 13438 Definition->getNumTemplateParameterLists())) { 13439 SkipBody->ShouldSkip = true; 13440 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13441 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13442 makeMergedDefinitionVisible(TD); 13443 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13444 return; 13445 } 13446 13447 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13448 Definition->getStorageClass() == SC_Extern) 13449 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13450 << FD->getDeclName() << getLangOpts().CPlusPlus; 13451 else 13452 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13453 13454 Diag(Definition->getLocation(), diag::note_previous_definition); 13455 FD->setInvalidDecl(); 13456 } 13457 13458 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13459 Sema &S) { 13460 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13461 13462 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13463 LSI->CallOperator = CallOperator; 13464 LSI->Lambda = LambdaClass; 13465 LSI->ReturnType = CallOperator->getReturnType(); 13466 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13467 13468 if (LCD == LCD_None) 13469 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13470 else if (LCD == LCD_ByCopy) 13471 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13472 else if (LCD == LCD_ByRef) 13473 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13474 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13475 13476 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13477 LSI->Mutable = !CallOperator->isConst(); 13478 13479 // Add the captures to the LSI so they can be noted as already 13480 // captured within tryCaptureVar. 13481 auto I = LambdaClass->field_begin(); 13482 for (const auto &C : LambdaClass->captures()) { 13483 if (C.capturesVariable()) { 13484 VarDecl *VD = C.getCapturedVar(); 13485 if (VD->isInitCapture()) 13486 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13487 QualType CaptureType = VD->getType(); 13488 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13489 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13490 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13491 /*EllipsisLoc*/C.isPackExpansion() 13492 ? C.getEllipsisLoc() : SourceLocation(), 13493 CaptureType, /*Invalid*/false); 13494 13495 } else if (C.capturesThis()) { 13496 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13497 C.getCaptureKind() == LCK_StarThis); 13498 } else { 13499 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13500 I->getType()); 13501 } 13502 ++I; 13503 } 13504 } 13505 13506 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13507 SkipBodyInfo *SkipBody) { 13508 if (!D) { 13509 // Parsing the function declaration failed in some way. Push on a fake scope 13510 // anyway so we can try to parse the function body. 13511 PushFunctionScope(); 13512 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13513 return D; 13514 } 13515 13516 FunctionDecl *FD = nullptr; 13517 13518 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13519 FD = FunTmpl->getTemplatedDecl(); 13520 else 13521 FD = cast<FunctionDecl>(D); 13522 13523 // Do not push if it is a lambda because one is already pushed when building 13524 // the lambda in ActOnStartOfLambdaDefinition(). 13525 if (!isLambdaCallOperator(FD)) 13526 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13527 13528 // Check for defining attributes before the check for redefinition. 13529 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13530 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13531 FD->dropAttr<AliasAttr>(); 13532 FD->setInvalidDecl(); 13533 } 13534 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13535 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13536 FD->dropAttr<IFuncAttr>(); 13537 FD->setInvalidDecl(); 13538 } 13539 13540 // See if this is a redefinition. If 'will have body' is already set, then 13541 // these checks were already performed when it was set. 13542 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13543 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13544 13545 // If we're skipping the body, we're done. Don't enter the scope. 13546 if (SkipBody && SkipBody->ShouldSkip) 13547 return D; 13548 } 13549 13550 // Mark this function as "will have a body eventually". This lets users to 13551 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13552 // this function. 13553 FD->setWillHaveBody(); 13554 13555 // If we are instantiating a generic lambda call operator, push 13556 // a LambdaScopeInfo onto the function stack. But use the information 13557 // that's already been calculated (ActOnLambdaExpr) to prime the current 13558 // LambdaScopeInfo. 13559 // When the template operator is being specialized, the LambdaScopeInfo, 13560 // has to be properly restored so that tryCaptureVariable doesn't try 13561 // and capture any new variables. In addition when calculating potential 13562 // captures during transformation of nested lambdas, it is necessary to 13563 // have the LSI properly restored. 13564 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13565 assert(inTemplateInstantiation() && 13566 "There should be an active template instantiation on the stack " 13567 "when instantiating a generic lambda!"); 13568 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13569 } else { 13570 // Enter a new function scope 13571 PushFunctionScope(); 13572 } 13573 13574 // Builtin functions cannot be defined. 13575 if (unsigned BuiltinID = FD->getBuiltinID()) { 13576 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13577 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13578 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13579 FD->setInvalidDecl(); 13580 } 13581 } 13582 13583 // The return type of a function definition must be complete 13584 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13585 QualType ResultType = FD->getReturnType(); 13586 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13587 !FD->isInvalidDecl() && 13588 RequireCompleteType(FD->getLocation(), ResultType, 13589 diag::err_func_def_incomplete_result)) 13590 FD->setInvalidDecl(); 13591 13592 if (FnBodyScope) 13593 PushDeclContext(FnBodyScope, FD); 13594 13595 // Check the validity of our function parameters 13596 CheckParmsForFunctionDef(FD->parameters(), 13597 /*CheckParameterNames=*/true); 13598 13599 // Add non-parameter declarations already in the function to the current 13600 // scope. 13601 if (FnBodyScope) { 13602 for (Decl *NPD : FD->decls()) { 13603 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13604 if (!NonParmDecl) 13605 continue; 13606 assert(!isa<ParmVarDecl>(NonParmDecl) && 13607 "parameters should not be in newly created FD yet"); 13608 13609 // If the decl has a name, make it accessible in the current scope. 13610 if (NonParmDecl->getDeclName()) 13611 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13612 13613 // Similarly, dive into enums and fish their constants out, making them 13614 // accessible in this scope. 13615 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13616 for (auto *EI : ED->enumerators()) 13617 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13618 } 13619 } 13620 } 13621 13622 // Introduce our parameters into the function scope 13623 for (auto Param : FD->parameters()) { 13624 Param->setOwningFunction(FD); 13625 13626 // If this has an identifier, add it to the scope stack. 13627 if (Param->getIdentifier() && FnBodyScope) { 13628 CheckShadow(FnBodyScope, Param); 13629 13630 PushOnScopeChains(Param, FnBodyScope); 13631 } 13632 } 13633 13634 // Ensure that the function's exception specification is instantiated. 13635 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13636 ResolveExceptionSpec(D->getLocation(), FPT); 13637 13638 // dllimport cannot be applied to non-inline function definitions. 13639 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13640 !FD->isTemplateInstantiation()) { 13641 assert(!FD->hasAttr<DLLExportAttr>()); 13642 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13643 FD->setInvalidDecl(); 13644 return D; 13645 } 13646 // We want to attach documentation to original Decl (which might be 13647 // a function template). 13648 ActOnDocumentableDecl(D); 13649 if (getCurLexicalContext()->isObjCContainer() && 13650 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13651 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13652 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13653 13654 return D; 13655 } 13656 13657 /// Given the set of return statements within a function body, 13658 /// compute the variables that are subject to the named return value 13659 /// optimization. 13660 /// 13661 /// Each of the variables that is subject to the named return value 13662 /// optimization will be marked as NRVO variables in the AST, and any 13663 /// return statement that has a marked NRVO variable as its NRVO candidate can 13664 /// use the named return value optimization. 13665 /// 13666 /// This function applies a very simplistic algorithm for NRVO: if every return 13667 /// statement in the scope of a variable has the same NRVO candidate, that 13668 /// candidate is an NRVO variable. 13669 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13670 ReturnStmt **Returns = Scope->Returns.data(); 13671 13672 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13673 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13674 if (!NRVOCandidate->isNRVOVariable()) 13675 Returns[I]->setNRVOCandidate(nullptr); 13676 } 13677 } 13678 } 13679 13680 bool Sema::canDelayFunctionBody(const Declarator &D) { 13681 // We can't delay parsing the body of a constexpr function template (yet). 13682 if (D.getDeclSpec().hasConstexprSpecifier()) 13683 return false; 13684 13685 // We can't delay parsing the body of a function template with a deduced 13686 // return type (yet). 13687 if (D.getDeclSpec().hasAutoTypeSpec()) { 13688 // If the placeholder introduces a non-deduced trailing return type, 13689 // we can still delay parsing it. 13690 if (D.getNumTypeObjects()) { 13691 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13692 if (Outer.Kind == DeclaratorChunk::Function && 13693 Outer.Fun.hasTrailingReturnType()) { 13694 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13695 return Ty.isNull() || !Ty->isUndeducedType(); 13696 } 13697 } 13698 return false; 13699 } 13700 13701 return true; 13702 } 13703 13704 bool Sema::canSkipFunctionBody(Decl *D) { 13705 // We cannot skip the body of a function (or function template) which is 13706 // constexpr, since we may need to evaluate its body in order to parse the 13707 // rest of the file. 13708 // We cannot skip the body of a function with an undeduced return type, 13709 // because any callers of that function need to know the type. 13710 if (const FunctionDecl *FD = D->getAsFunction()) { 13711 if (FD->isConstexpr()) 13712 return false; 13713 // We can't simply call Type::isUndeducedType here, because inside template 13714 // auto can be deduced to a dependent type, which is not considered 13715 // "undeduced". 13716 if (FD->getReturnType()->getContainedDeducedType()) 13717 return false; 13718 } 13719 return Consumer.shouldSkipFunctionBody(D); 13720 } 13721 13722 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13723 if (!Decl) 13724 return nullptr; 13725 if (FunctionDecl *FD = Decl->getAsFunction()) 13726 FD->setHasSkippedBody(); 13727 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13728 MD->setHasSkippedBody(); 13729 return Decl; 13730 } 13731 13732 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13733 return ActOnFinishFunctionBody(D, BodyArg, false); 13734 } 13735 13736 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13737 /// body. 13738 class ExitFunctionBodyRAII { 13739 public: 13740 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13741 ~ExitFunctionBodyRAII() { 13742 if (!IsLambda) 13743 S.PopExpressionEvaluationContext(); 13744 } 13745 13746 private: 13747 Sema &S; 13748 bool IsLambda = false; 13749 }; 13750 13751 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13752 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13753 13754 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13755 if (EscapeInfo.count(BD)) 13756 return EscapeInfo[BD]; 13757 13758 bool R = false; 13759 const BlockDecl *CurBD = BD; 13760 13761 do { 13762 R = !CurBD->doesNotEscape(); 13763 if (R) 13764 break; 13765 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 13766 } while (CurBD); 13767 13768 return EscapeInfo[BD] = R; 13769 }; 13770 13771 // If the location where 'self' is implicitly retained is inside a escaping 13772 // block, emit a diagnostic. 13773 for (const std::pair<SourceLocation, const BlockDecl *> &P : 13774 S.ImplicitlyRetainedSelfLocs) 13775 if (IsOrNestedInEscapingBlock(P.second)) 13776 S.Diag(P.first, diag::warn_implicitly_retains_self) 13777 << FixItHint::CreateInsertion(P.first, "self->"); 13778 } 13779 13780 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13781 bool IsInstantiation) { 13782 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13783 13784 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13785 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13786 13787 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 13788 CheckCompletedCoroutineBody(FD, Body); 13789 13790 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13791 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13792 // meant to pop the context added in ActOnStartOfFunctionDef(). 13793 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13794 13795 if (FD) { 13796 FD->setBody(Body); 13797 FD->setWillHaveBody(false); 13798 13799 if (getLangOpts().CPlusPlus14) { 13800 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13801 FD->getReturnType()->isUndeducedType()) { 13802 // If the function has a deduced result type but contains no 'return' 13803 // statements, the result type as written must be exactly 'auto', and 13804 // the deduced result type is 'void'. 13805 if (!FD->getReturnType()->getAs<AutoType>()) { 13806 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13807 << FD->getReturnType(); 13808 FD->setInvalidDecl(); 13809 } else { 13810 // Substitute 'void' for the 'auto' in the type. 13811 TypeLoc ResultType = getReturnTypeLoc(FD); 13812 Context.adjustDeducedFunctionResultType( 13813 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13814 } 13815 } 13816 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13817 // In C++11, we don't use 'auto' deduction rules for lambda call 13818 // operators because we don't support return type deduction. 13819 auto *LSI = getCurLambda(); 13820 if (LSI->HasImplicitReturnType) { 13821 deduceClosureReturnType(*LSI); 13822 13823 // C++11 [expr.prim.lambda]p4: 13824 // [...] if there are no return statements in the compound-statement 13825 // [the deduced type is] the type void 13826 QualType RetType = 13827 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13828 13829 // Update the return type to the deduced type. 13830 const FunctionProtoType *Proto = 13831 FD->getType()->getAs<FunctionProtoType>(); 13832 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13833 Proto->getExtProtoInfo())); 13834 } 13835 } 13836 13837 // If the function implicitly returns zero (like 'main') or is naked, 13838 // don't complain about missing return statements. 13839 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13840 WP.disableCheckFallThrough(); 13841 13842 // MSVC permits the use of pure specifier (=0) on function definition, 13843 // defined at class scope, warn about this non-standard construct. 13844 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 13845 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13846 13847 if (!FD->isInvalidDecl()) { 13848 // Don't diagnose unused parameters of defaulted or deleted functions. 13849 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13850 DiagnoseUnusedParameters(FD->parameters()); 13851 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13852 FD->getReturnType(), FD); 13853 13854 // If this is a structor, we need a vtable. 13855 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13856 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13857 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13858 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13859 13860 // Try to apply the named return value optimization. We have to check 13861 // if we can do this here because lambdas keep return statements around 13862 // to deduce an implicit return type. 13863 if (FD->getReturnType()->isRecordType() && 13864 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13865 computeNRVO(Body, getCurFunction()); 13866 } 13867 13868 // GNU warning -Wmissing-prototypes: 13869 // Warn if a global function is defined without a previous 13870 // prototype declaration. This warning is issued even if the 13871 // definition itself provides a prototype. The aim is to detect 13872 // global functions that fail to be declared in header files. 13873 const FunctionDecl *PossiblePrototype = nullptr; 13874 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 13875 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13876 13877 if (PossiblePrototype) { 13878 // We found a declaration that is not a prototype, 13879 // but that could be a zero-parameter prototype 13880 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 13881 TypeLoc TL = TI->getTypeLoc(); 13882 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13883 Diag(PossiblePrototype->getLocation(), 13884 diag::note_declaration_not_a_prototype) 13885 << (FD->getNumParams() != 0) 13886 << (FD->getNumParams() == 0 13887 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 13888 : FixItHint{}); 13889 } 13890 } else { 13891 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13892 << /* function */ 1 13893 << (FD->getStorageClass() == SC_None 13894 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 13895 "static ") 13896 : FixItHint{}); 13897 } 13898 13899 // GNU warning -Wstrict-prototypes 13900 // Warn if K&R function is defined without a previous declaration. 13901 // This warning is issued only if the definition itself does not provide 13902 // a prototype. Only K&R definitions do not provide a prototype. 13903 // An empty list in a function declarator that is part of a definition 13904 // of that function specifies that the function has no parameters 13905 // (C99 6.7.5.3p14) 13906 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13907 !LangOpts.CPlusPlus) { 13908 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13909 TypeLoc TL = TI->getTypeLoc(); 13910 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13911 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13912 } 13913 } 13914 13915 // Warn on CPUDispatch with an actual body. 13916 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13917 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13918 if (!CmpndBody->body_empty()) 13919 Diag(CmpndBody->body_front()->getBeginLoc(), 13920 diag::warn_dispatch_body_ignored); 13921 13922 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13923 const CXXMethodDecl *KeyFunction; 13924 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13925 MD->isVirtual() && 13926 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13927 MD == KeyFunction->getCanonicalDecl()) { 13928 // Update the key-function state if necessary for this ABI. 13929 if (FD->isInlined() && 13930 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13931 Context.setNonKeyFunction(MD); 13932 13933 // If the newly-chosen key function is already defined, then we 13934 // need to mark the vtable as used retroactively. 13935 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13936 const FunctionDecl *Definition; 13937 if (KeyFunction && KeyFunction->isDefined(Definition)) 13938 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13939 } else { 13940 // We just defined they key function; mark the vtable as used. 13941 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13942 } 13943 } 13944 } 13945 13946 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13947 "Function parsing confused"); 13948 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13949 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13950 MD->setBody(Body); 13951 if (!MD->isInvalidDecl()) { 13952 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13953 MD->getReturnType(), MD); 13954 13955 if (Body) 13956 computeNRVO(Body, getCurFunction()); 13957 } 13958 if (getCurFunction()->ObjCShouldCallSuper) { 13959 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13960 << MD->getSelector().getAsString(); 13961 getCurFunction()->ObjCShouldCallSuper = false; 13962 } 13963 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13964 const ObjCMethodDecl *InitMethod = nullptr; 13965 bool isDesignated = 13966 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13967 assert(isDesignated && InitMethod); 13968 (void)isDesignated; 13969 13970 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13971 auto IFace = MD->getClassInterface(); 13972 if (!IFace) 13973 return false; 13974 auto SuperD = IFace->getSuperClass(); 13975 if (!SuperD) 13976 return false; 13977 return SuperD->getIdentifier() == 13978 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13979 }; 13980 // Don't issue this warning for unavailable inits or direct subclasses 13981 // of NSObject. 13982 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13983 Diag(MD->getLocation(), 13984 diag::warn_objc_designated_init_missing_super_call); 13985 Diag(InitMethod->getLocation(), 13986 diag::note_objc_designated_init_marked_here); 13987 } 13988 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13989 } 13990 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13991 // Don't issue this warning for unavaialable inits. 13992 if (!MD->isUnavailable()) 13993 Diag(MD->getLocation(), 13994 diag::warn_objc_secondary_init_missing_init_call); 13995 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13996 } 13997 13998 diagnoseImplicitlyRetainedSelf(*this); 13999 } else { 14000 // Parsing the function declaration failed in some way. Pop the fake scope 14001 // we pushed on. 14002 PopFunctionScopeInfo(ActivePolicy, dcl); 14003 return nullptr; 14004 } 14005 14006 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14007 DiagnoseUnguardedAvailabilityViolations(dcl); 14008 14009 assert(!getCurFunction()->ObjCShouldCallSuper && 14010 "This should only be set for ObjC methods, which should have been " 14011 "handled in the block above."); 14012 14013 // Verify and clean out per-function state. 14014 if (Body && (!FD || !FD->isDefaulted())) { 14015 // C++ constructors that have function-try-blocks can't have return 14016 // statements in the handlers of that block. (C++ [except.handle]p14) 14017 // Verify this. 14018 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14019 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14020 14021 // Verify that gotos and switch cases don't jump into scopes illegally. 14022 if (getCurFunction()->NeedsScopeChecking() && 14023 !PP.isCodeCompletionEnabled()) 14024 DiagnoseInvalidJumps(Body); 14025 14026 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14027 if (!Destructor->getParent()->isDependentType()) 14028 CheckDestructor(Destructor); 14029 14030 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14031 Destructor->getParent()); 14032 } 14033 14034 // If any errors have occurred, clear out any temporaries that may have 14035 // been leftover. This ensures that these temporaries won't be picked up for 14036 // deletion in some later function. 14037 if (getDiagnostics().hasErrorOccurred() || 14038 getDiagnostics().getSuppressAllDiagnostics()) { 14039 DiscardCleanupsInEvaluationContext(); 14040 } 14041 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14042 !isa<FunctionTemplateDecl>(dcl)) { 14043 // Since the body is valid, issue any analysis-based warnings that are 14044 // enabled. 14045 ActivePolicy = &WP; 14046 } 14047 14048 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14049 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14050 FD->setInvalidDecl(); 14051 14052 if (FD && FD->hasAttr<NakedAttr>()) { 14053 for (const Stmt *S : Body->children()) { 14054 // Allow local register variables without initializer as they don't 14055 // require prologue. 14056 bool RegisterVariables = false; 14057 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14058 for (const auto *Decl : DS->decls()) { 14059 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14060 RegisterVariables = 14061 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14062 if (!RegisterVariables) 14063 break; 14064 } 14065 } 14066 } 14067 if (RegisterVariables) 14068 continue; 14069 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14070 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14071 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14072 FD->setInvalidDecl(); 14073 break; 14074 } 14075 } 14076 } 14077 14078 assert(ExprCleanupObjects.size() == 14079 ExprEvalContexts.back().NumCleanupObjects && 14080 "Leftover temporaries in function"); 14081 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14082 assert(MaybeODRUseExprs.empty() && 14083 "Leftover expressions for odr-use checking"); 14084 } 14085 14086 if (!IsInstantiation) 14087 PopDeclContext(); 14088 14089 PopFunctionScopeInfo(ActivePolicy, dcl); 14090 // If any errors have occurred, clear out any temporaries that may have 14091 // been leftover. This ensures that these temporaries won't be picked up for 14092 // deletion in some later function. 14093 if (getDiagnostics().hasErrorOccurred()) { 14094 DiscardCleanupsInEvaluationContext(); 14095 } 14096 14097 return dcl; 14098 } 14099 14100 /// When we finish delayed parsing of an attribute, we must attach it to the 14101 /// relevant Decl. 14102 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14103 ParsedAttributes &Attrs) { 14104 // Always attach attributes to the underlying decl. 14105 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14106 D = TD->getTemplatedDecl(); 14107 ProcessDeclAttributeList(S, D, Attrs); 14108 14109 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14110 if (Method->isStatic()) 14111 checkThisInStaticMemberFunctionAttributes(Method); 14112 } 14113 14114 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14115 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14116 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14117 IdentifierInfo &II, Scope *S) { 14118 // Find the scope in which the identifier is injected and the corresponding 14119 // DeclContext. 14120 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14121 // In that case, we inject the declaration into the translation unit scope 14122 // instead. 14123 Scope *BlockScope = S; 14124 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14125 BlockScope = BlockScope->getParent(); 14126 14127 Scope *ContextScope = BlockScope; 14128 while (!ContextScope->getEntity()) 14129 ContextScope = ContextScope->getParent(); 14130 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14131 14132 // Before we produce a declaration for an implicitly defined 14133 // function, see whether there was a locally-scoped declaration of 14134 // this name as a function or variable. If so, use that 14135 // (non-visible) declaration, and complain about it. 14136 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14137 if (ExternCPrev) { 14138 // We still need to inject the function into the enclosing block scope so 14139 // that later (non-call) uses can see it. 14140 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14141 14142 // C89 footnote 38: 14143 // If in fact it is not defined as having type "function returning int", 14144 // the behavior is undefined. 14145 if (!isa<FunctionDecl>(ExternCPrev) || 14146 !Context.typesAreCompatible( 14147 cast<FunctionDecl>(ExternCPrev)->getType(), 14148 Context.getFunctionNoProtoType(Context.IntTy))) { 14149 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14150 << ExternCPrev << !getLangOpts().C99; 14151 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14152 return ExternCPrev; 14153 } 14154 } 14155 14156 // Extension in C99. Legal in C90, but warn about it. 14157 unsigned diag_id; 14158 if (II.getName().startswith("__builtin_")) 14159 diag_id = diag::warn_builtin_unknown; 14160 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14161 else if (getLangOpts().OpenCL) 14162 diag_id = diag::err_opencl_implicit_function_decl; 14163 else if (getLangOpts().C99) 14164 diag_id = diag::ext_implicit_function_decl; 14165 else 14166 diag_id = diag::warn_implicit_function_decl; 14167 Diag(Loc, diag_id) << &II; 14168 14169 // If we found a prior declaration of this function, don't bother building 14170 // another one. We've already pushed that one into scope, so there's nothing 14171 // more to do. 14172 if (ExternCPrev) 14173 return ExternCPrev; 14174 14175 // Because typo correction is expensive, only do it if the implicit 14176 // function declaration is going to be treated as an error. 14177 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14178 TypoCorrection Corrected; 14179 DeclFilterCCC<FunctionDecl> CCC{}; 14180 if (S && (Corrected = 14181 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14182 S, nullptr, CCC, CTK_NonError))) 14183 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14184 /*ErrorRecovery*/false); 14185 } 14186 14187 // Set a Declarator for the implicit definition: int foo(); 14188 const char *Dummy; 14189 AttributeFactory attrFactory; 14190 DeclSpec DS(attrFactory); 14191 unsigned DiagID; 14192 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14193 Context.getPrintingPolicy()); 14194 (void)Error; // Silence warning. 14195 assert(!Error && "Error setting up implicit decl!"); 14196 SourceLocation NoLoc; 14197 Declarator D(DS, DeclaratorContext::BlockContext); 14198 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14199 /*IsAmbiguous=*/false, 14200 /*LParenLoc=*/NoLoc, 14201 /*Params=*/nullptr, 14202 /*NumParams=*/0, 14203 /*EllipsisLoc=*/NoLoc, 14204 /*RParenLoc=*/NoLoc, 14205 /*RefQualifierIsLvalueRef=*/true, 14206 /*RefQualifierLoc=*/NoLoc, 14207 /*MutableLoc=*/NoLoc, EST_None, 14208 /*ESpecRange=*/SourceRange(), 14209 /*Exceptions=*/nullptr, 14210 /*ExceptionRanges=*/nullptr, 14211 /*NumExceptions=*/0, 14212 /*NoexceptExpr=*/nullptr, 14213 /*ExceptionSpecTokens=*/nullptr, 14214 /*DeclsInPrototype=*/None, Loc, 14215 Loc, D), 14216 std::move(DS.getAttributes()), SourceLocation()); 14217 D.SetIdentifier(&II, Loc); 14218 14219 // Insert this function into the enclosing block scope. 14220 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14221 FD->setImplicit(); 14222 14223 AddKnownFunctionAttributes(FD); 14224 14225 return FD; 14226 } 14227 14228 /// Adds any function attributes that we know a priori based on 14229 /// the declaration of this function. 14230 /// 14231 /// These attributes can apply both to implicitly-declared builtins 14232 /// (like __builtin___printf_chk) or to library-declared functions 14233 /// like NSLog or printf. 14234 /// 14235 /// We need to check for duplicate attributes both here and where user-written 14236 /// attributes are applied to declarations. 14237 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14238 if (FD->isInvalidDecl()) 14239 return; 14240 14241 // If this is a built-in function, map its builtin attributes to 14242 // actual attributes. 14243 if (unsigned BuiltinID = FD->getBuiltinID()) { 14244 // Handle printf-formatting attributes. 14245 unsigned FormatIdx; 14246 bool HasVAListArg; 14247 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14248 if (!FD->hasAttr<FormatAttr>()) { 14249 const char *fmt = "printf"; 14250 unsigned int NumParams = FD->getNumParams(); 14251 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14252 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14253 fmt = "NSString"; 14254 FD->addAttr(FormatAttr::CreateImplicit(Context, 14255 &Context.Idents.get(fmt), 14256 FormatIdx+1, 14257 HasVAListArg ? 0 : FormatIdx+2, 14258 FD->getLocation())); 14259 } 14260 } 14261 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14262 HasVAListArg)) { 14263 if (!FD->hasAttr<FormatAttr>()) 14264 FD->addAttr(FormatAttr::CreateImplicit(Context, 14265 &Context.Idents.get("scanf"), 14266 FormatIdx+1, 14267 HasVAListArg ? 0 : FormatIdx+2, 14268 FD->getLocation())); 14269 } 14270 14271 // Handle automatically recognized callbacks. 14272 SmallVector<int, 4> Encoding; 14273 if (!FD->hasAttr<CallbackAttr>() && 14274 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14275 FD->addAttr(CallbackAttr::CreateImplicit( 14276 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14277 14278 // Mark const if we don't care about errno and that is the only thing 14279 // preventing the function from being const. This allows IRgen to use LLVM 14280 // intrinsics for such functions. 14281 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14282 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14283 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14284 14285 // We make "fma" on some platforms const because we know it does not set 14286 // errno in those environments even though it could set errno based on the 14287 // C standard. 14288 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14289 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14290 !FD->hasAttr<ConstAttr>()) { 14291 switch (BuiltinID) { 14292 case Builtin::BI__builtin_fma: 14293 case Builtin::BI__builtin_fmaf: 14294 case Builtin::BI__builtin_fmal: 14295 case Builtin::BIfma: 14296 case Builtin::BIfmaf: 14297 case Builtin::BIfmal: 14298 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14299 break; 14300 default: 14301 break; 14302 } 14303 } 14304 14305 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14306 !FD->hasAttr<ReturnsTwiceAttr>()) 14307 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14308 FD->getLocation())); 14309 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14310 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14311 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14312 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14313 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14314 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14315 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14316 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14317 // Add the appropriate attribute, depending on the CUDA compilation mode 14318 // and which target the builtin belongs to. For example, during host 14319 // compilation, aux builtins are __device__, while the rest are __host__. 14320 if (getLangOpts().CUDAIsDevice != 14321 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14322 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14323 else 14324 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14325 } 14326 } 14327 14328 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14329 // throw, add an implicit nothrow attribute to any extern "C" function we come 14330 // across. 14331 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14332 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14333 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14334 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14335 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14336 } 14337 14338 IdentifierInfo *Name = FD->getIdentifier(); 14339 if (!Name) 14340 return; 14341 if ((!getLangOpts().CPlusPlus && 14342 FD->getDeclContext()->isTranslationUnit()) || 14343 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14344 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14345 LinkageSpecDecl::lang_c)) { 14346 // Okay: this could be a libc/libm/Objective-C function we know 14347 // about. 14348 } else 14349 return; 14350 14351 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14352 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14353 // target-specific builtins, perhaps? 14354 if (!FD->hasAttr<FormatAttr>()) 14355 FD->addAttr(FormatAttr::CreateImplicit(Context, 14356 &Context.Idents.get("printf"), 2, 14357 Name->isStr("vasprintf") ? 0 : 3, 14358 FD->getLocation())); 14359 } 14360 14361 if (Name->isStr("__CFStringMakeConstantString")) { 14362 // We already have a __builtin___CFStringMakeConstantString, 14363 // but builds that use -fno-constant-cfstrings don't go through that. 14364 if (!FD->hasAttr<FormatArgAttr>()) 14365 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14366 FD->getLocation())); 14367 } 14368 } 14369 14370 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14371 TypeSourceInfo *TInfo) { 14372 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14373 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14374 14375 if (!TInfo) { 14376 assert(D.isInvalidType() && "no declarator info for valid type"); 14377 TInfo = Context.getTrivialTypeSourceInfo(T); 14378 } 14379 14380 // Scope manipulation handled by caller. 14381 TypedefDecl *NewTD = 14382 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14383 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14384 14385 // Bail out immediately if we have an invalid declaration. 14386 if (D.isInvalidType()) { 14387 NewTD->setInvalidDecl(); 14388 return NewTD; 14389 } 14390 14391 if (D.getDeclSpec().isModulePrivateSpecified()) { 14392 if (CurContext->isFunctionOrMethod()) 14393 Diag(NewTD->getLocation(), diag::err_module_private_local) 14394 << 2 << NewTD->getDeclName() 14395 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14396 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14397 else 14398 NewTD->setModulePrivate(); 14399 } 14400 14401 // C++ [dcl.typedef]p8: 14402 // If the typedef declaration defines an unnamed class (or 14403 // enum), the first typedef-name declared by the declaration 14404 // to be that class type (or enum type) is used to denote the 14405 // class type (or enum type) for linkage purposes only. 14406 // We need to check whether the type was declared in the declaration. 14407 switch (D.getDeclSpec().getTypeSpecType()) { 14408 case TST_enum: 14409 case TST_struct: 14410 case TST_interface: 14411 case TST_union: 14412 case TST_class: { 14413 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14414 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14415 break; 14416 } 14417 14418 default: 14419 break; 14420 } 14421 14422 return NewTD; 14423 } 14424 14425 /// Check that this is a valid underlying type for an enum declaration. 14426 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14427 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14428 QualType T = TI->getType(); 14429 14430 if (T->isDependentType()) 14431 return false; 14432 14433 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14434 if (BT->isInteger()) 14435 return false; 14436 14437 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14438 return true; 14439 } 14440 14441 /// Check whether this is a valid redeclaration of a previous enumeration. 14442 /// \return true if the redeclaration was invalid. 14443 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14444 QualType EnumUnderlyingTy, bool IsFixed, 14445 const EnumDecl *Prev) { 14446 if (IsScoped != Prev->isScoped()) { 14447 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14448 << Prev->isScoped(); 14449 Diag(Prev->getLocation(), diag::note_previous_declaration); 14450 return true; 14451 } 14452 14453 if (IsFixed && Prev->isFixed()) { 14454 if (!EnumUnderlyingTy->isDependentType() && 14455 !Prev->getIntegerType()->isDependentType() && 14456 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14457 Prev->getIntegerType())) { 14458 // TODO: Highlight the underlying type of the redeclaration. 14459 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14460 << EnumUnderlyingTy << Prev->getIntegerType(); 14461 Diag(Prev->getLocation(), diag::note_previous_declaration) 14462 << Prev->getIntegerTypeRange(); 14463 return true; 14464 } 14465 } else if (IsFixed != Prev->isFixed()) { 14466 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14467 << Prev->isFixed(); 14468 Diag(Prev->getLocation(), diag::note_previous_declaration); 14469 return true; 14470 } 14471 14472 return false; 14473 } 14474 14475 /// Get diagnostic %select index for tag kind for 14476 /// redeclaration diagnostic message. 14477 /// WARNING: Indexes apply to particular diagnostics only! 14478 /// 14479 /// \returns diagnostic %select index. 14480 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14481 switch (Tag) { 14482 case TTK_Struct: return 0; 14483 case TTK_Interface: return 1; 14484 case TTK_Class: return 2; 14485 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14486 } 14487 } 14488 14489 /// Determine if tag kind is a class-key compatible with 14490 /// class for redeclaration (class, struct, or __interface). 14491 /// 14492 /// \returns true iff the tag kind is compatible. 14493 static bool isClassCompatTagKind(TagTypeKind Tag) 14494 { 14495 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14496 } 14497 14498 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14499 TagTypeKind TTK) { 14500 if (isa<TypedefDecl>(PrevDecl)) 14501 return NTK_Typedef; 14502 else if (isa<TypeAliasDecl>(PrevDecl)) 14503 return NTK_TypeAlias; 14504 else if (isa<ClassTemplateDecl>(PrevDecl)) 14505 return NTK_Template; 14506 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14507 return NTK_TypeAliasTemplate; 14508 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14509 return NTK_TemplateTemplateArgument; 14510 switch (TTK) { 14511 case TTK_Struct: 14512 case TTK_Interface: 14513 case TTK_Class: 14514 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14515 case TTK_Union: 14516 return NTK_NonUnion; 14517 case TTK_Enum: 14518 return NTK_NonEnum; 14519 } 14520 llvm_unreachable("invalid TTK"); 14521 } 14522 14523 /// Determine whether a tag with a given kind is acceptable 14524 /// as a redeclaration of the given tag declaration. 14525 /// 14526 /// \returns true if the new tag kind is acceptable, false otherwise. 14527 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14528 TagTypeKind NewTag, bool isDefinition, 14529 SourceLocation NewTagLoc, 14530 const IdentifierInfo *Name) { 14531 // C++ [dcl.type.elab]p3: 14532 // The class-key or enum keyword present in the 14533 // elaborated-type-specifier shall agree in kind with the 14534 // declaration to which the name in the elaborated-type-specifier 14535 // refers. This rule also applies to the form of 14536 // elaborated-type-specifier that declares a class-name or 14537 // friend class since it can be construed as referring to the 14538 // definition of the class. Thus, in any 14539 // elaborated-type-specifier, the enum keyword shall be used to 14540 // refer to an enumeration (7.2), the union class-key shall be 14541 // used to refer to a union (clause 9), and either the class or 14542 // struct class-key shall be used to refer to a class (clause 9) 14543 // declared using the class or struct class-key. 14544 TagTypeKind OldTag = Previous->getTagKind(); 14545 if (OldTag != NewTag && 14546 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14547 return false; 14548 14549 // Tags are compatible, but we might still want to warn on mismatched tags. 14550 // Non-class tags can't be mismatched at this point. 14551 if (!isClassCompatTagKind(NewTag)) 14552 return true; 14553 14554 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14555 // by our warning analysis. We don't want to warn about mismatches with (eg) 14556 // declarations in system headers that are designed to be specialized, but if 14557 // a user asks us to warn, we should warn if their code contains mismatched 14558 // declarations. 14559 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14560 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14561 Loc); 14562 }; 14563 if (IsIgnoredLoc(NewTagLoc)) 14564 return true; 14565 14566 auto IsIgnored = [&](const TagDecl *Tag) { 14567 return IsIgnoredLoc(Tag->getLocation()); 14568 }; 14569 while (IsIgnored(Previous)) { 14570 Previous = Previous->getPreviousDecl(); 14571 if (!Previous) 14572 return true; 14573 OldTag = Previous->getTagKind(); 14574 } 14575 14576 bool isTemplate = false; 14577 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14578 isTemplate = Record->getDescribedClassTemplate(); 14579 14580 if (inTemplateInstantiation()) { 14581 if (OldTag != NewTag) { 14582 // In a template instantiation, do not offer fix-its for tag mismatches 14583 // since they usually mess up the template instead of fixing the problem. 14584 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14585 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14586 << getRedeclDiagFromTagKind(OldTag); 14587 // FIXME: Note previous location? 14588 } 14589 return true; 14590 } 14591 14592 if (isDefinition) { 14593 // On definitions, check all previous tags and issue a fix-it for each 14594 // one that doesn't match the current tag. 14595 if (Previous->getDefinition()) { 14596 // Don't suggest fix-its for redefinitions. 14597 return true; 14598 } 14599 14600 bool previousMismatch = false; 14601 for (const TagDecl *I : Previous->redecls()) { 14602 if (I->getTagKind() != NewTag) { 14603 // Ignore previous declarations for which the warning was disabled. 14604 if (IsIgnored(I)) 14605 continue; 14606 14607 if (!previousMismatch) { 14608 previousMismatch = true; 14609 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14610 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14611 << getRedeclDiagFromTagKind(I->getTagKind()); 14612 } 14613 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14614 << getRedeclDiagFromTagKind(NewTag) 14615 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14616 TypeWithKeyword::getTagTypeKindName(NewTag)); 14617 } 14618 } 14619 return true; 14620 } 14621 14622 // Identify the prevailing tag kind: this is the kind of the definition (if 14623 // there is a non-ignored definition), or otherwise the kind of the prior 14624 // (non-ignored) declaration. 14625 const TagDecl *PrevDef = Previous->getDefinition(); 14626 if (PrevDef && IsIgnored(PrevDef)) 14627 PrevDef = nullptr; 14628 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14629 if (Redecl->getTagKind() != NewTag) { 14630 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14631 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14632 << getRedeclDiagFromTagKind(OldTag); 14633 Diag(Redecl->getLocation(), diag::note_previous_use); 14634 14635 // If there is a previous definition, suggest a fix-it. 14636 if (PrevDef) { 14637 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14638 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14639 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14640 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14641 } 14642 } 14643 14644 return true; 14645 } 14646 14647 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14648 /// from an outer enclosing namespace or file scope inside a friend declaration. 14649 /// This should provide the commented out code in the following snippet: 14650 /// namespace N { 14651 /// struct X; 14652 /// namespace M { 14653 /// struct Y { friend struct /*N::*/ X; }; 14654 /// } 14655 /// } 14656 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14657 SourceLocation NameLoc) { 14658 // While the decl is in a namespace, do repeated lookup of that name and see 14659 // if we get the same namespace back. If we do not, continue until 14660 // translation unit scope, at which point we have a fully qualified NNS. 14661 SmallVector<IdentifierInfo *, 4> Namespaces; 14662 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14663 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14664 // This tag should be declared in a namespace, which can only be enclosed by 14665 // other namespaces. Bail if there's an anonymous namespace in the chain. 14666 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14667 if (!Namespace || Namespace->isAnonymousNamespace()) 14668 return FixItHint(); 14669 IdentifierInfo *II = Namespace->getIdentifier(); 14670 Namespaces.push_back(II); 14671 NamedDecl *Lookup = SemaRef.LookupSingleName( 14672 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14673 if (Lookup == Namespace) 14674 break; 14675 } 14676 14677 // Once we have all the namespaces, reverse them to go outermost first, and 14678 // build an NNS. 14679 SmallString<64> Insertion; 14680 llvm::raw_svector_ostream OS(Insertion); 14681 if (DC->isTranslationUnit()) 14682 OS << "::"; 14683 std::reverse(Namespaces.begin(), Namespaces.end()); 14684 for (auto *II : Namespaces) 14685 OS << II->getName() << "::"; 14686 return FixItHint::CreateInsertion(NameLoc, Insertion); 14687 } 14688 14689 /// Determine whether a tag originally declared in context \p OldDC can 14690 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14691 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14692 /// using-declaration). 14693 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14694 DeclContext *NewDC) { 14695 OldDC = OldDC->getRedeclContext(); 14696 NewDC = NewDC->getRedeclContext(); 14697 14698 if (OldDC->Equals(NewDC)) 14699 return true; 14700 14701 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14702 // encloses the other). 14703 if (S.getLangOpts().MSVCCompat && 14704 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14705 return true; 14706 14707 return false; 14708 } 14709 14710 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14711 /// former case, Name will be non-null. In the later case, Name will be null. 14712 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14713 /// reference/declaration/definition of a tag. 14714 /// 14715 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14716 /// trailing-type-specifier) other than one in an alias-declaration. 14717 /// 14718 /// \param SkipBody If non-null, will be set to indicate if the caller should 14719 /// skip the definition of this tag and treat it as if it were a declaration. 14720 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14721 SourceLocation KWLoc, CXXScopeSpec &SS, 14722 IdentifierInfo *Name, SourceLocation NameLoc, 14723 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14724 SourceLocation ModulePrivateLoc, 14725 MultiTemplateParamsArg TemplateParameterLists, 14726 bool &OwnedDecl, bool &IsDependent, 14727 SourceLocation ScopedEnumKWLoc, 14728 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14729 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14730 SkipBodyInfo *SkipBody) { 14731 // If this is not a definition, it must have a name. 14732 IdentifierInfo *OrigName = Name; 14733 assert((Name != nullptr || TUK == TUK_Definition) && 14734 "Nameless record must be a definition!"); 14735 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14736 14737 OwnedDecl = false; 14738 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14739 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14740 14741 // FIXME: Check member specializations more carefully. 14742 bool isMemberSpecialization = false; 14743 bool Invalid = false; 14744 14745 // We only need to do this matching if we have template parameters 14746 // or a scope specifier, which also conveniently avoids this work 14747 // for non-C++ cases. 14748 if (TemplateParameterLists.size() > 0 || 14749 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14750 if (TemplateParameterList *TemplateParams = 14751 MatchTemplateParametersToScopeSpecifier( 14752 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14753 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14754 if (Kind == TTK_Enum) { 14755 Diag(KWLoc, diag::err_enum_template); 14756 return nullptr; 14757 } 14758 14759 if (TemplateParams->size() > 0) { 14760 // This is a declaration or definition of a class template (which may 14761 // be a member of another template). 14762 14763 if (Invalid) 14764 return nullptr; 14765 14766 OwnedDecl = false; 14767 DeclResult Result = CheckClassTemplate( 14768 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14769 AS, ModulePrivateLoc, 14770 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14771 TemplateParameterLists.data(), SkipBody); 14772 return Result.get(); 14773 } else { 14774 // The "template<>" header is extraneous. 14775 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14776 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14777 isMemberSpecialization = true; 14778 } 14779 } 14780 } 14781 14782 // Figure out the underlying type if this a enum declaration. We need to do 14783 // this early, because it's needed to detect if this is an incompatible 14784 // redeclaration. 14785 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14786 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14787 14788 if (Kind == TTK_Enum) { 14789 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14790 // No underlying type explicitly specified, or we failed to parse the 14791 // type, default to int. 14792 EnumUnderlying = Context.IntTy.getTypePtr(); 14793 } else if (UnderlyingType.get()) { 14794 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14795 // integral type; any cv-qualification is ignored. 14796 TypeSourceInfo *TI = nullptr; 14797 GetTypeFromParser(UnderlyingType.get(), &TI); 14798 EnumUnderlying = TI; 14799 14800 if (CheckEnumUnderlyingType(TI)) 14801 // Recover by falling back to int. 14802 EnumUnderlying = Context.IntTy.getTypePtr(); 14803 14804 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14805 UPPC_FixedUnderlyingType)) 14806 EnumUnderlying = Context.IntTy.getTypePtr(); 14807 14808 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 14809 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14810 // of 'int'. However, if this is an unfixed forward declaration, don't set 14811 // the underlying type unless the user enables -fms-compatibility. This 14812 // makes unfixed forward declared enums incomplete and is more conforming. 14813 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14814 EnumUnderlying = Context.IntTy.getTypePtr(); 14815 } 14816 } 14817 14818 DeclContext *SearchDC = CurContext; 14819 DeclContext *DC = CurContext; 14820 bool isStdBadAlloc = false; 14821 bool isStdAlignValT = false; 14822 14823 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14824 if (TUK == TUK_Friend || TUK == TUK_Reference) 14825 Redecl = NotForRedeclaration; 14826 14827 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14828 /// implemented asks for structural equivalence checking, the returned decl 14829 /// here is passed back to the parser, allowing the tag body to be parsed. 14830 auto createTagFromNewDecl = [&]() -> TagDecl * { 14831 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14832 // If there is an identifier, use the location of the identifier as the 14833 // location of the decl, otherwise use the location of the struct/union 14834 // keyword. 14835 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14836 TagDecl *New = nullptr; 14837 14838 if (Kind == TTK_Enum) { 14839 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14840 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14841 // If this is an undefined enum, bail. 14842 if (TUK != TUK_Definition && !Invalid) 14843 return nullptr; 14844 if (EnumUnderlying) { 14845 EnumDecl *ED = cast<EnumDecl>(New); 14846 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14847 ED->setIntegerTypeSourceInfo(TI); 14848 else 14849 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14850 ED->setPromotionType(ED->getIntegerType()); 14851 } 14852 } else { // struct/union 14853 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14854 nullptr); 14855 } 14856 14857 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14858 // Add alignment attributes if necessary; these attributes are checked 14859 // when the ASTContext lays out the structure. 14860 // 14861 // It is important for implementing the correct semantics that this 14862 // happen here (in ActOnTag). The #pragma pack stack is 14863 // maintained as a result of parser callbacks which can occur at 14864 // many points during the parsing of a struct declaration (because 14865 // the #pragma tokens are effectively skipped over during the 14866 // parsing of the struct). 14867 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14868 AddAlignmentAttributesForRecord(RD); 14869 AddMsStructLayoutForRecord(RD); 14870 } 14871 } 14872 New->setLexicalDeclContext(CurContext); 14873 return New; 14874 }; 14875 14876 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14877 if (Name && SS.isNotEmpty()) { 14878 // We have a nested-name tag ('struct foo::bar'). 14879 14880 // Check for invalid 'foo::'. 14881 if (SS.isInvalid()) { 14882 Name = nullptr; 14883 goto CreateNewDecl; 14884 } 14885 14886 // If this is a friend or a reference to a class in a dependent 14887 // context, don't try to make a decl for it. 14888 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14889 DC = computeDeclContext(SS, false); 14890 if (!DC) { 14891 IsDependent = true; 14892 return nullptr; 14893 } 14894 } else { 14895 DC = computeDeclContext(SS, true); 14896 if (!DC) { 14897 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14898 << SS.getRange(); 14899 return nullptr; 14900 } 14901 } 14902 14903 if (RequireCompleteDeclContext(SS, DC)) 14904 return nullptr; 14905 14906 SearchDC = DC; 14907 // Look-up name inside 'foo::'. 14908 LookupQualifiedName(Previous, DC); 14909 14910 if (Previous.isAmbiguous()) 14911 return nullptr; 14912 14913 if (Previous.empty()) { 14914 // Name lookup did not find anything. However, if the 14915 // nested-name-specifier refers to the current instantiation, 14916 // and that current instantiation has any dependent base 14917 // classes, we might find something at instantiation time: treat 14918 // this as a dependent elaborated-type-specifier. 14919 // But this only makes any sense for reference-like lookups. 14920 if (Previous.wasNotFoundInCurrentInstantiation() && 14921 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14922 IsDependent = true; 14923 return nullptr; 14924 } 14925 14926 // A tag 'foo::bar' must already exist. 14927 Diag(NameLoc, diag::err_not_tag_in_scope) 14928 << Kind << Name << DC << SS.getRange(); 14929 Name = nullptr; 14930 Invalid = true; 14931 goto CreateNewDecl; 14932 } 14933 } else if (Name) { 14934 // C++14 [class.mem]p14: 14935 // If T is the name of a class, then each of the following shall have a 14936 // name different from T: 14937 // -- every member of class T that is itself a type 14938 if (TUK != TUK_Reference && TUK != TUK_Friend && 14939 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14940 return nullptr; 14941 14942 // If this is a named struct, check to see if there was a previous forward 14943 // declaration or definition. 14944 // FIXME: We're looking into outer scopes here, even when we 14945 // shouldn't be. Doing so can result in ambiguities that we 14946 // shouldn't be diagnosing. 14947 LookupName(Previous, S); 14948 14949 // When declaring or defining a tag, ignore ambiguities introduced 14950 // by types using'ed into this scope. 14951 if (Previous.isAmbiguous() && 14952 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14953 LookupResult::Filter F = Previous.makeFilter(); 14954 while (F.hasNext()) { 14955 NamedDecl *ND = F.next(); 14956 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14957 SearchDC->getRedeclContext())) 14958 F.erase(); 14959 } 14960 F.done(); 14961 } 14962 14963 // C++11 [namespace.memdef]p3: 14964 // If the name in a friend declaration is neither qualified nor 14965 // a template-id and the declaration is a function or an 14966 // elaborated-type-specifier, the lookup to determine whether 14967 // the entity has been previously declared shall not consider 14968 // any scopes outside the innermost enclosing namespace. 14969 // 14970 // MSVC doesn't implement the above rule for types, so a friend tag 14971 // declaration may be a redeclaration of a type declared in an enclosing 14972 // scope. They do implement this rule for friend functions. 14973 // 14974 // Does it matter that this should be by scope instead of by 14975 // semantic context? 14976 if (!Previous.empty() && TUK == TUK_Friend) { 14977 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14978 LookupResult::Filter F = Previous.makeFilter(); 14979 bool FriendSawTagOutsideEnclosingNamespace = false; 14980 while (F.hasNext()) { 14981 NamedDecl *ND = F.next(); 14982 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14983 if (DC->isFileContext() && 14984 !EnclosingNS->Encloses(ND->getDeclContext())) { 14985 if (getLangOpts().MSVCCompat) 14986 FriendSawTagOutsideEnclosingNamespace = true; 14987 else 14988 F.erase(); 14989 } 14990 } 14991 F.done(); 14992 14993 // Diagnose this MSVC extension in the easy case where lookup would have 14994 // unambiguously found something outside the enclosing namespace. 14995 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14996 NamedDecl *ND = Previous.getFoundDecl(); 14997 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14998 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14999 } 15000 } 15001 15002 // Note: there used to be some attempt at recovery here. 15003 if (Previous.isAmbiguous()) 15004 return nullptr; 15005 15006 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15007 // FIXME: This makes sure that we ignore the contexts associated 15008 // with C structs, unions, and enums when looking for a matching 15009 // tag declaration or definition. See the similar lookup tweak 15010 // in Sema::LookupName; is there a better way to deal with this? 15011 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15012 SearchDC = SearchDC->getParent(); 15013 } 15014 } 15015 15016 if (Previous.isSingleResult() && 15017 Previous.getFoundDecl()->isTemplateParameter()) { 15018 // Maybe we will complain about the shadowed template parameter. 15019 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15020 // Just pretend that we didn't see the previous declaration. 15021 Previous.clear(); 15022 } 15023 15024 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15025 DC->Equals(getStdNamespace())) { 15026 if (Name->isStr("bad_alloc")) { 15027 // This is a declaration of or a reference to "std::bad_alloc". 15028 isStdBadAlloc = true; 15029 15030 // If std::bad_alloc has been implicitly declared (but made invisible to 15031 // name lookup), fill in this implicit declaration as the previous 15032 // declaration, so that the declarations get chained appropriately. 15033 if (Previous.empty() && StdBadAlloc) 15034 Previous.addDecl(getStdBadAlloc()); 15035 } else if (Name->isStr("align_val_t")) { 15036 isStdAlignValT = true; 15037 if (Previous.empty() && StdAlignValT) 15038 Previous.addDecl(getStdAlignValT()); 15039 } 15040 } 15041 15042 // If we didn't find a previous declaration, and this is a reference 15043 // (or friend reference), move to the correct scope. In C++, we 15044 // also need to do a redeclaration lookup there, just in case 15045 // there's a shadow friend decl. 15046 if (Name && Previous.empty() && 15047 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15048 if (Invalid) goto CreateNewDecl; 15049 assert(SS.isEmpty()); 15050 15051 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15052 // C++ [basic.scope.pdecl]p5: 15053 // -- for an elaborated-type-specifier of the form 15054 // 15055 // class-key identifier 15056 // 15057 // if the elaborated-type-specifier is used in the 15058 // decl-specifier-seq or parameter-declaration-clause of a 15059 // function defined in namespace scope, the identifier is 15060 // declared as a class-name in the namespace that contains 15061 // the declaration; otherwise, except as a friend 15062 // declaration, the identifier is declared in the smallest 15063 // non-class, non-function-prototype scope that contains the 15064 // declaration. 15065 // 15066 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15067 // C structs and unions. 15068 // 15069 // It is an error in C++ to declare (rather than define) an enum 15070 // type, including via an elaborated type specifier. We'll 15071 // diagnose that later; for now, declare the enum in the same 15072 // scope as we would have picked for any other tag type. 15073 // 15074 // GNU C also supports this behavior as part of its incomplete 15075 // enum types extension, while GNU C++ does not. 15076 // 15077 // Find the context where we'll be declaring the tag. 15078 // FIXME: We would like to maintain the current DeclContext as the 15079 // lexical context, 15080 SearchDC = getTagInjectionContext(SearchDC); 15081 15082 // Find the scope where we'll be declaring the tag. 15083 S = getTagInjectionScope(S, getLangOpts()); 15084 } else { 15085 assert(TUK == TUK_Friend); 15086 // C++ [namespace.memdef]p3: 15087 // If a friend declaration in a non-local class first declares a 15088 // class or function, the friend class or function is a member of 15089 // the innermost enclosing namespace. 15090 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15091 } 15092 15093 // In C++, we need to do a redeclaration lookup to properly 15094 // diagnose some problems. 15095 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15096 // hidden declaration so that we don't get ambiguity errors when using a 15097 // type declared by an elaborated-type-specifier. In C that is not correct 15098 // and we should instead merge compatible types found by lookup. 15099 if (getLangOpts().CPlusPlus) { 15100 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15101 LookupQualifiedName(Previous, SearchDC); 15102 } else { 15103 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15104 LookupName(Previous, S); 15105 } 15106 } 15107 15108 // If we have a known previous declaration to use, then use it. 15109 if (Previous.empty() && SkipBody && SkipBody->Previous) 15110 Previous.addDecl(SkipBody->Previous); 15111 15112 if (!Previous.empty()) { 15113 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15114 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15115 15116 // It's okay to have a tag decl in the same scope as a typedef 15117 // which hides a tag decl in the same scope. Finding this 15118 // insanity with a redeclaration lookup can only actually happen 15119 // in C++. 15120 // 15121 // This is also okay for elaborated-type-specifiers, which is 15122 // technically forbidden by the current standard but which is 15123 // okay according to the likely resolution of an open issue; 15124 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15125 if (getLangOpts().CPlusPlus) { 15126 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15127 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15128 TagDecl *Tag = TT->getDecl(); 15129 if (Tag->getDeclName() == Name && 15130 Tag->getDeclContext()->getRedeclContext() 15131 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15132 PrevDecl = Tag; 15133 Previous.clear(); 15134 Previous.addDecl(Tag); 15135 Previous.resolveKind(); 15136 } 15137 } 15138 } 15139 } 15140 15141 // If this is a redeclaration of a using shadow declaration, it must 15142 // declare a tag in the same context. In MSVC mode, we allow a 15143 // redefinition if either context is within the other. 15144 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15145 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15146 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15147 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15148 !(OldTag && isAcceptableTagRedeclContext( 15149 *this, OldTag->getDeclContext(), SearchDC))) { 15150 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15151 Diag(Shadow->getTargetDecl()->getLocation(), 15152 diag::note_using_decl_target); 15153 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15154 << 0; 15155 // Recover by ignoring the old declaration. 15156 Previous.clear(); 15157 goto CreateNewDecl; 15158 } 15159 } 15160 15161 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15162 // If this is a use of a previous tag, or if the tag is already declared 15163 // in the same scope (so that the definition/declaration completes or 15164 // rementions the tag), reuse the decl. 15165 if (TUK == TUK_Reference || TUK == TUK_Friend || 15166 isDeclInScope(DirectPrevDecl, SearchDC, S, 15167 SS.isNotEmpty() || isMemberSpecialization)) { 15168 // Make sure that this wasn't declared as an enum and now used as a 15169 // struct or something similar. 15170 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15171 TUK == TUK_Definition, KWLoc, 15172 Name)) { 15173 bool SafeToContinue 15174 = (PrevTagDecl->getTagKind() != TTK_Enum && 15175 Kind != TTK_Enum); 15176 if (SafeToContinue) 15177 Diag(KWLoc, diag::err_use_with_wrong_tag) 15178 << Name 15179 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15180 PrevTagDecl->getKindName()); 15181 else 15182 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15183 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15184 15185 if (SafeToContinue) 15186 Kind = PrevTagDecl->getTagKind(); 15187 else { 15188 // Recover by making this an anonymous redefinition. 15189 Name = nullptr; 15190 Previous.clear(); 15191 Invalid = true; 15192 } 15193 } 15194 15195 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15196 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15197 15198 // If this is an elaborated-type-specifier for a scoped enumeration, 15199 // the 'class' keyword is not necessary and not permitted. 15200 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15201 if (ScopedEnum) 15202 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15203 << PrevEnum->isScoped() 15204 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15205 return PrevTagDecl; 15206 } 15207 15208 QualType EnumUnderlyingTy; 15209 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15210 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15211 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15212 EnumUnderlyingTy = QualType(T, 0); 15213 15214 // All conflicts with previous declarations are recovered by 15215 // returning the previous declaration, unless this is a definition, 15216 // in which case we want the caller to bail out. 15217 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15218 ScopedEnum, EnumUnderlyingTy, 15219 IsFixed, PrevEnum)) 15220 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15221 } 15222 15223 // C++11 [class.mem]p1: 15224 // A member shall not be declared twice in the member-specification, 15225 // except that a nested class or member class template can be declared 15226 // and then later defined. 15227 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15228 S->isDeclScope(PrevDecl)) { 15229 Diag(NameLoc, diag::ext_member_redeclared); 15230 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15231 } 15232 15233 if (!Invalid) { 15234 // If this is a use, just return the declaration we found, unless 15235 // we have attributes. 15236 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15237 if (!Attrs.empty()) { 15238 // FIXME: Diagnose these attributes. For now, we create a new 15239 // declaration to hold them. 15240 } else if (TUK == TUK_Reference && 15241 (PrevTagDecl->getFriendObjectKind() == 15242 Decl::FOK_Undeclared || 15243 PrevDecl->getOwningModule() != getCurrentModule()) && 15244 SS.isEmpty()) { 15245 // This declaration is a reference to an existing entity, but 15246 // has different visibility from that entity: it either makes 15247 // a friend visible or it makes a type visible in a new module. 15248 // In either case, create a new declaration. We only do this if 15249 // the declaration would have meant the same thing if no prior 15250 // declaration were found, that is, if it was found in the same 15251 // scope where we would have injected a declaration. 15252 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15253 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15254 return PrevTagDecl; 15255 // This is in the injected scope, create a new declaration in 15256 // that scope. 15257 S = getTagInjectionScope(S, getLangOpts()); 15258 } else { 15259 return PrevTagDecl; 15260 } 15261 } 15262 15263 // Diagnose attempts to redefine a tag. 15264 if (TUK == TUK_Definition) { 15265 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15266 // If we're defining a specialization and the previous definition 15267 // is from an implicit instantiation, don't emit an error 15268 // here; we'll catch this in the general case below. 15269 bool IsExplicitSpecializationAfterInstantiation = false; 15270 if (isMemberSpecialization) { 15271 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15272 IsExplicitSpecializationAfterInstantiation = 15273 RD->getTemplateSpecializationKind() != 15274 TSK_ExplicitSpecialization; 15275 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15276 IsExplicitSpecializationAfterInstantiation = 15277 ED->getTemplateSpecializationKind() != 15278 TSK_ExplicitSpecialization; 15279 } 15280 15281 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15282 // not keep more that one definition around (merge them). However, 15283 // ensure the decl passes the structural compatibility check in 15284 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15285 NamedDecl *Hidden = nullptr; 15286 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15287 // There is a definition of this tag, but it is not visible. We 15288 // explicitly make use of C++'s one definition rule here, and 15289 // assume that this definition is identical to the hidden one 15290 // we already have. Make the existing definition visible and 15291 // use it in place of this one. 15292 if (!getLangOpts().CPlusPlus) { 15293 // Postpone making the old definition visible until after we 15294 // complete parsing the new one and do the structural 15295 // comparison. 15296 SkipBody->CheckSameAsPrevious = true; 15297 SkipBody->New = createTagFromNewDecl(); 15298 SkipBody->Previous = Def; 15299 return Def; 15300 } else { 15301 SkipBody->ShouldSkip = true; 15302 SkipBody->Previous = Def; 15303 makeMergedDefinitionVisible(Hidden); 15304 // Carry on and handle it like a normal definition. We'll 15305 // skip starting the definitiion later. 15306 } 15307 } else if (!IsExplicitSpecializationAfterInstantiation) { 15308 // A redeclaration in function prototype scope in C isn't 15309 // visible elsewhere, so merely issue a warning. 15310 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15311 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15312 else 15313 Diag(NameLoc, diag::err_redefinition) << Name; 15314 notePreviousDefinition(Def, 15315 NameLoc.isValid() ? NameLoc : KWLoc); 15316 // If this is a redefinition, recover by making this 15317 // struct be anonymous, which will make any later 15318 // references get the previous definition. 15319 Name = nullptr; 15320 Previous.clear(); 15321 Invalid = true; 15322 } 15323 } else { 15324 // If the type is currently being defined, complain 15325 // about a nested redefinition. 15326 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15327 if (TD->isBeingDefined()) { 15328 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15329 Diag(PrevTagDecl->getLocation(), 15330 diag::note_previous_definition); 15331 Name = nullptr; 15332 Previous.clear(); 15333 Invalid = true; 15334 } 15335 } 15336 15337 // Okay, this is definition of a previously declared or referenced 15338 // tag. We're going to create a new Decl for it. 15339 } 15340 15341 // Okay, we're going to make a redeclaration. If this is some kind 15342 // of reference, make sure we build the redeclaration in the same DC 15343 // as the original, and ignore the current access specifier. 15344 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15345 SearchDC = PrevTagDecl->getDeclContext(); 15346 AS = AS_none; 15347 } 15348 } 15349 // If we get here we have (another) forward declaration or we 15350 // have a definition. Just create a new decl. 15351 15352 } else { 15353 // If we get here, this is a definition of a new tag type in a nested 15354 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15355 // new decl/type. We set PrevDecl to NULL so that the entities 15356 // have distinct types. 15357 Previous.clear(); 15358 } 15359 // If we get here, we're going to create a new Decl. If PrevDecl 15360 // is non-NULL, it's a definition of the tag declared by 15361 // PrevDecl. If it's NULL, we have a new definition. 15362 15363 // Otherwise, PrevDecl is not a tag, but was found with tag 15364 // lookup. This is only actually possible in C++, where a few 15365 // things like templates still live in the tag namespace. 15366 } else { 15367 // Use a better diagnostic if an elaborated-type-specifier 15368 // found the wrong kind of type on the first 15369 // (non-redeclaration) lookup. 15370 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15371 !Previous.isForRedeclaration()) { 15372 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15373 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15374 << Kind; 15375 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15376 Invalid = true; 15377 15378 // Otherwise, only diagnose if the declaration is in scope. 15379 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15380 SS.isNotEmpty() || isMemberSpecialization)) { 15381 // do nothing 15382 15383 // Diagnose implicit declarations introduced by elaborated types. 15384 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15385 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15386 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15387 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15388 Invalid = true; 15389 15390 // Otherwise it's a declaration. Call out a particularly common 15391 // case here. 15392 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15393 unsigned Kind = 0; 15394 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15395 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15396 << Name << Kind << TND->getUnderlyingType(); 15397 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15398 Invalid = true; 15399 15400 // Otherwise, diagnose. 15401 } else { 15402 // The tag name clashes with something else in the target scope, 15403 // issue an error and recover by making this tag be anonymous. 15404 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15405 notePreviousDefinition(PrevDecl, NameLoc); 15406 Name = nullptr; 15407 Invalid = true; 15408 } 15409 15410 // The existing declaration isn't relevant to us; we're in a 15411 // new scope, so clear out the previous declaration. 15412 Previous.clear(); 15413 } 15414 } 15415 15416 CreateNewDecl: 15417 15418 TagDecl *PrevDecl = nullptr; 15419 if (Previous.isSingleResult()) 15420 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15421 15422 // If there is an identifier, use the location of the identifier as the 15423 // location of the decl, otherwise use the location of the struct/union 15424 // keyword. 15425 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15426 15427 // Otherwise, create a new declaration. If there is a previous 15428 // declaration of the same entity, the two will be linked via 15429 // PrevDecl. 15430 TagDecl *New; 15431 15432 if (Kind == TTK_Enum) { 15433 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15434 // enum X { A, B, C } D; D should chain to X. 15435 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15436 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15437 ScopedEnumUsesClassTag, IsFixed); 15438 15439 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15440 StdAlignValT = cast<EnumDecl>(New); 15441 15442 // If this is an undefined enum, warn. 15443 if (TUK != TUK_Definition && !Invalid) { 15444 TagDecl *Def; 15445 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15446 // C++0x: 7.2p2: opaque-enum-declaration. 15447 // Conflicts are diagnosed above. Do nothing. 15448 } 15449 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15450 Diag(Loc, diag::ext_forward_ref_enum_def) 15451 << New; 15452 Diag(Def->getLocation(), diag::note_previous_definition); 15453 } else { 15454 unsigned DiagID = diag::ext_forward_ref_enum; 15455 if (getLangOpts().MSVCCompat) 15456 DiagID = diag::ext_ms_forward_ref_enum; 15457 else if (getLangOpts().CPlusPlus) 15458 DiagID = diag::err_forward_ref_enum; 15459 Diag(Loc, DiagID); 15460 } 15461 } 15462 15463 if (EnumUnderlying) { 15464 EnumDecl *ED = cast<EnumDecl>(New); 15465 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15466 ED->setIntegerTypeSourceInfo(TI); 15467 else 15468 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15469 ED->setPromotionType(ED->getIntegerType()); 15470 assert(ED->isComplete() && "enum with type should be complete"); 15471 } 15472 } else { 15473 // struct/union/class 15474 15475 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15476 // struct X { int A; } D; D should chain to X. 15477 if (getLangOpts().CPlusPlus) { 15478 // FIXME: Look for a way to use RecordDecl for simple structs. 15479 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15480 cast_or_null<CXXRecordDecl>(PrevDecl)); 15481 15482 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15483 StdBadAlloc = cast<CXXRecordDecl>(New); 15484 } else 15485 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15486 cast_or_null<RecordDecl>(PrevDecl)); 15487 } 15488 15489 // C++11 [dcl.type]p3: 15490 // A type-specifier-seq shall not define a class or enumeration [...]. 15491 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15492 TUK == TUK_Definition) { 15493 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15494 << Context.getTagDeclType(New); 15495 Invalid = true; 15496 } 15497 15498 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15499 DC->getDeclKind() == Decl::Enum) { 15500 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15501 << Context.getTagDeclType(New); 15502 Invalid = true; 15503 } 15504 15505 // Maybe add qualifier info. 15506 if (SS.isNotEmpty()) { 15507 if (SS.isSet()) { 15508 // If this is either a declaration or a definition, check the 15509 // nested-name-specifier against the current context. 15510 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15511 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15512 isMemberSpecialization)) 15513 Invalid = true; 15514 15515 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15516 if (TemplateParameterLists.size() > 0) { 15517 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15518 } 15519 } 15520 else 15521 Invalid = true; 15522 } 15523 15524 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15525 // Add alignment attributes if necessary; these attributes are checked when 15526 // the ASTContext lays out the structure. 15527 // 15528 // It is important for implementing the correct semantics that this 15529 // happen here (in ActOnTag). The #pragma pack stack is 15530 // maintained as a result of parser callbacks which can occur at 15531 // many points during the parsing of a struct declaration (because 15532 // the #pragma tokens are effectively skipped over during the 15533 // parsing of the struct). 15534 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15535 AddAlignmentAttributesForRecord(RD); 15536 AddMsStructLayoutForRecord(RD); 15537 } 15538 } 15539 15540 if (ModulePrivateLoc.isValid()) { 15541 if (isMemberSpecialization) 15542 Diag(New->getLocation(), diag::err_module_private_specialization) 15543 << 2 15544 << FixItHint::CreateRemoval(ModulePrivateLoc); 15545 // __module_private__ does not apply to local classes. However, we only 15546 // diagnose this as an error when the declaration specifiers are 15547 // freestanding. Here, we just ignore the __module_private__. 15548 else if (!SearchDC->isFunctionOrMethod()) 15549 New->setModulePrivate(); 15550 } 15551 15552 // If this is a specialization of a member class (of a class template), 15553 // check the specialization. 15554 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15555 Invalid = true; 15556 15557 // If we're declaring or defining a tag in function prototype scope in C, 15558 // note that this type can only be used within the function and add it to 15559 // the list of decls to inject into the function definition scope. 15560 if ((Name || Kind == TTK_Enum) && 15561 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15562 if (getLangOpts().CPlusPlus) { 15563 // C++ [dcl.fct]p6: 15564 // Types shall not be defined in return or parameter types. 15565 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15566 Diag(Loc, diag::err_type_defined_in_param_type) 15567 << Name; 15568 Invalid = true; 15569 } 15570 } else if (!PrevDecl) { 15571 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15572 } 15573 } 15574 15575 if (Invalid) 15576 New->setInvalidDecl(); 15577 15578 // Set the lexical context. If the tag has a C++ scope specifier, the 15579 // lexical context will be different from the semantic context. 15580 New->setLexicalDeclContext(CurContext); 15581 15582 // Mark this as a friend decl if applicable. 15583 // In Microsoft mode, a friend declaration also acts as a forward 15584 // declaration so we always pass true to setObjectOfFriendDecl to make 15585 // the tag name visible. 15586 if (TUK == TUK_Friend) 15587 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15588 15589 // Set the access specifier. 15590 if (!Invalid && SearchDC->isRecord()) 15591 SetMemberAccessSpecifier(New, PrevDecl, AS); 15592 15593 if (PrevDecl) 15594 CheckRedeclarationModuleOwnership(New, PrevDecl); 15595 15596 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15597 New->startDefinition(); 15598 15599 ProcessDeclAttributeList(S, New, Attrs); 15600 AddPragmaAttributes(S, New); 15601 15602 // If this has an identifier, add it to the scope stack. 15603 if (TUK == TUK_Friend) { 15604 // We might be replacing an existing declaration in the lookup tables; 15605 // if so, borrow its access specifier. 15606 if (PrevDecl) 15607 New->setAccess(PrevDecl->getAccess()); 15608 15609 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15610 DC->makeDeclVisibleInContext(New); 15611 if (Name) // can be null along some error paths 15612 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15613 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15614 } else if (Name) { 15615 S = getNonFieldDeclScope(S); 15616 PushOnScopeChains(New, S, true); 15617 } else { 15618 CurContext->addDecl(New); 15619 } 15620 15621 // If this is the C FILE type, notify the AST context. 15622 if (IdentifierInfo *II = New->getIdentifier()) 15623 if (!New->isInvalidDecl() && 15624 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15625 II->isStr("FILE")) 15626 Context.setFILEDecl(New); 15627 15628 if (PrevDecl) 15629 mergeDeclAttributes(New, PrevDecl); 15630 15631 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15632 inferGslOwnerPointerAttribute(CXXRD); 15633 15634 // If there's a #pragma GCC visibility in scope, set the visibility of this 15635 // record. 15636 AddPushedVisibilityAttribute(New); 15637 15638 if (isMemberSpecialization && !New->isInvalidDecl()) 15639 CompleteMemberSpecialization(New, Previous); 15640 15641 OwnedDecl = true; 15642 // In C++, don't return an invalid declaration. We can't recover well from 15643 // the cases where we make the type anonymous. 15644 if (Invalid && getLangOpts().CPlusPlus) { 15645 if (New->isBeingDefined()) 15646 if (auto RD = dyn_cast<RecordDecl>(New)) 15647 RD->completeDefinition(); 15648 return nullptr; 15649 } else if (SkipBody && SkipBody->ShouldSkip) { 15650 return SkipBody->Previous; 15651 } else { 15652 return New; 15653 } 15654 } 15655 15656 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15657 AdjustDeclIfTemplate(TagD); 15658 TagDecl *Tag = cast<TagDecl>(TagD); 15659 15660 // Enter the tag context. 15661 PushDeclContext(S, Tag); 15662 15663 ActOnDocumentableDecl(TagD); 15664 15665 // If there's a #pragma GCC visibility in scope, set the visibility of this 15666 // record. 15667 AddPushedVisibilityAttribute(Tag); 15668 } 15669 15670 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15671 SkipBodyInfo &SkipBody) { 15672 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15673 return false; 15674 15675 // Make the previous decl visible. 15676 makeMergedDefinitionVisible(SkipBody.Previous); 15677 return true; 15678 } 15679 15680 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15681 assert(isa<ObjCContainerDecl>(IDecl) && 15682 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15683 DeclContext *OCD = cast<DeclContext>(IDecl); 15684 assert(getContainingDC(OCD) == CurContext && 15685 "The next DeclContext should be lexically contained in the current one."); 15686 CurContext = OCD; 15687 return IDecl; 15688 } 15689 15690 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15691 SourceLocation FinalLoc, 15692 bool IsFinalSpelledSealed, 15693 SourceLocation LBraceLoc) { 15694 AdjustDeclIfTemplate(TagD); 15695 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15696 15697 FieldCollector->StartClass(); 15698 15699 if (!Record->getIdentifier()) 15700 return; 15701 15702 if (FinalLoc.isValid()) 15703 Record->addAttr(FinalAttr::Create( 15704 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 15705 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 15706 15707 // C++ [class]p2: 15708 // [...] The class-name is also inserted into the scope of the 15709 // class itself; this is known as the injected-class-name. For 15710 // purposes of access checking, the injected-class-name is treated 15711 // as if it were a public member name. 15712 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15713 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15714 Record->getLocation(), Record->getIdentifier(), 15715 /*PrevDecl=*/nullptr, 15716 /*DelayTypeCreation=*/true); 15717 Context.getTypeDeclType(InjectedClassName, Record); 15718 InjectedClassName->setImplicit(); 15719 InjectedClassName->setAccess(AS_public); 15720 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15721 InjectedClassName->setDescribedClassTemplate(Template); 15722 PushOnScopeChains(InjectedClassName, S); 15723 assert(InjectedClassName->isInjectedClassName() && 15724 "Broken injected-class-name"); 15725 } 15726 15727 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15728 SourceRange BraceRange) { 15729 AdjustDeclIfTemplate(TagD); 15730 TagDecl *Tag = cast<TagDecl>(TagD); 15731 Tag->setBraceRange(BraceRange); 15732 15733 // Make sure we "complete" the definition even it is invalid. 15734 if (Tag->isBeingDefined()) { 15735 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15736 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15737 RD->completeDefinition(); 15738 } 15739 15740 if (isa<CXXRecordDecl>(Tag)) { 15741 FieldCollector->FinishClass(); 15742 } 15743 15744 // Exit this scope of this tag's definition. 15745 PopDeclContext(); 15746 15747 if (getCurLexicalContext()->isObjCContainer() && 15748 Tag->getDeclContext()->isFileContext()) 15749 Tag->setTopLevelDeclInObjCContainer(); 15750 15751 // Notify the consumer that we've defined a tag. 15752 if (!Tag->isInvalidDecl()) 15753 Consumer.HandleTagDeclDefinition(Tag); 15754 } 15755 15756 void Sema::ActOnObjCContainerFinishDefinition() { 15757 // Exit this scope of this interface definition. 15758 PopDeclContext(); 15759 } 15760 15761 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15762 assert(DC == CurContext && "Mismatch of container contexts"); 15763 OriginalLexicalContext = DC; 15764 ActOnObjCContainerFinishDefinition(); 15765 } 15766 15767 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15768 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15769 OriginalLexicalContext = nullptr; 15770 } 15771 15772 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15773 AdjustDeclIfTemplate(TagD); 15774 TagDecl *Tag = cast<TagDecl>(TagD); 15775 Tag->setInvalidDecl(); 15776 15777 // Make sure we "complete" the definition even it is invalid. 15778 if (Tag->isBeingDefined()) { 15779 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15780 RD->completeDefinition(); 15781 } 15782 15783 // We're undoing ActOnTagStartDefinition here, not 15784 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15785 // the FieldCollector. 15786 15787 PopDeclContext(); 15788 } 15789 15790 // Note that FieldName may be null for anonymous bitfields. 15791 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15792 IdentifierInfo *FieldName, 15793 QualType FieldTy, bool IsMsStruct, 15794 Expr *BitWidth, bool *ZeroWidth) { 15795 // Default to true; that shouldn't confuse checks for emptiness 15796 if (ZeroWidth) 15797 *ZeroWidth = true; 15798 15799 // C99 6.7.2.1p4 - verify the field type. 15800 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15801 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15802 // Handle incomplete types with specific error. 15803 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15804 return ExprError(); 15805 if (FieldName) 15806 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15807 << FieldName << FieldTy << BitWidth->getSourceRange(); 15808 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15809 << FieldTy << BitWidth->getSourceRange(); 15810 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15811 UPPC_BitFieldWidth)) 15812 return ExprError(); 15813 15814 // If the bit-width is type- or value-dependent, don't try to check 15815 // it now. 15816 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15817 return BitWidth; 15818 15819 llvm::APSInt Value; 15820 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15821 if (ICE.isInvalid()) 15822 return ICE; 15823 BitWidth = ICE.get(); 15824 15825 if (Value != 0 && ZeroWidth) 15826 *ZeroWidth = false; 15827 15828 // Zero-width bitfield is ok for anonymous field. 15829 if (Value == 0 && FieldName) 15830 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15831 15832 if (Value.isSigned() && Value.isNegative()) { 15833 if (FieldName) 15834 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15835 << FieldName << Value.toString(10); 15836 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15837 << Value.toString(10); 15838 } 15839 15840 if (!FieldTy->isDependentType()) { 15841 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15842 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15843 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15844 15845 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15846 // ABI. 15847 bool CStdConstraintViolation = 15848 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15849 bool MSBitfieldViolation = 15850 Value.ugt(TypeStorageSize) && 15851 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15852 if (CStdConstraintViolation || MSBitfieldViolation) { 15853 unsigned DiagWidth = 15854 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15855 if (FieldName) 15856 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15857 << FieldName << (unsigned)Value.getZExtValue() 15858 << !CStdConstraintViolation << DiagWidth; 15859 15860 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15861 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15862 << DiagWidth; 15863 } 15864 15865 // Warn on types where the user might conceivably expect to get all 15866 // specified bits as value bits: that's all integral types other than 15867 // 'bool'. 15868 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15869 if (FieldName) 15870 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15871 << FieldName << (unsigned)Value.getZExtValue() 15872 << (unsigned)TypeWidth; 15873 else 15874 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15875 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15876 } 15877 } 15878 15879 return BitWidth; 15880 } 15881 15882 /// ActOnField - Each field of a C struct/union is passed into this in order 15883 /// to create a FieldDecl object for it. 15884 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15885 Declarator &D, Expr *BitfieldWidth) { 15886 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15887 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15888 /*InitStyle=*/ICIS_NoInit, AS_public); 15889 return Res; 15890 } 15891 15892 /// HandleField - Analyze a field of a C struct or a C++ data member. 15893 /// 15894 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15895 SourceLocation DeclStart, 15896 Declarator &D, Expr *BitWidth, 15897 InClassInitStyle InitStyle, 15898 AccessSpecifier AS) { 15899 if (D.isDecompositionDeclarator()) { 15900 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15901 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15902 << Decomp.getSourceRange(); 15903 return nullptr; 15904 } 15905 15906 IdentifierInfo *II = D.getIdentifier(); 15907 SourceLocation Loc = DeclStart; 15908 if (II) Loc = D.getIdentifierLoc(); 15909 15910 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15911 QualType T = TInfo->getType(); 15912 if (getLangOpts().CPlusPlus) { 15913 CheckExtraCXXDefaultArguments(D); 15914 15915 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15916 UPPC_DataMemberType)) { 15917 D.setInvalidType(); 15918 T = Context.IntTy; 15919 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15920 } 15921 } 15922 15923 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15924 15925 if (D.getDeclSpec().isInlineSpecified()) 15926 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15927 << getLangOpts().CPlusPlus17; 15928 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15929 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15930 diag::err_invalid_thread) 15931 << DeclSpec::getSpecifierName(TSCS); 15932 15933 // Check to see if this name was declared as a member previously 15934 NamedDecl *PrevDecl = nullptr; 15935 LookupResult Previous(*this, II, Loc, LookupMemberName, 15936 ForVisibleRedeclaration); 15937 LookupName(Previous, S); 15938 switch (Previous.getResultKind()) { 15939 case LookupResult::Found: 15940 case LookupResult::FoundUnresolvedValue: 15941 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15942 break; 15943 15944 case LookupResult::FoundOverloaded: 15945 PrevDecl = Previous.getRepresentativeDecl(); 15946 break; 15947 15948 case LookupResult::NotFound: 15949 case LookupResult::NotFoundInCurrentInstantiation: 15950 case LookupResult::Ambiguous: 15951 break; 15952 } 15953 Previous.suppressDiagnostics(); 15954 15955 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15956 // Maybe we will complain about the shadowed template parameter. 15957 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15958 // Just pretend that we didn't see the previous declaration. 15959 PrevDecl = nullptr; 15960 } 15961 15962 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15963 PrevDecl = nullptr; 15964 15965 bool Mutable 15966 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15967 SourceLocation TSSL = D.getBeginLoc(); 15968 FieldDecl *NewFD 15969 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15970 TSSL, AS, PrevDecl, &D); 15971 15972 if (NewFD->isInvalidDecl()) 15973 Record->setInvalidDecl(); 15974 15975 if (D.getDeclSpec().isModulePrivateSpecified()) 15976 NewFD->setModulePrivate(); 15977 15978 if (NewFD->isInvalidDecl() && PrevDecl) { 15979 // Don't introduce NewFD into scope; there's already something 15980 // with the same name in the same scope. 15981 } else if (II) { 15982 PushOnScopeChains(NewFD, S); 15983 } else 15984 Record->addDecl(NewFD); 15985 15986 return NewFD; 15987 } 15988 15989 /// Build a new FieldDecl and check its well-formedness. 15990 /// 15991 /// This routine builds a new FieldDecl given the fields name, type, 15992 /// record, etc. \p PrevDecl should refer to any previous declaration 15993 /// with the same name and in the same scope as the field to be 15994 /// created. 15995 /// 15996 /// \returns a new FieldDecl. 15997 /// 15998 /// \todo The Declarator argument is a hack. It will be removed once 15999 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16000 TypeSourceInfo *TInfo, 16001 RecordDecl *Record, SourceLocation Loc, 16002 bool Mutable, Expr *BitWidth, 16003 InClassInitStyle InitStyle, 16004 SourceLocation TSSL, 16005 AccessSpecifier AS, NamedDecl *PrevDecl, 16006 Declarator *D) { 16007 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16008 bool InvalidDecl = false; 16009 if (D) InvalidDecl = D->isInvalidType(); 16010 16011 // If we receive a broken type, recover by assuming 'int' and 16012 // marking this declaration as invalid. 16013 if (T.isNull()) { 16014 InvalidDecl = true; 16015 T = Context.IntTy; 16016 } 16017 16018 QualType EltTy = Context.getBaseElementType(T); 16019 if (!EltTy->isDependentType()) { 16020 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 16021 // Fields of incomplete type force their record to be invalid. 16022 Record->setInvalidDecl(); 16023 InvalidDecl = true; 16024 } else { 16025 NamedDecl *Def; 16026 EltTy->isIncompleteType(&Def); 16027 if (Def && Def->isInvalidDecl()) { 16028 Record->setInvalidDecl(); 16029 InvalidDecl = true; 16030 } 16031 } 16032 } 16033 16034 // TR 18037 does not allow fields to be declared with address space 16035 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 16036 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16037 Diag(Loc, diag::err_field_with_address_space); 16038 Record->setInvalidDecl(); 16039 InvalidDecl = true; 16040 } 16041 16042 if (LangOpts.OpenCL) { 16043 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16044 // used as structure or union field: image, sampler, event or block types. 16045 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16046 T->isBlockPointerType()) { 16047 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16048 Record->setInvalidDecl(); 16049 InvalidDecl = true; 16050 } 16051 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16052 if (BitWidth) { 16053 Diag(Loc, diag::err_opencl_bitfields); 16054 InvalidDecl = true; 16055 } 16056 } 16057 16058 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16059 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16060 T.hasQualifiers()) { 16061 InvalidDecl = true; 16062 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16063 } 16064 16065 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16066 // than a variably modified type. 16067 if (!InvalidDecl && T->isVariablyModifiedType()) { 16068 bool SizeIsNegative; 16069 llvm::APSInt Oversized; 16070 16071 TypeSourceInfo *FixedTInfo = 16072 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16073 SizeIsNegative, 16074 Oversized); 16075 if (FixedTInfo) { 16076 Diag(Loc, diag::warn_illegal_constant_array_size); 16077 TInfo = FixedTInfo; 16078 T = FixedTInfo->getType(); 16079 } else { 16080 if (SizeIsNegative) 16081 Diag(Loc, diag::err_typecheck_negative_array_size); 16082 else if (Oversized.getBoolValue()) 16083 Diag(Loc, diag::err_array_too_large) 16084 << Oversized.toString(10); 16085 else 16086 Diag(Loc, diag::err_typecheck_field_variable_size); 16087 InvalidDecl = true; 16088 } 16089 } 16090 16091 // Fields can not have abstract class types 16092 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16093 diag::err_abstract_type_in_decl, 16094 AbstractFieldType)) 16095 InvalidDecl = true; 16096 16097 bool ZeroWidth = false; 16098 if (InvalidDecl) 16099 BitWidth = nullptr; 16100 // If this is declared as a bit-field, check the bit-field. 16101 if (BitWidth) { 16102 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16103 &ZeroWidth).get(); 16104 if (!BitWidth) { 16105 InvalidDecl = true; 16106 BitWidth = nullptr; 16107 ZeroWidth = false; 16108 } 16109 } 16110 16111 // Check that 'mutable' is consistent with the type of the declaration. 16112 if (!InvalidDecl && Mutable) { 16113 unsigned DiagID = 0; 16114 if (T->isReferenceType()) 16115 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16116 : diag::err_mutable_reference; 16117 else if (T.isConstQualified()) 16118 DiagID = diag::err_mutable_const; 16119 16120 if (DiagID) { 16121 SourceLocation ErrLoc = Loc; 16122 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16123 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16124 Diag(ErrLoc, DiagID); 16125 if (DiagID != diag::ext_mutable_reference) { 16126 Mutable = false; 16127 InvalidDecl = true; 16128 } 16129 } 16130 } 16131 16132 // C++11 [class.union]p8 (DR1460): 16133 // At most one variant member of a union may have a 16134 // brace-or-equal-initializer. 16135 if (InitStyle != ICIS_NoInit) 16136 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16137 16138 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16139 BitWidth, Mutable, InitStyle); 16140 if (InvalidDecl) 16141 NewFD->setInvalidDecl(); 16142 16143 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16144 Diag(Loc, diag::err_duplicate_member) << II; 16145 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16146 NewFD->setInvalidDecl(); 16147 } 16148 16149 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16150 if (Record->isUnion()) { 16151 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16152 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16153 if (RDecl->getDefinition()) { 16154 // C++ [class.union]p1: An object of a class with a non-trivial 16155 // constructor, a non-trivial copy constructor, a non-trivial 16156 // destructor, or a non-trivial copy assignment operator 16157 // cannot be a member of a union, nor can an array of such 16158 // objects. 16159 if (CheckNontrivialField(NewFD)) 16160 NewFD->setInvalidDecl(); 16161 } 16162 } 16163 16164 // C++ [class.union]p1: If a union contains a member of reference type, 16165 // the program is ill-formed, except when compiling with MSVC extensions 16166 // enabled. 16167 if (EltTy->isReferenceType()) { 16168 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16169 diag::ext_union_member_of_reference_type : 16170 diag::err_union_member_of_reference_type) 16171 << NewFD->getDeclName() << EltTy; 16172 if (!getLangOpts().MicrosoftExt) 16173 NewFD->setInvalidDecl(); 16174 } 16175 } 16176 } 16177 16178 // FIXME: We need to pass in the attributes given an AST 16179 // representation, not a parser representation. 16180 if (D) { 16181 // FIXME: The current scope is almost... but not entirely... correct here. 16182 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16183 16184 if (NewFD->hasAttrs()) 16185 CheckAlignasUnderalignment(NewFD); 16186 } 16187 16188 // In auto-retain/release, infer strong retension for fields of 16189 // retainable type. 16190 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16191 NewFD->setInvalidDecl(); 16192 16193 if (T.isObjCGCWeak()) 16194 Diag(Loc, diag::warn_attribute_weak_on_field); 16195 16196 NewFD->setAccess(AS); 16197 return NewFD; 16198 } 16199 16200 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16201 assert(FD); 16202 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16203 16204 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16205 return false; 16206 16207 QualType EltTy = Context.getBaseElementType(FD->getType()); 16208 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16209 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16210 if (RDecl->getDefinition()) { 16211 // We check for copy constructors before constructors 16212 // because otherwise we'll never get complaints about 16213 // copy constructors. 16214 16215 CXXSpecialMember member = CXXInvalid; 16216 // We're required to check for any non-trivial constructors. Since the 16217 // implicit default constructor is suppressed if there are any 16218 // user-declared constructors, we just need to check that there is a 16219 // trivial default constructor and a trivial copy constructor. (We don't 16220 // worry about move constructors here, since this is a C++98 check.) 16221 if (RDecl->hasNonTrivialCopyConstructor()) 16222 member = CXXCopyConstructor; 16223 else if (!RDecl->hasTrivialDefaultConstructor()) 16224 member = CXXDefaultConstructor; 16225 else if (RDecl->hasNonTrivialCopyAssignment()) 16226 member = CXXCopyAssignment; 16227 else if (RDecl->hasNonTrivialDestructor()) 16228 member = CXXDestructor; 16229 16230 if (member != CXXInvalid) { 16231 if (!getLangOpts().CPlusPlus11 && 16232 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16233 // Objective-C++ ARC: it is an error to have a non-trivial field of 16234 // a union. However, system headers in Objective-C programs 16235 // occasionally have Objective-C lifetime objects within unions, 16236 // and rather than cause the program to fail, we make those 16237 // members unavailable. 16238 SourceLocation Loc = FD->getLocation(); 16239 if (getSourceManager().isInSystemHeader(Loc)) { 16240 if (!FD->hasAttr<UnavailableAttr>()) 16241 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16242 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16243 return false; 16244 } 16245 } 16246 16247 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16248 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16249 diag::err_illegal_union_or_anon_struct_member) 16250 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16251 DiagnoseNontrivial(RDecl, member); 16252 return !getLangOpts().CPlusPlus11; 16253 } 16254 } 16255 } 16256 16257 return false; 16258 } 16259 16260 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16261 /// AST enum value. 16262 static ObjCIvarDecl::AccessControl 16263 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16264 switch (ivarVisibility) { 16265 default: llvm_unreachable("Unknown visitibility kind"); 16266 case tok::objc_private: return ObjCIvarDecl::Private; 16267 case tok::objc_public: return ObjCIvarDecl::Public; 16268 case tok::objc_protected: return ObjCIvarDecl::Protected; 16269 case tok::objc_package: return ObjCIvarDecl::Package; 16270 } 16271 } 16272 16273 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16274 /// in order to create an IvarDecl object for it. 16275 Decl *Sema::ActOnIvar(Scope *S, 16276 SourceLocation DeclStart, 16277 Declarator &D, Expr *BitfieldWidth, 16278 tok::ObjCKeywordKind Visibility) { 16279 16280 IdentifierInfo *II = D.getIdentifier(); 16281 Expr *BitWidth = (Expr*)BitfieldWidth; 16282 SourceLocation Loc = DeclStart; 16283 if (II) Loc = D.getIdentifierLoc(); 16284 16285 // FIXME: Unnamed fields can be handled in various different ways, for 16286 // example, unnamed unions inject all members into the struct namespace! 16287 16288 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16289 QualType T = TInfo->getType(); 16290 16291 if (BitWidth) { 16292 // 6.7.2.1p3, 6.7.2.1p4 16293 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16294 if (!BitWidth) 16295 D.setInvalidType(); 16296 } else { 16297 // Not a bitfield. 16298 16299 // validate II. 16300 16301 } 16302 if (T->isReferenceType()) { 16303 Diag(Loc, diag::err_ivar_reference_type); 16304 D.setInvalidType(); 16305 } 16306 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16307 // than a variably modified type. 16308 else if (T->isVariablyModifiedType()) { 16309 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16310 D.setInvalidType(); 16311 } 16312 16313 // Get the visibility (access control) for this ivar. 16314 ObjCIvarDecl::AccessControl ac = 16315 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16316 : ObjCIvarDecl::None; 16317 // Must set ivar's DeclContext to its enclosing interface. 16318 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16319 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16320 return nullptr; 16321 ObjCContainerDecl *EnclosingContext; 16322 if (ObjCImplementationDecl *IMPDecl = 16323 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16324 if (LangOpts.ObjCRuntime.isFragile()) { 16325 // Case of ivar declared in an implementation. Context is that of its class. 16326 EnclosingContext = IMPDecl->getClassInterface(); 16327 assert(EnclosingContext && "Implementation has no class interface!"); 16328 } 16329 else 16330 EnclosingContext = EnclosingDecl; 16331 } else { 16332 if (ObjCCategoryDecl *CDecl = 16333 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16334 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16335 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16336 return nullptr; 16337 } 16338 } 16339 EnclosingContext = EnclosingDecl; 16340 } 16341 16342 // Construct the decl. 16343 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16344 DeclStart, Loc, II, T, 16345 TInfo, ac, (Expr *)BitfieldWidth); 16346 16347 if (II) { 16348 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16349 ForVisibleRedeclaration); 16350 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16351 && !isa<TagDecl>(PrevDecl)) { 16352 Diag(Loc, diag::err_duplicate_member) << II; 16353 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16354 NewID->setInvalidDecl(); 16355 } 16356 } 16357 16358 // Process attributes attached to the ivar. 16359 ProcessDeclAttributes(S, NewID, D); 16360 16361 if (D.isInvalidType()) 16362 NewID->setInvalidDecl(); 16363 16364 // In ARC, infer 'retaining' for ivars of retainable type. 16365 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16366 NewID->setInvalidDecl(); 16367 16368 if (D.getDeclSpec().isModulePrivateSpecified()) 16369 NewID->setModulePrivate(); 16370 16371 if (II) { 16372 // FIXME: When interfaces are DeclContexts, we'll need to add 16373 // these to the interface. 16374 S->AddDecl(NewID); 16375 IdResolver.AddDecl(NewID); 16376 } 16377 16378 if (LangOpts.ObjCRuntime.isNonFragile() && 16379 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16380 Diag(Loc, diag::warn_ivars_in_interface); 16381 16382 return NewID; 16383 } 16384 16385 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16386 /// class and class extensions. For every class \@interface and class 16387 /// extension \@interface, if the last ivar is a bitfield of any type, 16388 /// then add an implicit `char :0` ivar to the end of that interface. 16389 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16390 SmallVectorImpl<Decl *> &AllIvarDecls) { 16391 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16392 return; 16393 16394 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16395 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16396 16397 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16398 return; 16399 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16400 if (!ID) { 16401 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16402 if (!CD->IsClassExtension()) 16403 return; 16404 } 16405 // No need to add this to end of @implementation. 16406 else 16407 return; 16408 } 16409 // All conditions are met. Add a new bitfield to the tail end of ivars. 16410 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16411 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16412 16413 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16414 DeclLoc, DeclLoc, nullptr, 16415 Context.CharTy, 16416 Context.getTrivialTypeSourceInfo(Context.CharTy, 16417 DeclLoc), 16418 ObjCIvarDecl::Private, BW, 16419 true); 16420 AllIvarDecls.push_back(Ivar); 16421 } 16422 16423 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16424 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16425 SourceLocation RBrac, 16426 const ParsedAttributesView &Attrs) { 16427 assert(EnclosingDecl && "missing record or interface decl"); 16428 16429 // If this is an Objective-C @implementation or category and we have 16430 // new fields here we should reset the layout of the interface since 16431 // it will now change. 16432 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16433 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16434 switch (DC->getKind()) { 16435 default: break; 16436 case Decl::ObjCCategory: 16437 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16438 break; 16439 case Decl::ObjCImplementation: 16440 Context. 16441 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16442 break; 16443 } 16444 } 16445 16446 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16447 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16448 16449 // Start counting up the number of named members; make sure to include 16450 // members of anonymous structs and unions in the total. 16451 unsigned NumNamedMembers = 0; 16452 if (Record) { 16453 for (const auto *I : Record->decls()) { 16454 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16455 if (IFD->getDeclName()) 16456 ++NumNamedMembers; 16457 } 16458 } 16459 16460 // Verify that all the fields are okay. 16461 SmallVector<FieldDecl*, 32> RecFields; 16462 16463 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16464 i != end; ++i) { 16465 FieldDecl *FD = cast<FieldDecl>(*i); 16466 16467 // Get the type for the field. 16468 const Type *FDTy = FD->getType().getTypePtr(); 16469 16470 if (!FD->isAnonymousStructOrUnion()) { 16471 // Remember all fields written by the user. 16472 RecFields.push_back(FD); 16473 } 16474 16475 // If the field is already invalid for some reason, don't emit more 16476 // diagnostics about it. 16477 if (FD->isInvalidDecl()) { 16478 EnclosingDecl->setInvalidDecl(); 16479 continue; 16480 } 16481 16482 // C99 6.7.2.1p2: 16483 // A structure or union shall not contain a member with 16484 // incomplete or function type (hence, a structure shall not 16485 // contain an instance of itself, but may contain a pointer to 16486 // an instance of itself), except that the last member of a 16487 // structure with more than one named member may have incomplete 16488 // array type; such a structure (and any union containing, 16489 // possibly recursively, a member that is such a structure) 16490 // shall not be a member of a structure or an element of an 16491 // array. 16492 bool IsLastField = (i + 1 == Fields.end()); 16493 if (FDTy->isFunctionType()) { 16494 // Field declared as a function. 16495 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16496 << FD->getDeclName(); 16497 FD->setInvalidDecl(); 16498 EnclosingDecl->setInvalidDecl(); 16499 continue; 16500 } else if (FDTy->isIncompleteArrayType() && 16501 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16502 if (Record) { 16503 // Flexible array member. 16504 // Microsoft and g++ is more permissive regarding flexible array. 16505 // It will accept flexible array in union and also 16506 // as the sole element of a struct/class. 16507 unsigned DiagID = 0; 16508 if (!Record->isUnion() && !IsLastField) { 16509 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16510 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16511 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16512 FD->setInvalidDecl(); 16513 EnclosingDecl->setInvalidDecl(); 16514 continue; 16515 } else if (Record->isUnion()) 16516 DiagID = getLangOpts().MicrosoftExt 16517 ? diag::ext_flexible_array_union_ms 16518 : getLangOpts().CPlusPlus 16519 ? diag::ext_flexible_array_union_gnu 16520 : diag::err_flexible_array_union; 16521 else if (NumNamedMembers < 1) 16522 DiagID = getLangOpts().MicrosoftExt 16523 ? diag::ext_flexible_array_empty_aggregate_ms 16524 : getLangOpts().CPlusPlus 16525 ? diag::ext_flexible_array_empty_aggregate_gnu 16526 : diag::err_flexible_array_empty_aggregate; 16527 16528 if (DiagID) 16529 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16530 << Record->getTagKind(); 16531 // While the layout of types that contain virtual bases is not specified 16532 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16533 // virtual bases after the derived members. This would make a flexible 16534 // array member declared at the end of an object not adjacent to the end 16535 // of the type. 16536 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16537 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16538 << FD->getDeclName() << Record->getTagKind(); 16539 if (!getLangOpts().C99) 16540 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16541 << FD->getDeclName() << Record->getTagKind(); 16542 16543 // If the element type has a non-trivial destructor, we would not 16544 // implicitly destroy the elements, so disallow it for now. 16545 // 16546 // FIXME: GCC allows this. We should probably either implicitly delete 16547 // the destructor of the containing class, or just allow this. 16548 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16549 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16550 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16551 << FD->getDeclName() << FD->getType(); 16552 FD->setInvalidDecl(); 16553 EnclosingDecl->setInvalidDecl(); 16554 continue; 16555 } 16556 // Okay, we have a legal flexible array member at the end of the struct. 16557 Record->setHasFlexibleArrayMember(true); 16558 } else { 16559 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16560 // unless they are followed by another ivar. That check is done 16561 // elsewhere, after synthesized ivars are known. 16562 } 16563 } else if (!FDTy->isDependentType() && 16564 RequireCompleteType(FD->getLocation(), FD->getType(), 16565 diag::err_field_incomplete)) { 16566 // Incomplete type 16567 FD->setInvalidDecl(); 16568 EnclosingDecl->setInvalidDecl(); 16569 continue; 16570 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16571 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16572 // A type which contains a flexible array member is considered to be a 16573 // flexible array member. 16574 Record->setHasFlexibleArrayMember(true); 16575 if (!Record->isUnion()) { 16576 // If this is a struct/class and this is not the last element, reject 16577 // it. Note that GCC supports variable sized arrays in the middle of 16578 // structures. 16579 if (!IsLastField) 16580 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16581 << FD->getDeclName() << FD->getType(); 16582 else { 16583 // We support flexible arrays at the end of structs in 16584 // other structs as an extension. 16585 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16586 << FD->getDeclName(); 16587 } 16588 } 16589 } 16590 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16591 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16592 diag::err_abstract_type_in_decl, 16593 AbstractIvarType)) { 16594 // Ivars can not have abstract class types 16595 FD->setInvalidDecl(); 16596 } 16597 if (Record && FDTTy->getDecl()->hasObjectMember()) 16598 Record->setHasObjectMember(true); 16599 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16600 Record->setHasVolatileMember(true); 16601 } else if (FDTy->isObjCObjectType()) { 16602 /// A field cannot be an Objective-c object 16603 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16604 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16605 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16606 FD->setType(T); 16607 } else if (Record && Record->isUnion() && 16608 FD->getType().hasNonTrivialObjCLifetime() && 16609 getSourceManager().isInSystemHeader(FD->getLocation()) && 16610 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16611 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16612 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16613 // For backward compatibility, fields of C unions declared in system 16614 // headers that have non-trivial ObjC ownership qualifications are marked 16615 // as unavailable unless the qualifier is explicit and __strong. This can 16616 // break ABI compatibility between programs compiled with ARC and MRR, but 16617 // is a better option than rejecting programs using those unions under 16618 // ARC. 16619 FD->addAttr(UnavailableAttr::CreateImplicit( 16620 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16621 FD->getLocation())); 16622 } else if (getLangOpts().ObjC && 16623 getLangOpts().getGC() != LangOptions::NonGC && 16624 Record && !Record->hasObjectMember()) { 16625 if (FD->getType()->isObjCObjectPointerType() || 16626 FD->getType().isObjCGCStrong()) 16627 Record->setHasObjectMember(true); 16628 else if (Context.getAsArrayType(FD->getType())) { 16629 QualType BaseType = Context.getBaseElementType(FD->getType()); 16630 if (BaseType->isRecordType() && 16631 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 16632 Record->setHasObjectMember(true); 16633 else if (BaseType->isObjCObjectPointerType() || 16634 BaseType.isObjCGCStrong()) 16635 Record->setHasObjectMember(true); 16636 } 16637 } 16638 16639 if (Record && !getLangOpts().CPlusPlus && 16640 !shouldIgnoreForRecordTriviality(FD)) { 16641 QualType FT = FD->getType(); 16642 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16643 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16644 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16645 Record->isUnion()) 16646 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16647 } 16648 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16649 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16650 Record->setNonTrivialToPrimitiveCopy(true); 16651 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16652 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16653 } 16654 if (FT.isDestructedType()) { 16655 Record->setNonTrivialToPrimitiveDestroy(true); 16656 Record->setParamDestroyedInCallee(true); 16657 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16658 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16659 } 16660 16661 if (const auto *RT = FT->getAs<RecordType>()) { 16662 if (RT->getDecl()->getArgPassingRestrictions() == 16663 RecordDecl::APK_CanNeverPassInRegs) 16664 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16665 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16666 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16667 } 16668 16669 if (Record && FD->getType().isVolatileQualified()) 16670 Record->setHasVolatileMember(true); 16671 // Keep track of the number of named members. 16672 if (FD->getIdentifier()) 16673 ++NumNamedMembers; 16674 } 16675 16676 // Okay, we successfully defined 'Record'. 16677 if (Record) { 16678 bool Completed = false; 16679 if (CXXRecord) { 16680 if (!CXXRecord->isInvalidDecl()) { 16681 // Set access bits correctly on the directly-declared conversions. 16682 for (CXXRecordDecl::conversion_iterator 16683 I = CXXRecord->conversion_begin(), 16684 E = CXXRecord->conversion_end(); I != E; ++I) 16685 I.setAccess((*I)->getAccess()); 16686 } 16687 16688 if (!CXXRecord->isDependentType()) { 16689 // Add any implicitly-declared members to this class. 16690 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16691 16692 if (!CXXRecord->isInvalidDecl()) { 16693 // If we have virtual base classes, we may end up finding multiple 16694 // final overriders for a given virtual function. Check for this 16695 // problem now. 16696 if (CXXRecord->getNumVBases()) { 16697 CXXFinalOverriderMap FinalOverriders; 16698 CXXRecord->getFinalOverriders(FinalOverriders); 16699 16700 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16701 MEnd = FinalOverriders.end(); 16702 M != MEnd; ++M) { 16703 for (OverridingMethods::iterator SO = M->second.begin(), 16704 SOEnd = M->second.end(); 16705 SO != SOEnd; ++SO) { 16706 assert(SO->second.size() > 0 && 16707 "Virtual function without overriding functions?"); 16708 if (SO->second.size() == 1) 16709 continue; 16710 16711 // C++ [class.virtual]p2: 16712 // In a derived class, if a virtual member function of a base 16713 // class subobject has more than one final overrider the 16714 // program is ill-formed. 16715 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16716 << (const NamedDecl *)M->first << Record; 16717 Diag(M->first->getLocation(), 16718 diag::note_overridden_virtual_function); 16719 for (OverridingMethods::overriding_iterator 16720 OM = SO->second.begin(), 16721 OMEnd = SO->second.end(); 16722 OM != OMEnd; ++OM) 16723 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16724 << (const NamedDecl *)M->first << OM->Method->getParent(); 16725 16726 Record->setInvalidDecl(); 16727 } 16728 } 16729 CXXRecord->completeDefinition(&FinalOverriders); 16730 Completed = true; 16731 } 16732 } 16733 } 16734 } 16735 16736 if (!Completed) 16737 Record->completeDefinition(); 16738 16739 // Handle attributes before checking the layout. 16740 ProcessDeclAttributeList(S, Record, Attrs); 16741 16742 // We may have deferred checking for a deleted destructor. Check now. 16743 if (CXXRecord) { 16744 auto *Dtor = CXXRecord->getDestructor(); 16745 if (Dtor && Dtor->isImplicit() && 16746 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16747 CXXRecord->setImplicitDestructorIsDeleted(); 16748 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16749 } 16750 } 16751 16752 if (Record->hasAttrs()) { 16753 CheckAlignasUnderalignment(Record); 16754 16755 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16756 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16757 IA->getRange(), IA->getBestCase(), 16758 IA->getSemanticSpelling()); 16759 } 16760 16761 // Check if the structure/union declaration is a type that can have zero 16762 // size in C. For C this is a language extension, for C++ it may cause 16763 // compatibility problems. 16764 bool CheckForZeroSize; 16765 if (!getLangOpts().CPlusPlus) { 16766 CheckForZeroSize = true; 16767 } else { 16768 // For C++ filter out types that cannot be referenced in C code. 16769 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16770 CheckForZeroSize = 16771 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16772 !CXXRecord->isDependentType() && 16773 CXXRecord->isCLike(); 16774 } 16775 if (CheckForZeroSize) { 16776 bool ZeroSize = true; 16777 bool IsEmpty = true; 16778 unsigned NonBitFields = 0; 16779 for (RecordDecl::field_iterator I = Record->field_begin(), 16780 E = Record->field_end(); 16781 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16782 IsEmpty = false; 16783 if (I->isUnnamedBitfield()) { 16784 if (!I->isZeroLengthBitField(Context)) 16785 ZeroSize = false; 16786 } else { 16787 ++NonBitFields; 16788 QualType FieldType = I->getType(); 16789 if (FieldType->isIncompleteType() || 16790 !Context.getTypeSizeInChars(FieldType).isZero()) 16791 ZeroSize = false; 16792 } 16793 } 16794 16795 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16796 // allowed in C++, but warn if its declaration is inside 16797 // extern "C" block. 16798 if (ZeroSize) { 16799 Diag(RecLoc, getLangOpts().CPlusPlus ? 16800 diag::warn_zero_size_struct_union_in_extern_c : 16801 diag::warn_zero_size_struct_union_compat) 16802 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16803 } 16804 16805 // Structs without named members are extension in C (C99 6.7.2.1p7), 16806 // but are accepted by GCC. 16807 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16808 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16809 diag::ext_no_named_members_in_struct_union) 16810 << Record->isUnion(); 16811 } 16812 } 16813 } else { 16814 ObjCIvarDecl **ClsFields = 16815 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16816 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16817 ID->setEndOfDefinitionLoc(RBrac); 16818 // Add ivar's to class's DeclContext. 16819 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16820 ClsFields[i]->setLexicalDeclContext(ID); 16821 ID->addDecl(ClsFields[i]); 16822 } 16823 // Must enforce the rule that ivars in the base classes may not be 16824 // duplicates. 16825 if (ID->getSuperClass()) 16826 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16827 } else if (ObjCImplementationDecl *IMPDecl = 16828 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16829 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16830 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16831 // Ivar declared in @implementation never belongs to the implementation. 16832 // Only it is in implementation's lexical context. 16833 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16834 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16835 IMPDecl->setIvarLBraceLoc(LBrac); 16836 IMPDecl->setIvarRBraceLoc(RBrac); 16837 } else if (ObjCCategoryDecl *CDecl = 16838 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16839 // case of ivars in class extension; all other cases have been 16840 // reported as errors elsewhere. 16841 // FIXME. Class extension does not have a LocEnd field. 16842 // CDecl->setLocEnd(RBrac); 16843 // Add ivar's to class extension's DeclContext. 16844 // Diagnose redeclaration of private ivars. 16845 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16846 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16847 if (IDecl) { 16848 if (const ObjCIvarDecl *ClsIvar = 16849 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16850 Diag(ClsFields[i]->getLocation(), 16851 diag::err_duplicate_ivar_declaration); 16852 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16853 continue; 16854 } 16855 for (const auto *Ext : IDecl->known_extensions()) { 16856 if (const ObjCIvarDecl *ClsExtIvar 16857 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16858 Diag(ClsFields[i]->getLocation(), 16859 diag::err_duplicate_ivar_declaration); 16860 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16861 continue; 16862 } 16863 } 16864 } 16865 ClsFields[i]->setLexicalDeclContext(CDecl); 16866 CDecl->addDecl(ClsFields[i]); 16867 } 16868 CDecl->setIvarLBraceLoc(LBrac); 16869 CDecl->setIvarRBraceLoc(RBrac); 16870 } 16871 } 16872 } 16873 16874 /// Determine whether the given integral value is representable within 16875 /// the given type T. 16876 static bool isRepresentableIntegerValue(ASTContext &Context, 16877 llvm::APSInt &Value, 16878 QualType T) { 16879 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16880 "Integral type required!"); 16881 unsigned BitWidth = Context.getIntWidth(T); 16882 16883 if (Value.isUnsigned() || Value.isNonNegative()) { 16884 if (T->isSignedIntegerOrEnumerationType()) 16885 --BitWidth; 16886 return Value.getActiveBits() <= BitWidth; 16887 } 16888 return Value.getMinSignedBits() <= BitWidth; 16889 } 16890 16891 // Given an integral type, return the next larger integral type 16892 // (or a NULL type of no such type exists). 16893 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16894 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16895 // enum checking below. 16896 assert((T->isIntegralType(Context) || 16897 T->isEnumeralType()) && "Integral type required!"); 16898 const unsigned NumTypes = 4; 16899 QualType SignedIntegralTypes[NumTypes] = { 16900 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16901 }; 16902 QualType UnsignedIntegralTypes[NumTypes] = { 16903 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16904 Context.UnsignedLongLongTy 16905 }; 16906 16907 unsigned BitWidth = Context.getTypeSize(T); 16908 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16909 : UnsignedIntegralTypes; 16910 for (unsigned I = 0; I != NumTypes; ++I) 16911 if (Context.getTypeSize(Types[I]) > BitWidth) 16912 return Types[I]; 16913 16914 return QualType(); 16915 } 16916 16917 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16918 EnumConstantDecl *LastEnumConst, 16919 SourceLocation IdLoc, 16920 IdentifierInfo *Id, 16921 Expr *Val) { 16922 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16923 llvm::APSInt EnumVal(IntWidth); 16924 QualType EltTy; 16925 16926 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16927 Val = nullptr; 16928 16929 if (Val) 16930 Val = DefaultLvalueConversion(Val).get(); 16931 16932 if (Val) { 16933 if (Enum->isDependentType() || Val->isTypeDependent()) 16934 EltTy = Context.DependentTy; 16935 else { 16936 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 16937 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16938 // constant-expression in the enumerator-definition shall be a converted 16939 // constant expression of the underlying type. 16940 EltTy = Enum->getIntegerType(); 16941 ExprResult Converted = 16942 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16943 CCEK_Enumerator); 16944 if (Converted.isInvalid()) 16945 Val = nullptr; 16946 else 16947 Val = Converted.get(); 16948 } else if (!Val->isValueDependent() && 16949 !(Val = VerifyIntegerConstantExpression(Val, 16950 &EnumVal).get())) { 16951 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16952 } else { 16953 if (Enum->isComplete()) { 16954 EltTy = Enum->getIntegerType(); 16955 16956 // In Obj-C and Microsoft mode, require the enumeration value to be 16957 // representable in the underlying type of the enumeration. In C++11, 16958 // we perform a non-narrowing conversion as part of converted constant 16959 // expression checking. 16960 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16961 if (Context.getTargetInfo() 16962 .getTriple() 16963 .isWindowsMSVCEnvironment()) { 16964 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16965 } else { 16966 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16967 } 16968 } 16969 16970 // Cast to the underlying type. 16971 Val = ImpCastExprToType(Val, EltTy, 16972 EltTy->isBooleanType() ? CK_IntegralToBoolean 16973 : CK_IntegralCast) 16974 .get(); 16975 } else if (getLangOpts().CPlusPlus) { 16976 // C++11 [dcl.enum]p5: 16977 // If the underlying type is not fixed, the type of each enumerator 16978 // is the type of its initializing value: 16979 // - If an initializer is specified for an enumerator, the 16980 // initializing value has the same type as the expression. 16981 EltTy = Val->getType(); 16982 } else { 16983 // C99 6.7.2.2p2: 16984 // The expression that defines the value of an enumeration constant 16985 // shall be an integer constant expression that has a value 16986 // representable as an int. 16987 16988 // Complain if the value is not representable in an int. 16989 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16990 Diag(IdLoc, diag::ext_enum_value_not_int) 16991 << EnumVal.toString(10) << Val->getSourceRange() 16992 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16993 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16994 // Force the type of the expression to 'int'. 16995 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16996 } 16997 EltTy = Val->getType(); 16998 } 16999 } 17000 } 17001 } 17002 17003 if (!Val) { 17004 if (Enum->isDependentType()) 17005 EltTy = Context.DependentTy; 17006 else if (!LastEnumConst) { 17007 // C++0x [dcl.enum]p5: 17008 // If the underlying type is not fixed, the type of each enumerator 17009 // is the type of its initializing value: 17010 // - If no initializer is specified for the first enumerator, the 17011 // initializing value has an unspecified integral type. 17012 // 17013 // GCC uses 'int' for its unspecified integral type, as does 17014 // C99 6.7.2.2p3. 17015 if (Enum->isFixed()) { 17016 EltTy = Enum->getIntegerType(); 17017 } 17018 else { 17019 EltTy = Context.IntTy; 17020 } 17021 } else { 17022 // Assign the last value + 1. 17023 EnumVal = LastEnumConst->getInitVal(); 17024 ++EnumVal; 17025 EltTy = LastEnumConst->getType(); 17026 17027 // Check for overflow on increment. 17028 if (EnumVal < LastEnumConst->getInitVal()) { 17029 // C++0x [dcl.enum]p5: 17030 // If the underlying type is not fixed, the type of each enumerator 17031 // is the type of its initializing value: 17032 // 17033 // - Otherwise the type of the initializing value is the same as 17034 // the type of the initializing value of the preceding enumerator 17035 // unless the incremented value is not representable in that type, 17036 // in which case the type is an unspecified integral type 17037 // sufficient to contain the incremented value. If no such type 17038 // exists, the program is ill-formed. 17039 QualType T = getNextLargerIntegralType(Context, EltTy); 17040 if (T.isNull() || Enum->isFixed()) { 17041 // There is no integral type larger enough to represent this 17042 // value. Complain, then allow the value to wrap around. 17043 EnumVal = LastEnumConst->getInitVal(); 17044 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17045 ++EnumVal; 17046 if (Enum->isFixed()) 17047 // When the underlying type is fixed, this is ill-formed. 17048 Diag(IdLoc, diag::err_enumerator_wrapped) 17049 << EnumVal.toString(10) 17050 << EltTy; 17051 else 17052 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17053 << EnumVal.toString(10); 17054 } else { 17055 EltTy = T; 17056 } 17057 17058 // Retrieve the last enumerator's value, extent that type to the 17059 // type that is supposed to be large enough to represent the incremented 17060 // value, then increment. 17061 EnumVal = LastEnumConst->getInitVal(); 17062 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17063 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17064 ++EnumVal; 17065 17066 // If we're not in C++, diagnose the overflow of enumerator values, 17067 // which in C99 means that the enumerator value is not representable in 17068 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17069 // permits enumerator values that are representable in some larger 17070 // integral type. 17071 if (!getLangOpts().CPlusPlus && !T.isNull()) 17072 Diag(IdLoc, diag::warn_enum_value_overflow); 17073 } else if (!getLangOpts().CPlusPlus && 17074 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17075 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17076 Diag(IdLoc, diag::ext_enum_value_not_int) 17077 << EnumVal.toString(10) << 1; 17078 } 17079 } 17080 } 17081 17082 if (!EltTy->isDependentType()) { 17083 // Make the enumerator value match the signedness and size of the 17084 // enumerator's type. 17085 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17086 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17087 } 17088 17089 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17090 Val, EnumVal); 17091 } 17092 17093 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17094 SourceLocation IILoc) { 17095 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17096 !getLangOpts().CPlusPlus) 17097 return SkipBodyInfo(); 17098 17099 // We have an anonymous enum definition. Look up the first enumerator to 17100 // determine if we should merge the definition with an existing one and 17101 // skip the body. 17102 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17103 forRedeclarationInCurContext()); 17104 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17105 if (!PrevECD) 17106 return SkipBodyInfo(); 17107 17108 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17109 NamedDecl *Hidden; 17110 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17111 SkipBodyInfo Skip; 17112 Skip.Previous = Hidden; 17113 return Skip; 17114 } 17115 17116 return SkipBodyInfo(); 17117 } 17118 17119 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17120 SourceLocation IdLoc, IdentifierInfo *Id, 17121 const ParsedAttributesView &Attrs, 17122 SourceLocation EqualLoc, Expr *Val) { 17123 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17124 EnumConstantDecl *LastEnumConst = 17125 cast_or_null<EnumConstantDecl>(lastEnumConst); 17126 17127 // The scope passed in may not be a decl scope. Zip up the scope tree until 17128 // we find one that is. 17129 S = getNonFieldDeclScope(S); 17130 17131 // Verify that there isn't already something declared with this name in this 17132 // scope. 17133 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17134 LookupName(R, S); 17135 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17136 17137 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17138 // Maybe we will complain about the shadowed template parameter. 17139 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17140 // Just pretend that we didn't see the previous declaration. 17141 PrevDecl = nullptr; 17142 } 17143 17144 // C++ [class.mem]p15: 17145 // If T is the name of a class, then each of the following shall have a name 17146 // different from T: 17147 // - every enumerator of every member of class T that is an unscoped 17148 // enumerated type 17149 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17150 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17151 DeclarationNameInfo(Id, IdLoc)); 17152 17153 EnumConstantDecl *New = 17154 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17155 if (!New) 17156 return nullptr; 17157 17158 if (PrevDecl) { 17159 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17160 // Check for other kinds of shadowing not already handled. 17161 CheckShadow(New, PrevDecl, R); 17162 } 17163 17164 // When in C++, we may get a TagDecl with the same name; in this case the 17165 // enum constant will 'hide' the tag. 17166 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17167 "Received TagDecl when not in C++!"); 17168 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17169 if (isa<EnumConstantDecl>(PrevDecl)) 17170 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17171 else 17172 Diag(IdLoc, diag::err_redefinition) << Id; 17173 notePreviousDefinition(PrevDecl, IdLoc); 17174 return nullptr; 17175 } 17176 } 17177 17178 // Process attributes. 17179 ProcessDeclAttributeList(S, New, Attrs); 17180 AddPragmaAttributes(S, New); 17181 17182 // Register this decl in the current scope stack. 17183 New->setAccess(TheEnumDecl->getAccess()); 17184 PushOnScopeChains(New, S); 17185 17186 ActOnDocumentableDecl(New); 17187 17188 return New; 17189 } 17190 17191 // Returns true when the enum initial expression does not trigger the 17192 // duplicate enum warning. A few common cases are exempted as follows: 17193 // Element2 = Element1 17194 // Element2 = Element1 + 1 17195 // Element2 = Element1 - 1 17196 // Where Element2 and Element1 are from the same enum. 17197 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17198 Expr *InitExpr = ECD->getInitExpr(); 17199 if (!InitExpr) 17200 return true; 17201 InitExpr = InitExpr->IgnoreImpCasts(); 17202 17203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17204 if (!BO->isAdditiveOp()) 17205 return true; 17206 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17207 if (!IL) 17208 return true; 17209 if (IL->getValue() != 1) 17210 return true; 17211 17212 InitExpr = BO->getLHS(); 17213 } 17214 17215 // This checks if the elements are from the same enum. 17216 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17217 if (!DRE) 17218 return true; 17219 17220 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17221 if (!EnumConstant) 17222 return true; 17223 17224 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17225 Enum) 17226 return true; 17227 17228 return false; 17229 } 17230 17231 // Emits a warning when an element is implicitly set a value that 17232 // a previous element has already been set to. 17233 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17234 EnumDecl *Enum, QualType EnumType) { 17235 // Avoid anonymous enums 17236 if (!Enum->getIdentifier()) 17237 return; 17238 17239 // Only check for small enums. 17240 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17241 return; 17242 17243 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17244 return; 17245 17246 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17247 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17248 17249 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17250 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17251 17252 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 17253 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17254 llvm::APSInt Val = D->getInitVal(); 17255 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17256 }; 17257 17258 DuplicatesVector DupVector; 17259 ValueToVectorMap EnumMap; 17260 17261 // Populate the EnumMap with all values represented by enum constants without 17262 // an initializer. 17263 for (auto *Element : Elements) { 17264 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17265 17266 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17267 // this constant. Skip this enum since it may be ill-formed. 17268 if (!ECD) { 17269 return; 17270 } 17271 17272 // Constants with initalizers are handled in the next loop. 17273 if (ECD->getInitExpr()) 17274 continue; 17275 17276 // Duplicate values are handled in the next loop. 17277 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17278 } 17279 17280 if (EnumMap.size() == 0) 17281 return; 17282 17283 // Create vectors for any values that has duplicates. 17284 for (auto *Element : Elements) { 17285 // The last loop returned if any constant was null. 17286 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17287 if (!ValidDuplicateEnum(ECD, Enum)) 17288 continue; 17289 17290 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17291 if (Iter == EnumMap.end()) 17292 continue; 17293 17294 DeclOrVector& Entry = Iter->second; 17295 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17296 // Ensure constants are different. 17297 if (D == ECD) 17298 continue; 17299 17300 // Create new vector and push values onto it. 17301 auto Vec = std::make_unique<ECDVector>(); 17302 Vec->push_back(D); 17303 Vec->push_back(ECD); 17304 17305 // Update entry to point to the duplicates vector. 17306 Entry = Vec.get(); 17307 17308 // Store the vector somewhere we can consult later for quick emission of 17309 // diagnostics. 17310 DupVector.emplace_back(std::move(Vec)); 17311 continue; 17312 } 17313 17314 ECDVector *Vec = Entry.get<ECDVector*>(); 17315 // Make sure constants are not added more than once. 17316 if (*Vec->begin() == ECD) 17317 continue; 17318 17319 Vec->push_back(ECD); 17320 } 17321 17322 // Emit diagnostics. 17323 for (const auto &Vec : DupVector) { 17324 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17325 17326 // Emit warning for one enum constant. 17327 auto *FirstECD = Vec->front(); 17328 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17329 << FirstECD << FirstECD->getInitVal().toString(10) 17330 << FirstECD->getSourceRange(); 17331 17332 // Emit one note for each of the remaining enum constants with 17333 // the same value. 17334 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17335 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17336 << ECD << ECD->getInitVal().toString(10) 17337 << ECD->getSourceRange(); 17338 } 17339 } 17340 17341 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17342 bool AllowMask) const { 17343 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17344 assert(ED->isCompleteDefinition() && "expected enum definition"); 17345 17346 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17347 llvm::APInt &FlagBits = R.first->second; 17348 17349 if (R.second) { 17350 for (auto *E : ED->enumerators()) { 17351 const auto &EVal = E->getInitVal(); 17352 // Only single-bit enumerators introduce new flag values. 17353 if (EVal.isPowerOf2()) 17354 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17355 } 17356 } 17357 17358 // A value is in a flag enum if either its bits are a subset of the enum's 17359 // flag bits (the first condition) or we are allowing masks and the same is 17360 // true of its complement (the second condition). When masks are allowed, we 17361 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17362 // 17363 // While it's true that any value could be used as a mask, the assumption is 17364 // that a mask will have all of the insignificant bits set. Anything else is 17365 // likely a logic error. 17366 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17367 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17368 } 17369 17370 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17371 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17372 const ParsedAttributesView &Attrs) { 17373 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17374 QualType EnumType = Context.getTypeDeclType(Enum); 17375 17376 ProcessDeclAttributeList(S, Enum, Attrs); 17377 17378 if (Enum->isDependentType()) { 17379 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17380 EnumConstantDecl *ECD = 17381 cast_or_null<EnumConstantDecl>(Elements[i]); 17382 if (!ECD) continue; 17383 17384 ECD->setType(EnumType); 17385 } 17386 17387 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17388 return; 17389 } 17390 17391 // TODO: If the result value doesn't fit in an int, it must be a long or long 17392 // long value. ISO C does not support this, but GCC does as an extension, 17393 // emit a warning. 17394 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17395 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17396 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17397 17398 // Verify that all the values are okay, compute the size of the values, and 17399 // reverse the list. 17400 unsigned NumNegativeBits = 0; 17401 unsigned NumPositiveBits = 0; 17402 17403 // Keep track of whether all elements have type int. 17404 bool AllElementsInt = true; 17405 17406 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17407 EnumConstantDecl *ECD = 17408 cast_or_null<EnumConstantDecl>(Elements[i]); 17409 if (!ECD) continue; // Already issued a diagnostic. 17410 17411 const llvm::APSInt &InitVal = ECD->getInitVal(); 17412 17413 // Keep track of the size of positive and negative values. 17414 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17415 NumPositiveBits = std::max(NumPositiveBits, 17416 (unsigned)InitVal.getActiveBits()); 17417 else 17418 NumNegativeBits = std::max(NumNegativeBits, 17419 (unsigned)InitVal.getMinSignedBits()); 17420 17421 // Keep track of whether every enum element has type int (very common). 17422 if (AllElementsInt) 17423 AllElementsInt = ECD->getType() == Context.IntTy; 17424 } 17425 17426 // Figure out the type that should be used for this enum. 17427 QualType BestType; 17428 unsigned BestWidth; 17429 17430 // C++0x N3000 [conv.prom]p3: 17431 // An rvalue of an unscoped enumeration type whose underlying 17432 // type is not fixed can be converted to an rvalue of the first 17433 // of the following types that can represent all the values of 17434 // the enumeration: int, unsigned int, long int, unsigned long 17435 // int, long long int, or unsigned long long int. 17436 // C99 6.4.4.3p2: 17437 // An identifier declared as an enumeration constant has type int. 17438 // The C99 rule is modified by a gcc extension 17439 QualType BestPromotionType; 17440 17441 bool Packed = Enum->hasAttr<PackedAttr>(); 17442 // -fshort-enums is the equivalent to specifying the packed attribute on all 17443 // enum definitions. 17444 if (LangOpts.ShortEnums) 17445 Packed = true; 17446 17447 // If the enum already has a type because it is fixed or dictated by the 17448 // target, promote that type instead of analyzing the enumerators. 17449 if (Enum->isComplete()) { 17450 BestType = Enum->getIntegerType(); 17451 if (BestType->isPromotableIntegerType()) 17452 BestPromotionType = Context.getPromotedIntegerType(BestType); 17453 else 17454 BestPromotionType = BestType; 17455 17456 BestWidth = Context.getIntWidth(BestType); 17457 } 17458 else if (NumNegativeBits) { 17459 // If there is a negative value, figure out the smallest integer type (of 17460 // int/long/longlong) that fits. 17461 // If it's packed, check also if it fits a char or a short. 17462 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17463 BestType = Context.SignedCharTy; 17464 BestWidth = CharWidth; 17465 } else if (Packed && NumNegativeBits <= ShortWidth && 17466 NumPositiveBits < ShortWidth) { 17467 BestType = Context.ShortTy; 17468 BestWidth = ShortWidth; 17469 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17470 BestType = Context.IntTy; 17471 BestWidth = IntWidth; 17472 } else { 17473 BestWidth = Context.getTargetInfo().getLongWidth(); 17474 17475 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17476 BestType = Context.LongTy; 17477 } else { 17478 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17479 17480 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17481 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17482 BestType = Context.LongLongTy; 17483 } 17484 } 17485 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17486 } else { 17487 // If there is no negative value, figure out the smallest type that fits 17488 // all of the enumerator values. 17489 // If it's packed, check also if it fits a char or a short. 17490 if (Packed && NumPositiveBits <= CharWidth) { 17491 BestType = Context.UnsignedCharTy; 17492 BestPromotionType = Context.IntTy; 17493 BestWidth = CharWidth; 17494 } else if (Packed && NumPositiveBits <= ShortWidth) { 17495 BestType = Context.UnsignedShortTy; 17496 BestPromotionType = Context.IntTy; 17497 BestWidth = ShortWidth; 17498 } else if (NumPositiveBits <= IntWidth) { 17499 BestType = Context.UnsignedIntTy; 17500 BestWidth = IntWidth; 17501 BestPromotionType 17502 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17503 ? Context.UnsignedIntTy : Context.IntTy; 17504 } else if (NumPositiveBits <= 17505 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17506 BestType = Context.UnsignedLongTy; 17507 BestPromotionType 17508 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17509 ? Context.UnsignedLongTy : Context.LongTy; 17510 } else { 17511 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17512 assert(NumPositiveBits <= BestWidth && 17513 "How could an initializer get larger than ULL?"); 17514 BestType = Context.UnsignedLongLongTy; 17515 BestPromotionType 17516 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17517 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17518 } 17519 } 17520 17521 // Loop over all of the enumerator constants, changing their types to match 17522 // the type of the enum if needed. 17523 for (auto *D : Elements) { 17524 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17525 if (!ECD) continue; // Already issued a diagnostic. 17526 17527 // Standard C says the enumerators have int type, but we allow, as an 17528 // extension, the enumerators to be larger than int size. If each 17529 // enumerator value fits in an int, type it as an int, otherwise type it the 17530 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17531 // that X has type 'int', not 'unsigned'. 17532 17533 // Determine whether the value fits into an int. 17534 llvm::APSInt InitVal = ECD->getInitVal(); 17535 17536 // If it fits into an integer type, force it. Otherwise force it to match 17537 // the enum decl type. 17538 QualType NewTy; 17539 unsigned NewWidth; 17540 bool NewSign; 17541 if (!getLangOpts().CPlusPlus && 17542 !Enum->isFixed() && 17543 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17544 NewTy = Context.IntTy; 17545 NewWidth = IntWidth; 17546 NewSign = true; 17547 } else if (ECD->getType() == BestType) { 17548 // Already the right type! 17549 if (getLangOpts().CPlusPlus) 17550 // C++ [dcl.enum]p4: Following the closing brace of an 17551 // enum-specifier, each enumerator has the type of its 17552 // enumeration. 17553 ECD->setType(EnumType); 17554 continue; 17555 } else { 17556 NewTy = BestType; 17557 NewWidth = BestWidth; 17558 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17559 } 17560 17561 // Adjust the APSInt value. 17562 InitVal = InitVal.extOrTrunc(NewWidth); 17563 InitVal.setIsSigned(NewSign); 17564 ECD->setInitVal(InitVal); 17565 17566 // Adjust the Expr initializer and type. 17567 if (ECD->getInitExpr() && 17568 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17569 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17570 CK_IntegralCast, 17571 ECD->getInitExpr(), 17572 /*base paths*/ nullptr, 17573 VK_RValue)); 17574 if (getLangOpts().CPlusPlus) 17575 // C++ [dcl.enum]p4: Following the closing brace of an 17576 // enum-specifier, each enumerator has the type of its 17577 // enumeration. 17578 ECD->setType(EnumType); 17579 else 17580 ECD->setType(NewTy); 17581 } 17582 17583 Enum->completeDefinition(BestType, BestPromotionType, 17584 NumPositiveBits, NumNegativeBits); 17585 17586 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17587 17588 if (Enum->isClosedFlag()) { 17589 for (Decl *D : Elements) { 17590 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17591 if (!ECD) continue; // Already issued a diagnostic. 17592 17593 llvm::APSInt InitVal = ECD->getInitVal(); 17594 if (InitVal != 0 && !InitVal.isPowerOf2() && 17595 !IsValueInFlagEnum(Enum, InitVal, true)) 17596 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17597 << ECD << Enum; 17598 } 17599 } 17600 17601 // Now that the enum type is defined, ensure it's not been underaligned. 17602 if (Enum->hasAttrs()) 17603 CheckAlignasUnderalignment(Enum); 17604 } 17605 17606 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17607 SourceLocation StartLoc, 17608 SourceLocation EndLoc) { 17609 StringLiteral *AsmString = cast<StringLiteral>(expr); 17610 17611 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17612 AsmString, StartLoc, 17613 EndLoc); 17614 CurContext->addDecl(New); 17615 return New; 17616 } 17617 17618 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17619 IdentifierInfo* AliasName, 17620 SourceLocation PragmaLoc, 17621 SourceLocation NameLoc, 17622 SourceLocation AliasNameLoc) { 17623 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17624 LookupOrdinaryName); 17625 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17626 AttributeCommonInfo::AS_Pragma); 17627 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 17628 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 17629 17630 // If a declaration that: 17631 // 1) declares a function or a variable 17632 // 2) has external linkage 17633 // already exists, add a label attribute to it. 17634 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17635 if (isDeclExternC(PrevDecl)) 17636 PrevDecl->addAttr(Attr); 17637 else 17638 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17639 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17640 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17641 } else 17642 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17643 } 17644 17645 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17646 SourceLocation PragmaLoc, 17647 SourceLocation NameLoc) { 17648 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17649 17650 if (PrevDecl) { 17651 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17652 } else { 17653 (void)WeakUndeclaredIdentifiers.insert( 17654 std::pair<IdentifierInfo*,WeakInfo> 17655 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17656 } 17657 } 17658 17659 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17660 IdentifierInfo* AliasName, 17661 SourceLocation PragmaLoc, 17662 SourceLocation NameLoc, 17663 SourceLocation AliasNameLoc) { 17664 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17665 LookupOrdinaryName); 17666 WeakInfo W = WeakInfo(Name, NameLoc); 17667 17668 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17669 if (!PrevDecl->hasAttr<AliasAttr>()) 17670 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17671 DeclApplyPragmaWeak(TUScope, ND, W); 17672 } else { 17673 (void)WeakUndeclaredIdentifiers.insert( 17674 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17675 } 17676 } 17677 17678 Decl *Sema::getObjCDeclContext() const { 17679 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17680 } 17681 17682 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { 17683 // Templates are emitted when they're instantiated. 17684 if (FD->isDependentContext()) 17685 return FunctionEmissionStatus::TemplateDiscarded; 17686 17687 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 17688 if (LangOpts.OpenMPIsDevice) { 17689 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17690 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 17691 if (DevTy.hasValue()) { 17692 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 17693 OMPES = FunctionEmissionStatus::OMPDiscarded; 17694 else if (DeviceKnownEmittedFns.count(FD) > 0) 17695 OMPES = FunctionEmissionStatus::Emitted; 17696 } 17697 } else if (LangOpts.OpenMP) { 17698 // In OpenMP 4.5 all the functions are host functions. 17699 if (LangOpts.OpenMP <= 45) { 17700 OMPES = FunctionEmissionStatus::Emitted; 17701 } else { 17702 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17703 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 17704 // In OpenMP 5.0 or above, DevTy may be changed later by 17705 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 17706 // having no value does not imply host. The emission status will be 17707 // checked again at the end of compilation unit. 17708 if (DevTy.hasValue()) { 17709 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 17710 OMPES = FunctionEmissionStatus::OMPDiscarded; 17711 } else if (DeviceKnownEmittedFns.count(FD) > 0) { 17712 OMPES = FunctionEmissionStatus::Emitted; 17713 } 17714 } 17715 } 17716 } 17717 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 17718 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 17719 return OMPES; 17720 17721 if (LangOpts.CUDA) { 17722 // When compiling for device, host functions are never emitted. Similarly, 17723 // when compiling for host, device and global functions are never emitted. 17724 // (Technically, we do emit a host-side stub for global functions, but this 17725 // doesn't count for our purposes here.) 17726 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 17727 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 17728 return FunctionEmissionStatus::CUDADiscarded; 17729 if (!LangOpts.CUDAIsDevice && 17730 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 17731 return FunctionEmissionStatus::CUDADiscarded; 17732 17733 // Check whether this function is externally visible -- if so, it's 17734 // known-emitted. 17735 // 17736 // We have to check the GVA linkage of the function's *definition* -- if we 17737 // only have a declaration, we don't know whether or not the function will 17738 // be emitted, because (say) the definition could include "inline". 17739 FunctionDecl *Def = FD->getDefinition(); 17740 17741 if (Def && 17742 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 17743 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 17744 return FunctionEmissionStatus::Emitted; 17745 } 17746 17747 // Otherwise, the function is known-emitted if it's in our set of 17748 // known-emitted functions. 17749 return (DeviceKnownEmittedFns.count(FD) > 0) 17750 ? FunctionEmissionStatus::Emitted 17751 : FunctionEmissionStatus::Unknown; 17752 } 17753 17754 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 17755 // Host-side references to a __global__ function refer to the stub, so the 17756 // function itself is never emitted and therefore should not be marked. 17757 // If we have host fn calls kernel fn calls host+device, the HD function 17758 // does not get instantiated on the host. We model this by omitting at the 17759 // call to the kernel from the callgraph. This ensures that, when compiling 17760 // for host, only HD functions actually called from the host get marked as 17761 // known-emitted. 17762 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 17763 IdentifyCUDATarget(Callee) == CFT_Global; 17764 } 17765