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 #include <unordered_map> 51 52 using namespace clang; 53 using namespace sema; 54 55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 56 if (OwnedType) { 57 Decl *Group[2] = { OwnedType, Ptr }; 58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 59 } 60 61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 62 } 63 64 namespace { 65 66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 67 public: 68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 69 bool AllowTemplates = false, 70 bool AllowNonTemplates = true) 71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 73 WantExpressionKeywords = false; 74 WantCXXNamedCasts = false; 75 WantRemainingKeywords = false; 76 } 77 78 bool ValidateCandidate(const TypoCorrection &candidate) override { 79 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 80 if (!AllowInvalidDecl && ND->isInvalidDecl()) 81 return false; 82 83 if (getAsTypeTemplateDecl(ND)) 84 return AllowTemplates; 85 86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 87 if (!IsType) 88 return false; 89 90 if (AllowNonTemplates) 91 return true; 92 93 // An injected-class-name of a class template (specialization) is valid 94 // as a template or as a non-template. 95 if (AllowTemplates) { 96 auto *RD = dyn_cast<CXXRecordDecl>(ND); 97 if (!RD || !RD->isInjectedClassName()) 98 return false; 99 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 100 return RD->getDescribedClassTemplate() || 101 isa<ClassTemplateSpecializationDecl>(RD); 102 } 103 104 return false; 105 } 106 107 return !WantClassName && candidate.isKeyword(); 108 } 109 110 std::unique_ptr<CorrectionCandidateCallback> clone() override { 111 return std::make_unique<TypeNameValidatorCCC>(*this); 112 } 113 114 private: 115 bool AllowInvalidDecl; 116 bool WantClassName; 117 bool AllowTemplates; 118 bool AllowNonTemplates; 119 }; 120 121 } // end anonymous namespace 122 123 /// Determine whether the token kind starts a simple-type-specifier. 124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 125 switch (Kind) { 126 // FIXME: Take into account the current language when deciding whether a 127 // token kind is a valid type specifier 128 case tok::kw_short: 129 case tok::kw_long: 130 case tok::kw___int64: 131 case tok::kw___int128: 132 case tok::kw_signed: 133 case tok::kw_unsigned: 134 case tok::kw_void: 135 case tok::kw_char: 136 case tok::kw_int: 137 case tok::kw_half: 138 case tok::kw_float: 139 case tok::kw_double: 140 case tok::kw__Float16: 141 case tok::kw___float128: 142 case tok::kw_wchar_t: 143 case tok::kw_bool: 144 case tok::kw___underlying_type: 145 case tok::kw___auto_type: 146 return true; 147 148 case tok::annot_typename: 149 case tok::kw_char16_t: 150 case tok::kw_char32_t: 151 case tok::kw_typeof: 152 case tok::annot_decltype: 153 case tok::kw_decltype: 154 return getLangOpts().CPlusPlus; 155 156 case tok::kw_char8_t: 157 return getLangOpts().Char8; 158 159 default: 160 break; 161 } 162 163 return false; 164 } 165 166 namespace { 167 enum class UnqualifiedTypeNameLookupResult { 168 NotFound, 169 FoundNonType, 170 FoundType 171 }; 172 } // end anonymous namespace 173 174 /// Tries to perform unqualified lookup of the type decls in bases for 175 /// dependent class. 176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 177 /// type decl, \a FoundType if only type decls are found. 178 static UnqualifiedTypeNameLookupResult 179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 180 SourceLocation NameLoc, 181 const CXXRecordDecl *RD) { 182 if (!RD->hasDefinition()) 183 return UnqualifiedTypeNameLookupResult::NotFound; 184 // Look for type decls in base classes. 185 UnqualifiedTypeNameLookupResult FoundTypeDecl = 186 UnqualifiedTypeNameLookupResult::NotFound; 187 for (const auto &Base : RD->bases()) { 188 const CXXRecordDecl *BaseRD = nullptr; 189 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 190 BaseRD = BaseTT->getAsCXXRecordDecl(); 191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 192 // Look for type decls in dependent base classes that have known primary 193 // templates. 194 if (!TST || !TST->isDependentType()) 195 continue; 196 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 197 if (!TD) 198 continue; 199 if (auto *BasePrimaryTemplate = 200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = BasePrimaryTemplate; 203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 204 if (const ClassTemplatePartialSpecializationDecl *PS = 205 CTD->findPartialSpecialization(Base.getType())) 206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 207 BaseRD = PS; 208 } 209 } 210 } 211 if (BaseRD) { 212 for (NamedDecl *ND : BaseRD->lookup(&II)) { 213 if (!isa<TypeDecl>(ND)) 214 return UnqualifiedTypeNameLookupResult::FoundNonType; 215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 216 } 217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 219 case UnqualifiedTypeNameLookupResult::FoundNonType: 220 return UnqualifiedTypeNameLookupResult::FoundNonType; 221 case UnqualifiedTypeNameLookupResult::FoundType: 222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 223 break; 224 case UnqualifiedTypeNameLookupResult::NotFound: 225 break; 226 } 227 } 228 } 229 } 230 231 return FoundTypeDecl; 232 } 233 234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 235 const IdentifierInfo &II, 236 SourceLocation NameLoc) { 237 // Lookup in the parent class template context, if any. 238 const CXXRecordDecl *RD = nullptr; 239 UnqualifiedTypeNameLookupResult FoundTypeDecl = 240 UnqualifiedTypeNameLookupResult::NotFound; 241 for (DeclContext *DC = S.CurContext; 242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 243 DC = DC->getParent()) { 244 // Look for type decls in dependent base classes that have known primary 245 // templates. 246 RD = dyn_cast<CXXRecordDecl>(DC); 247 if (RD && RD->getDescribedClassTemplate()) 248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 249 } 250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 251 return nullptr; 252 253 // We found some types in dependent base classes. Recover as if the user 254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 255 // lookup during template instantiation. 256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 257 258 ASTContext &Context = S.Context; 259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 260 cast<Type>(Context.getRecordType(RD))); 261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 262 263 CXXScopeSpec SS; 264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 265 266 TypeLocBuilder Builder; 267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 268 DepTL.setNameLoc(NameLoc); 269 DepTL.setElaboratedKeywordLoc(SourceLocation()); 270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 272 } 273 274 /// If the identifier refers to a type name within this scope, 275 /// return the declaration of that type. 276 /// 277 /// This routine performs ordinary name lookup of the identifier II 278 /// within the given scope, with optional C++ scope specifier SS, to 279 /// determine whether the name refers to a type. If so, returns an 280 /// opaque pointer (actually a QualType) corresponding to that 281 /// type. Otherwise, returns NULL. 282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 283 Scope *S, CXXScopeSpec *SS, 284 bool isClassName, bool HasTrailingDot, 285 ParsedType ObjectTypePtr, 286 bool IsCtorOrDtorName, 287 bool WantNontrivialTypeSourceInfo, 288 bool IsClassTemplateDeductionContext, 289 IdentifierInfo **CorrectedII) { 290 // FIXME: Consider allowing this outside C++1z mode as an extension. 291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 293 !isClassName && !HasTrailingDot; 294 295 // Determine where we will perform name lookup. 296 DeclContext *LookupCtx = nullptr; 297 if (ObjectTypePtr) { 298 QualType ObjectType = ObjectTypePtr.get(); 299 if (ObjectType->isRecordType()) 300 LookupCtx = computeDeclContext(ObjectType); 301 } else if (SS && SS->isNotEmpty()) { 302 LookupCtx = computeDeclContext(*SS, false); 303 304 if (!LookupCtx) { 305 if (isDependentScopeSpecifier(*SS)) { 306 // C++ [temp.res]p3: 307 // A qualified-id that refers to a type and in which the 308 // nested-name-specifier depends on a template-parameter (14.6.2) 309 // shall be prefixed by the keyword typename to indicate that the 310 // qualified-id denotes a type, forming an 311 // elaborated-type-specifier (7.1.5.3). 312 // 313 // We therefore do not perform any name lookup if the result would 314 // refer to a member of an unknown specialization. 315 if (!isClassName && !IsCtorOrDtorName) 316 return nullptr; 317 318 // We know from the grammar that this name refers to a type, 319 // so build a dependent node to describe the type. 320 if (WantNontrivialTypeSourceInfo) 321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 322 323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 325 II, NameLoc); 326 return ParsedType::make(T); 327 } 328 329 return nullptr; 330 } 331 332 if (!LookupCtx->isDependentContext() && 333 RequireCompleteDeclContext(*SS, LookupCtx)) 334 return nullptr; 335 } 336 337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 338 // lookup for class-names. 339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 340 LookupOrdinaryName; 341 LookupResult Result(*this, &II, NameLoc, Kind); 342 if (LookupCtx) { 343 // Perform "qualified" name lookup into the declaration context we 344 // computed, which is either the type of the base of a member access 345 // expression or the declaration context associated with a prior 346 // nested-name-specifier. 347 LookupQualifiedName(Result, LookupCtx); 348 349 if (ObjectTypePtr && Result.empty()) { 350 // C++ [basic.lookup.classref]p3: 351 // If the unqualified-id is ~type-name, the type-name is looked up 352 // in the context of the entire postfix-expression. If the type T of 353 // the object expression is of a class type C, the type-name is also 354 // looked up in the scope of class C. At least one of the lookups shall 355 // find a name that refers to (possibly cv-qualified) T. 356 LookupName(Result, S); 357 } 358 } else { 359 // Perform unqualified name lookup. 360 LookupName(Result, S); 361 362 // For unqualified lookup in a class template in MSVC mode, look into 363 // dependent base classes where the primary class template is known. 364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 365 if (ParsedType TypeInBase = 366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 367 return TypeInBase; 368 } 369 } 370 371 NamedDecl *IIDecl = nullptr; 372 switch (Result.getResultKind()) { 373 case LookupResult::NotFound: 374 case LookupResult::NotFoundInCurrentInstantiation: 375 if (CorrectedII) { 376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 377 AllowDeducedTemplate); 378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 379 S, SS, CCC, CTK_ErrorRecovery); 380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 381 TemplateTy Template; 382 bool MemberOfUnknownSpecialization; 383 UnqualifiedId TemplateName; 384 TemplateName.setIdentifier(NewII, NameLoc); 385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 386 CXXScopeSpec NewSS, *NewSSPtr = SS; 387 if (SS && NNS) { 388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 389 NewSSPtr = &NewSS; 390 } 391 if (Correction && (NNS || NewII != &II) && 392 // Ignore a correction to a template type as the to-be-corrected 393 // identifier is not a template (typo correction for template names 394 // is handled elsewhere). 395 !(getLangOpts().CPlusPlus && NewSSPtr && 396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 397 Template, MemberOfUnknownSpecialization))) { 398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 399 isClassName, HasTrailingDot, ObjectTypePtr, 400 IsCtorOrDtorName, 401 WantNontrivialTypeSourceInfo, 402 IsClassTemplateDeductionContext); 403 if (Ty) { 404 diagnoseTypo(Correction, 405 PDiag(diag::err_unknown_type_or_class_name_suggest) 406 << Result.getLookupName() << isClassName); 407 if (SS && NNS) 408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 409 *CorrectedII = NewII; 410 return Ty; 411 } 412 } 413 } 414 // If typo correction failed or was not performed, fall through 415 LLVM_FALLTHROUGH; 416 case LookupResult::FoundOverloaded: 417 case LookupResult::FoundUnresolvedValue: 418 Result.suppressDiagnostics(); 419 return nullptr; 420 421 case LookupResult::Ambiguous: 422 // Recover from type-hiding ambiguities by hiding the type. We'll 423 // do the lookup again when looking for an object, and we can 424 // diagnose the error then. If we don't do this, then the error 425 // about hiding the type will be immediately followed by an error 426 // that only makes sense if the identifier was treated like a type. 427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 428 Result.suppressDiagnostics(); 429 return nullptr; 430 } 431 432 // Look to see if we have a type anywhere in the list of results. 433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 434 Res != ResEnd; ++Res) { 435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 437 if (!IIDecl || 438 (*Res)->getLocation().getRawEncoding() < 439 IIDecl->getLocation().getRawEncoding()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (isDependentScopeSpecifier(*SS)) { 752 unsigned DiagID = diag::err_typename_missing; 753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 754 DiagID = diag::ext_typename_missing; 755 756 Diag(SS->getRange().getBegin(), DiagID) 757 << SS->getScopeRep() << II->getName() 758 << SourceRange(SS->getRange().getBegin(), IILoc) 759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 760 SuggestedType = ActOnTypenameType(S, SourceLocation(), 761 *SS, *II, IILoc).get(); 762 } else { 763 assert(SS && SS->isInvalid() && 764 "Invalid scope specifier has already been diagnosed"); 765 } 766 } 767 768 /// Determine whether the given result set contains either a type name 769 /// or 770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 772 NextToken.is(tok::less); 773 774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 776 return true; 777 778 if (CheckTemplate && isa<TemplateDecl>(*I)) 779 return true; 780 } 781 782 return false; 783 } 784 785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 786 Scope *S, CXXScopeSpec &SS, 787 IdentifierInfo *&Name, 788 SourceLocation NameLoc) { 789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 790 SemaRef.LookupParsedName(R, S, &SS); 791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 792 StringRef FixItTagName; 793 switch (Tag->getTagKind()) { 794 case TTK_Class: 795 FixItTagName = "class "; 796 break; 797 798 case TTK_Enum: 799 FixItTagName = "enum "; 800 break; 801 802 case TTK_Struct: 803 FixItTagName = "struct "; 804 break; 805 806 case TTK_Interface: 807 FixItTagName = "__interface "; 808 break; 809 810 case TTK_Union: 811 FixItTagName = "union "; 812 break; 813 } 814 815 StringRef TagName = FixItTagName.drop_back(); 816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 818 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 819 820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 821 I != IEnd; ++I) 822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 823 << Name << TagName; 824 825 // Replace lookup results with just the tag decl. 826 Result.clear(Sema::LookupTagName); 827 SemaRef.LookupParsedName(Result, S, &SS); 828 return true; 829 } 830 831 return false; 832 } 833 834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 836 QualType T, SourceLocation NameLoc) { 837 ASTContext &Context = S.Context; 838 839 TypeLocBuilder Builder; 840 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 841 842 T = S.getElaboratedType(ETK_None, SS, T); 843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 844 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 847 } 848 849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 850 IdentifierInfo *&Name, 851 SourceLocation NameLoc, 852 const Token &NextToken, 853 CorrectionCandidateCallback *CCC) { 854 DeclarationNameInfo NameInfo(Name, NameLoc); 855 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 856 857 assert(NextToken.isNot(tok::coloncolon) && 858 "parse nested name specifiers before calling ClassifyName"); 859 if (getLangOpts().CPlusPlus && SS.isSet() && 860 isCurrentClassName(*Name, S, &SS)) { 861 // Per [class.qual]p2, this names the constructors of SS, not the 862 // injected-class-name. We don't have a classification for that. 863 // There's not much point caching this result, since the parser 864 // will reject it later. 865 return NameClassification::Unknown(); 866 } 867 868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 869 LookupParsedName(Result, S, &SS, !CurMethod); 870 871 if (SS.isInvalid()) 872 return NameClassification::Error(); 873 874 // For unqualified lookup in a class template in MSVC mode, look into 875 // dependent base classes where the primary class template is known. 876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 877 if (ParsedType TypeInBase = 878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 879 return TypeInBase; 880 } 881 882 // Perform lookup for Objective-C instance variables (including automatically 883 // synthesized instance variables), if we're in an Objective-C method. 884 // FIXME: This lookup really, really needs to be folded in to the normal 885 // unqualified lookup mechanism. 886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 888 if (Ivar.isInvalid()) 889 return NameClassification::Error(); 890 if (Ivar.isUsable()) 891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 892 893 // We defer builtin creation until after ivar lookup inside ObjC methods. 894 if (Result.empty()) 895 LookupBuiltin(Result); 896 } 897 898 bool SecondTry = false; 899 bool IsFilteredTemplateName = false; 900 901 Corrected: 902 switch (Result.getResultKind()) { 903 case LookupResult::NotFound: 904 // If an unqualified-id is followed by a '(', then we have a function 905 // call. 906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 907 // In C++, this is an ADL-only call. 908 // FIXME: Reference? 909 if (getLangOpts().CPlusPlus) 910 return NameClassification::UndeclaredNonType(); 911 912 // C90 6.3.2.2: 913 // If the expression that precedes the parenthesized argument list in a 914 // function call consists solely of an identifier, and if no 915 // declaration is visible for this identifier, the identifier is 916 // implicitly declared exactly as if, in the innermost block containing 917 // the function call, the declaration 918 // 919 // extern int identifier (); 920 // 921 // appeared. 922 // 923 // We also allow this in C99 as an extension. 924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 925 return NameClassification::NonType(D); 926 } 927 928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { 929 // In C++20 onwards, this could be an ADL-only call to a function 930 // template, and we're required to assume that this is a template name. 931 // 932 // FIXME: Find a way to still do typo correction in this case. 933 TemplateName Template = 934 Context.getAssumedTemplateName(NameInfo.getName()); 935 return NameClassification::UndeclaredTemplate(Template); 936 } 937 938 // In C, we first see whether there is a tag type by the same name, in 939 // which case it's likely that the user just forgot to write "enum", 940 // "struct", or "union". 941 if (!getLangOpts().CPlusPlus && !SecondTry && 942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 943 break; 944 } 945 946 // Perform typo correction to determine if there is another name that is 947 // close to this name. 948 if (!SecondTry && CCC) { 949 SecondTry = true; 950 if (TypoCorrection Corrected = 951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 952 &SS, *CCC, CTK_ErrorRecovery)) { 953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 954 unsigned QualifiedDiag = diag::err_no_member_suggest; 955 956 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 960 UnqualifiedDiag = diag::err_no_template_suggest; 961 QualifiedDiag = diag::err_no_member_template_suggest; 962 } else if (UnderlyingFirstDecl && 963 (isa<TypeDecl>(UnderlyingFirstDecl) || 964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 966 UnqualifiedDiag = diag::err_unknown_typename_suggest; 967 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 968 } 969 970 if (SS.isEmpty()) { 971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 972 } else {// FIXME: is this even reachable? Test it. 973 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 975 Name->getName().equals(CorrectedStr); 976 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 977 << Name << computeDeclContext(SS, false) 978 << DroppedSpecifier << SS.getRange()); 979 } 980 981 // Update the name, so that the caller has the new name. 982 Name = Corrected.getCorrectionAsIdentifierInfo(); 983 984 // Typo correction corrected to a keyword. 985 if (Corrected.isKeyword()) 986 return Name; 987 988 // Also update the LookupResult... 989 // FIXME: This should probably go away at some point 990 Result.clear(); 991 Result.setLookupName(Corrected.getCorrection()); 992 if (FirstDecl) 993 Result.addDecl(FirstDecl); 994 995 // If we found an Objective-C instance variable, let 996 // LookupInObjCMethod build the appropriate expression to 997 // reference the ivar. 998 // FIXME: This is a gross hack. 999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1000 DeclResult R = 1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1002 if (R.isInvalid()) 1003 return NameClassification::Error(); 1004 if (R.isUsable()) 1005 return NameClassification::NonType(Ivar); 1006 } 1007 1008 goto Corrected; 1009 } 1010 } 1011 1012 // We failed to correct; just fall through and let the parser deal with it. 1013 Result.suppressDiagnostics(); 1014 return NameClassification::Unknown(); 1015 1016 case LookupResult::NotFoundInCurrentInstantiation: { 1017 // We performed name lookup into the current instantiation, and there were 1018 // dependent bases, so we treat this result the same way as any other 1019 // dependent nested-name-specifier. 1020 1021 // C++ [temp.res]p2: 1022 // A name used in a template declaration or definition and that is 1023 // dependent on a template-parameter is assumed not to name a type 1024 // unless the applicable name lookup finds a type name or the name is 1025 // qualified by the keyword typename. 1026 // 1027 // FIXME: If the next token is '<', we might want to ask the parser to 1028 // perform some heroics to see if we actually have a 1029 // template-argument-list, which would indicate a missing 'template' 1030 // keyword here. 1031 return NameClassification::DependentNonType(); 1032 } 1033 1034 case LookupResult::Found: 1035 case LookupResult::FoundOverloaded: 1036 case LookupResult::FoundUnresolvedValue: 1037 break; 1038 1039 case LookupResult::Ambiguous: 1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1042 /*AllowDependent=*/false)) { 1043 // C++ [temp.local]p3: 1044 // A lookup that finds an injected-class-name (10.2) can result in an 1045 // ambiguity in certain cases (for example, if it is found in more than 1046 // one base class). If all of the injected-class-names that are found 1047 // refer to specializations of the same class template, and if the name 1048 // is followed by a template-argument-list, the reference refers to the 1049 // class template itself and not a specialization thereof, and is not 1050 // ambiguous. 1051 // 1052 // This filtering can make an ambiguous result into an unambiguous one, 1053 // so try again after filtering out template names. 1054 FilterAcceptableTemplateNames(Result); 1055 if (!Result.isAmbiguous()) { 1056 IsFilteredTemplateName = true; 1057 break; 1058 } 1059 } 1060 1061 // Diagnose the ambiguity and return an error. 1062 return NameClassification::Error(); 1063 } 1064 1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1066 (IsFilteredTemplateName || 1067 hasAnyAcceptableTemplateNames( 1068 Result, /*AllowFunctionTemplates=*/true, 1069 /*AllowDependent=*/false, 1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1071 getLangOpts().CPlusPlus2a))) { 1072 // C++ [temp.names]p3: 1073 // After name lookup (3.4) finds that a name is a template-name or that 1074 // an operator-function-id or a literal- operator-id refers to a set of 1075 // overloaded functions any member of which is a function template if 1076 // this is followed by a <, the < is always taken as the delimiter of a 1077 // template-argument-list and never as the less-than operator. 1078 // C++2a [temp.names]p2: 1079 // A name is also considered to refer to a template if it is an 1080 // unqualified-id followed by a < and name lookup finds either one 1081 // or more functions or finds nothing. 1082 if (!IsFilteredTemplateName) 1083 FilterAcceptableTemplateNames(Result); 1084 1085 bool IsFunctionTemplate; 1086 bool IsVarTemplate; 1087 TemplateName Template; 1088 if (Result.end() - Result.begin() > 1) { 1089 IsFunctionTemplate = true; 1090 Template = Context.getOverloadedTemplateName(Result.begin(), 1091 Result.end()); 1092 } else if (!Result.empty()) { 1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1094 *Result.begin(), /*AllowFunctionTemplates=*/true, 1095 /*AllowDependent=*/false)); 1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1097 IsVarTemplate = isa<VarTemplateDecl>(TD); 1098 1099 if (SS.isNotEmpty()) 1100 Template = 1101 Context.getQualifiedTemplateName(SS.getScopeRep(), 1102 /*TemplateKeyword=*/false, TD); 1103 else 1104 Template = TemplateName(TD); 1105 } else { 1106 // All results were non-template functions. This is a function template 1107 // name. 1108 IsFunctionTemplate = true; 1109 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1110 } 1111 1112 if (IsFunctionTemplate) { 1113 // Function templates always go through overload resolution, at which 1114 // point we'll perform the various checks (e.g., accessibility) we need 1115 // to based on which function we selected. 1116 Result.suppressDiagnostics(); 1117 1118 return NameClassification::FunctionTemplate(Template); 1119 } 1120 1121 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1122 : NameClassification::TypeTemplate(Template); 1123 } 1124 1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1127 DiagnoseUseOfDecl(Type, NameLoc); 1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1129 QualType T = Context.getTypeDeclType(Type); 1130 if (SS.isNotEmpty()) 1131 return buildNestedType(*this, SS, T, NameLoc); 1132 return ParsedType::make(T); 1133 } 1134 1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1136 if (!Class) { 1137 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1138 if (ObjCCompatibleAliasDecl *Alias = 1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1140 Class = Alias->getClassInterface(); 1141 } 1142 1143 if (Class) { 1144 DiagnoseUseOfDecl(Class, NameLoc); 1145 1146 if (NextToken.is(tok::period)) { 1147 // Interface. <something> is parsed as a property reference expression. 1148 // Just return "unknown" as a fall-through for now. 1149 Result.suppressDiagnostics(); 1150 return NameClassification::Unknown(); 1151 } 1152 1153 QualType T = Context.getObjCInterfaceType(Class); 1154 return ParsedType::make(T); 1155 } 1156 1157 if (isa<ConceptDecl>(FirstDecl)) 1158 return NameClassification::Concept( 1159 TemplateName(cast<TemplateDecl>(FirstDecl))); 1160 1161 // We can have a type template here if we're classifying a template argument. 1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1163 !isa<VarTemplateDecl>(FirstDecl)) 1164 return NameClassification::TypeTemplate( 1165 TemplateName(cast<TemplateDecl>(FirstDecl))); 1166 1167 // Check for a tag type hidden by a non-type decl in a few cases where it 1168 // seems likely a type is wanted instead of the non-type that was found. 1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1170 if ((NextToken.is(tok::identifier) || 1171 (NextIsOp && 1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1175 DiagnoseUseOfDecl(Type, NameLoc); 1176 QualType T = Context.getTypeDeclType(Type); 1177 if (SS.isNotEmpty()) 1178 return buildNestedType(*this, SS, T, NameLoc); 1179 return ParsedType::make(T); 1180 } 1181 1182 // FIXME: This is context-dependent. We need to defer building the member 1183 // expression until the classification is consumed. 1184 if (FirstDecl->isCXXClassMember()) 1185 return NameClassification::ContextIndependentExpr( 1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1187 S)); 1188 1189 // If we already know which single declaration is referenced, just annotate 1190 // that declaration directly. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1196 // context in which we performed classification, so it's safe to do now. 1197 return NameClassification::ContextIndependentExpr( 1198 BuildDeclarationNameExpr(SS, Result, ADL)); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 Sema::TemplateNameKindForDiagnostics 1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1240 auto *TD = Name.getAsTemplateDecl(); 1241 if (!TD) 1242 return TemplateNameKindForDiagnostics::DependentTemplate; 1243 if (isa<ClassTemplateDecl>(TD)) 1244 return TemplateNameKindForDiagnostics::ClassTemplate; 1245 if (isa<FunctionTemplateDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::FunctionTemplate; 1247 if (isa<VarTemplateDecl>(TD)) 1248 return TemplateNameKindForDiagnostics::VarTemplate; 1249 if (isa<TypeAliasTemplateDecl>(TD)) 1250 return TemplateNameKindForDiagnostics::AliasTemplate; 1251 if (isa<TemplateTemplateParmDecl>(TD)) 1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1253 if (isa<ConceptDecl>(TD)) 1254 return TemplateNameKindForDiagnostics::Concept; 1255 return TemplateNameKindForDiagnostics::DependentTemplate; 1256 } 1257 1258 // Determines the context to return to after temporarily entering a 1259 // context. This depends in an unnecessarily complicated way on the 1260 // exact ordering of callbacks from the parser. 1261 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1262 1263 // Functions defined inline within classes aren't parsed until we've 1264 // finished parsing the top-level class, so the top-level class is 1265 // the context we'll need to return to. 1266 // A Lambda call operator whose parent is a class must not be treated 1267 // as an inline member function. A Lambda can be used legally 1268 // either as an in-class member initializer or a default argument. These 1269 // are parsed once the class has been marked complete and so the containing 1270 // context would be the nested class (when the lambda is defined in one); 1271 // If the class is not complete, then the lambda is being used in an 1272 // ill-formed fashion (such as to specify the width of a bit-field, or 1273 // in an array-bound) - in which case we still want to return the 1274 // lexically containing DC (which could be a nested class). 1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1276 DC = DC->getLexicalParent(); 1277 1278 // A function not defined within a class will always return to its 1279 // lexical context. 1280 if (!isa<CXXRecordDecl>(DC)) 1281 return DC; 1282 1283 // A C++ inline method/friend is parsed *after* the topmost class 1284 // it was declared in is fully parsed ("complete"); the topmost 1285 // class is the context we need to return to. 1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1287 DC = RD; 1288 1289 // Return the declaration context of the topmost class the inline method is 1290 // declared in. 1291 return DC; 1292 } 1293 1294 return DC->getLexicalParent(); 1295 } 1296 1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1298 assert(getContainingDC(DC) == CurContext && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = DC; 1301 S->setEntity(DC); 1302 } 1303 1304 void Sema::PopDeclContext() { 1305 assert(CurContext && "DeclContext imbalance!"); 1306 1307 CurContext = getContainingDC(CurContext); 1308 assert(CurContext && "Popped translation unit!"); 1309 } 1310 1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1312 Decl *D) { 1313 // Unlike PushDeclContext, the context to which we return is not necessarily 1314 // the containing DC of TD, because the new context will be some pre-existing 1315 // TagDecl definition instead of a fresh one. 1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1317 CurContext = cast<TagDecl>(D)->getDefinition(); 1318 assert(CurContext && "skipping definition of undefined tag"); 1319 // Start lookups from the parent of the current context; we don't want to look 1320 // into the pre-existing complete definition. 1321 S->setEntity(CurContext->getLookupParent()); 1322 return Result; 1323 } 1324 1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1326 CurContext = static_cast<decltype(CurContext)>(Context); 1327 } 1328 1329 /// EnterDeclaratorContext - Used when we must lookup names in the context 1330 /// of a declarator's nested name specifier. 1331 /// 1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1333 // C++0x [basic.lookup.unqual]p13: 1334 // A name used in the definition of a static data member of class 1335 // X (after the qualified-id of the static member) is looked up as 1336 // if the name was used in a member function of X. 1337 // C++0x [basic.lookup.unqual]p14: 1338 // If a variable member of a namespace is defined outside of the 1339 // scope of its namespace then any name used in the definition of 1340 // the variable member (after the declarator-id) is looked up as 1341 // if the definition of the variable member occurred in its 1342 // namespace. 1343 // Both of these imply that we should push a scope whose context 1344 // is the semantic context of the declaration. We can't use 1345 // PushDeclContext here because that context is not necessarily 1346 // lexically contained in the current context. Fortunately, 1347 // the containing scope should have the appropriate information. 1348 1349 assert(!S->getEntity() && "scope already has entity"); 1350 1351 #ifndef NDEBUG 1352 Scope *Ancestor = S->getParent(); 1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1355 #endif 1356 1357 CurContext = DC; 1358 S->setEntity(DC); 1359 } 1360 1361 void Sema::ExitDeclaratorContext(Scope *S) { 1362 assert(S->getEntity() == CurContext && "Context imbalance!"); 1363 1364 // Switch back to the lexical context. The safety of this is 1365 // enforced by an assert in EnterDeclaratorContext. 1366 Scope *Ancestor = S->getParent(); 1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1368 CurContext = Ancestor->getEntity(); 1369 1370 // We don't need to do anything with the scope, which is going to 1371 // disappear. 1372 } 1373 1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1375 // We assume that the caller has already called 1376 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1377 FunctionDecl *FD = D->getAsFunction(); 1378 if (!FD) 1379 return; 1380 1381 // Same implementation as PushDeclContext, but enters the context 1382 // from the lexical parent, rather than the top-level class. 1383 assert(CurContext == FD->getLexicalParent() && 1384 "The next DeclContext should be lexically contained in the current one."); 1385 CurContext = FD; 1386 S->setEntity(CurContext); 1387 1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1389 ParmVarDecl *Param = FD->getParamDecl(P); 1390 // If the parameter has an identifier, then add it to the scope 1391 if (Param->getIdentifier()) { 1392 S->AddDecl(Param); 1393 IdResolver.AddDecl(Param); 1394 } 1395 } 1396 } 1397 1398 void Sema::ActOnExitFunctionContext() { 1399 // Same implementation as PopDeclContext, but returns to the lexical parent, 1400 // rather than the top-level class. 1401 assert(CurContext && "DeclContext imbalance!"); 1402 CurContext = CurContext->getLexicalParent(); 1403 assert(CurContext && "Popped translation unit!"); 1404 } 1405 1406 /// Determine whether we allow overloading of the function 1407 /// PrevDecl with another declaration. 1408 /// 1409 /// This routine determines whether overloading is possible, not 1410 /// whether some new function is actually an overload. It will return 1411 /// true in C++ (where we can always provide overloads) or, as an 1412 /// extension, in C when the previous function is already an 1413 /// overloaded function declaration or has the "overloadable" 1414 /// attribute. 1415 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1416 ASTContext &Context, 1417 const FunctionDecl *New) { 1418 if (Context.getLangOpts().CPlusPlus) 1419 return true; 1420 1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1422 return true; 1423 1424 return Previous.getResultKind() == LookupResult::Found && 1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1426 New->hasAttr<OverloadableAttr>()); 1427 } 1428 1429 /// Add this decl to the scope shadowed decl chains. 1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1431 // Move up the scope chain until we find the nearest enclosing 1432 // non-transparent context. The declaration will be introduced into this 1433 // scope. 1434 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1435 S = S->getParent(); 1436 1437 // Add scoped declarations into their context, so that they can be 1438 // found later. Declarations without a context won't be inserted 1439 // into any context. 1440 if (AddToContext) 1441 CurContext->addDecl(D); 1442 1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1444 // are function-local declarations. 1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1446 !D->getDeclContext()->getRedeclContext()->Equals( 1447 D->getLexicalDeclContext()->getRedeclContext()) && 1448 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1449 return; 1450 1451 // Template instantiations should also not be pushed into scope. 1452 if (isa<FunctionDecl>(D) && 1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1454 return; 1455 1456 // If this replaces anything in the current scope, 1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1458 IEnd = IdResolver.end(); 1459 for (; I != IEnd; ++I) { 1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1461 S->RemoveDecl(*I); 1462 IdResolver.RemoveDecl(*I); 1463 1464 // Should only need to replace one decl. 1465 break; 1466 } 1467 } 1468 1469 S->AddDecl(D); 1470 1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1472 // Implicitly-generated labels may end up getting generated in an order that 1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1474 // the label at the appropriate place in the identifier chain. 1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1477 if (IDC == CurContext) { 1478 if (!S->isDeclScope(*I)) 1479 continue; 1480 } else if (IDC->Encloses(CurContext)) 1481 break; 1482 } 1483 1484 IdResolver.InsertDeclAfter(I, D); 1485 } else { 1486 IdResolver.AddDecl(D); 1487 } 1488 } 1489 1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1491 bool AllowInlineNamespace) { 1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1493 } 1494 1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1496 DeclContext *TargetDC = DC->getPrimaryContext(); 1497 do { 1498 if (DeclContext *ScopeDC = S->getEntity()) 1499 if (ScopeDC->getPrimaryContext() == TargetDC) 1500 return S; 1501 } while ((S = S->getParent())); 1502 1503 return nullptr; 1504 } 1505 1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1507 DeclContext*, 1508 ASTContext&); 1509 1510 /// Filters out lookup results that don't fall within the given scope 1511 /// as determined by isDeclInScope. 1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1513 bool ConsiderLinkage, 1514 bool AllowInlineNamespace) { 1515 LookupResult::Filter F = R.makeFilter(); 1516 while (F.hasNext()) { 1517 NamedDecl *D = F.next(); 1518 1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1520 continue; 1521 1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1523 continue; 1524 1525 F.erase(); 1526 } 1527 1528 F.done(); 1529 } 1530 1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1532 /// have compatible owning modules. 1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1534 // FIXME: The Modules TS is not clear about how friend declarations are 1535 // to be treated. It's not meaningful to have different owning modules for 1536 // linkage in redeclarations of the same entity, so for now allow the 1537 // redeclaration and change the owning modules to match. 1538 if (New->getFriendObjectKind() && 1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1540 New->setLocalOwningModule(Old->getOwningModule()); 1541 makeMergedDefinitionVisible(New); 1542 return false; 1543 } 1544 1545 Module *NewM = New->getOwningModule(); 1546 Module *OldM = Old->getOwningModule(); 1547 1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1549 NewM = NewM->Parent; 1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1551 OldM = OldM->Parent; 1552 1553 if (NewM == OldM) 1554 return false; 1555 1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1558 if (NewIsModuleInterface || OldIsModuleInterface) { 1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1560 // if a declaration of D [...] appears in the purview of a module, all 1561 // other such declarations shall appear in the purview of the same module 1562 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1563 << New 1564 << NewIsModuleInterface 1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1566 << OldIsModuleInterface 1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1568 Diag(Old->getLocation(), diag::note_previous_declaration); 1569 New->setInvalidDecl(); 1570 return true; 1571 } 1572 1573 return false; 1574 } 1575 1576 static bool isUsingDecl(NamedDecl *D) { 1577 return isa<UsingShadowDecl>(D) || 1578 isa<UnresolvedUsingTypenameDecl>(D) || 1579 isa<UnresolvedUsingValueDecl>(D); 1580 } 1581 1582 /// Removes using shadow declarations from the lookup results. 1583 static void RemoveUsingDecls(LookupResult &R) { 1584 LookupResult::Filter F = R.makeFilter(); 1585 while (F.hasNext()) 1586 if (isUsingDecl(F.next())) 1587 F.erase(); 1588 1589 F.done(); 1590 } 1591 1592 /// Check for this common pattern: 1593 /// @code 1594 /// class S { 1595 /// S(const S&); // DO NOT IMPLEMENT 1596 /// void operator=(const S&); // DO NOT IMPLEMENT 1597 /// }; 1598 /// @endcode 1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1600 // FIXME: Should check for private access too but access is set after we get 1601 // the decl here. 1602 if (D->doesThisDeclarationHaveABody()) 1603 return false; 1604 1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1606 return CD->isCopyConstructor(); 1607 return D->isCopyAssignmentOperator(); 1608 } 1609 1610 // We need this to handle 1611 // 1612 // typedef struct { 1613 // void *foo() { return 0; } 1614 // } A; 1615 // 1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1617 // for example. If 'A', foo will have external linkage. If we have '*A', 1618 // foo will have no linkage. Since we can't know until we get to the end 1619 // of the typedef, this function finds out if D might have non-external linkage. 1620 // Callers should verify at the end of the TU if it D has external linkage or 1621 // not. 1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1623 const DeclContext *DC = D->getDeclContext(); 1624 while (!DC->isTranslationUnit()) { 1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1626 if (!RD->hasNameForLinkage()) 1627 return true; 1628 } 1629 DC = DC->getParent(); 1630 } 1631 1632 return !D->isExternallyVisible(); 1633 } 1634 1635 // FIXME: This needs to be refactored; some other isInMainFile users want 1636 // these semantics. 1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1638 if (S.TUKind != TU_Complete) 1639 return false; 1640 return S.SourceMgr.isInMainFile(Loc); 1641 } 1642 1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1644 assert(D); 1645 1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1647 return false; 1648 1649 // Ignore all entities declared within templates, and out-of-line definitions 1650 // of members of class templates. 1651 if (D->getDeclContext()->isDependentContext() || 1652 D->getLexicalDeclContext()->isDependentContext()) 1653 return false; 1654 1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1657 return false; 1658 // A non-out-of-line declaration of a member specialization was implicitly 1659 // instantiated; it's the out-of-line declaration that we're interested in. 1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1662 return false; 1663 1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1666 return false; 1667 } else { 1668 // 'static inline' functions are defined in headers; don't warn. 1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1670 return false; 1671 } 1672 1673 if (FD->doesThisDeclarationHaveABody() && 1674 Context.DeclMustBeEmitted(FD)) 1675 return false; 1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1677 // Constants and utility variables are defined in headers with internal 1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1679 // like "inline".) 1680 if (!isMainFileLoc(*this, VD->getLocation())) 1681 return false; 1682 1683 if (Context.DeclMustBeEmitted(VD)) 1684 return false; 1685 1686 if (VD->isStaticDataMember() && 1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 if (VD->isStaticDataMember() && 1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1692 return false; 1693 1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1695 return false; 1696 } else { 1697 return false; 1698 } 1699 1700 // Only warn for unused decls internal to the translation unit. 1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1702 // for inline functions defined in the main source file, for instance. 1703 return mightHaveNonExternalLinkage(D); 1704 } 1705 1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1707 if (!D) 1708 return; 1709 1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1711 const FunctionDecl *First = FD->getFirstDecl(); 1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1713 return; // First should already be in the vector. 1714 } 1715 1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1717 const VarDecl *First = VD->getFirstDecl(); 1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1719 return; // First should already be in the vector. 1720 } 1721 1722 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1723 UnusedFileScopedDecls.push_back(D); 1724 } 1725 1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1727 if (D->isInvalidDecl()) 1728 return false; 1729 1730 bool Referenced = false; 1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1732 // For a decomposition declaration, warn if none of the bindings are 1733 // referenced, instead of if the variable itself is referenced (which 1734 // it is, by the bindings' expressions). 1735 for (auto *BD : DD->bindings()) { 1736 if (BD->isReferenced()) { 1737 Referenced = true; 1738 break; 1739 } 1740 } 1741 } else if (!D->getDeclName()) { 1742 return false; 1743 } else if (D->isReferenced() || D->isUsed()) { 1744 Referenced = true; 1745 } 1746 1747 if (Referenced || D->hasAttr<UnusedAttr>() || 1748 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1749 return false; 1750 1751 if (isa<LabelDecl>(D)) 1752 return true; 1753 1754 // Except for labels, we only care about unused decls that are local to 1755 // functions. 1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1758 // For dependent types, the diagnostic is deferred. 1759 WithinFunction = 1760 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1761 if (!WithinFunction) 1762 return false; 1763 1764 if (isa<TypedefNameDecl>(D)) 1765 return true; 1766 1767 // White-list anything that isn't a local variable. 1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1769 return false; 1770 1771 // Types of valid local variables should be complete, so this should succeed. 1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1773 1774 // White-list anything with an __attribute__((unused)) type. 1775 const auto *Ty = VD->getType().getTypePtr(); 1776 1777 // Only look at the outermost level of typedef. 1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1779 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1780 return false; 1781 } 1782 1783 // If we failed to complete the type for some reason, or if the type is 1784 // dependent, don't diagnose the variable. 1785 if (Ty->isIncompleteType() || Ty->isDependentType()) 1786 return false; 1787 1788 // Look at the element type to ensure that the warning behaviour is 1789 // consistent for both scalars and arrays. 1790 Ty = Ty->getBaseElementTypeUnsafe(); 1791 1792 if (const TagType *TT = Ty->getAs<TagType>()) { 1793 const TagDecl *Tag = TT->getDecl(); 1794 if (Tag->hasAttr<UnusedAttr>()) 1795 return false; 1796 1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1799 return false; 1800 1801 if (const Expr *Init = VD->getInit()) { 1802 if (const ExprWithCleanups *Cleanups = 1803 dyn_cast<ExprWithCleanups>(Init)) 1804 Init = Cleanups->getSubExpr(); 1805 const CXXConstructExpr *Construct = 1806 dyn_cast<CXXConstructExpr>(Init); 1807 if (Construct && !Construct->isElidable()) { 1808 CXXConstructorDecl *CD = Construct->getConstructor(); 1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1811 return false; 1812 } 1813 1814 // Suppress the warning if we don't know how this is constructed, and 1815 // it could possibly be non-trivial constructor. 1816 if (Init->isTypeDependent()) 1817 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1818 if (!Ctor->isTrivial()) 1819 return false; 1820 } 1821 } 1822 } 1823 1824 // TODO: __attribute__((unused)) templates? 1825 } 1826 1827 return true; 1828 } 1829 1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1831 FixItHint &Hint) { 1832 if (isa<LabelDecl>(D)) { 1833 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1835 true); 1836 if (AfterColon.isInvalid()) 1837 return; 1838 Hint = FixItHint::CreateRemoval( 1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1840 } 1841 } 1842 1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1844 if (D->getTypeForDecl()->isDependentType()) 1845 return; 1846 1847 for (auto *TmpD : D->decls()) { 1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1849 DiagnoseUnusedDecl(T); 1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1851 DiagnoseUnusedNestedTypedefs(R); 1852 } 1853 } 1854 1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1856 /// unless they are marked attr(unused). 1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1858 if (!ShouldDiagnoseUnusedDecl(D)) 1859 return; 1860 1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1862 // typedefs can be referenced later on, so the diagnostics are emitted 1863 // at end-of-translation-unit. 1864 UnusedLocalTypedefNameCandidates.insert(TD); 1865 return; 1866 } 1867 1868 FixItHint Hint; 1869 GenerateFixForUnusedDecl(D, Context, Hint); 1870 1871 unsigned DiagID; 1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1873 DiagID = diag::warn_unused_exception_param; 1874 else if (isa<LabelDecl>(D)) 1875 DiagID = diag::warn_unused_label; 1876 else 1877 DiagID = diag::warn_unused_variable; 1878 1879 Diag(D->getLocation(), DiagID) << D << Hint; 1880 } 1881 1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1883 // Verify that we have no forward references left. If so, there was a goto 1884 // or address of a label taken, but no definition of it. Label fwd 1885 // definitions are indicated with a null substmt which is also not a resolved 1886 // MS inline assembly label name. 1887 bool Diagnose = false; 1888 if (L->isMSAsmLabel()) 1889 Diagnose = !L->isResolvedMSAsmLabel(); 1890 else 1891 Diagnose = L->getStmt() == nullptr; 1892 if (Diagnose) 1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1894 } 1895 1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1897 S->mergeNRVOIntoParent(); 1898 1899 if (S->decl_empty()) return; 1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1901 "Scope shouldn't contain decls!"); 1902 1903 for (auto *TmpD : S->decls()) { 1904 assert(TmpD && "This decl didn't get pushed??"); 1905 1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1907 NamedDecl *D = cast<NamedDecl>(TmpD); 1908 1909 // Diagnose unused variables in this scope. 1910 if (!S->hasUnrecoverableErrorOccurred()) { 1911 DiagnoseUnusedDecl(D); 1912 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1913 DiagnoseUnusedNestedTypedefs(RD); 1914 } 1915 1916 if (!D->getDeclName()) continue; 1917 1918 // If this was a forward reference to a label, verify it was defined. 1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1920 CheckPoppedLabel(LD, *this); 1921 1922 // Remove this name from our lexical scope, and warn on it if we haven't 1923 // already. 1924 IdResolver.RemoveDecl(D); 1925 auto ShadowI = ShadowingDecls.find(D); 1926 if (ShadowI != ShadowingDecls.end()) { 1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1929 << D << FD << FD->getParent(); 1930 Diag(FD->getLocation(), diag::note_previous_declaration); 1931 } 1932 ShadowingDecls.erase(ShadowI); 1933 } 1934 } 1935 } 1936 1937 /// Look for an Objective-C class in the translation unit. 1938 /// 1939 /// \param Id The name of the Objective-C class we're looking for. If 1940 /// typo-correction fixes this name, the Id will be updated 1941 /// to the fixed name. 1942 /// 1943 /// \param IdLoc The location of the name in the translation unit. 1944 /// 1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1946 /// if there is no class with the given name. 1947 /// 1948 /// \returns The declaration of the named Objective-C class, or NULL if the 1949 /// class could not be found. 1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1951 SourceLocation IdLoc, 1952 bool DoTypoCorrection) { 1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1954 // creation from this context. 1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1956 1957 if (!IDecl && DoTypoCorrection) { 1958 // Perform typo correction at the given location, but only if we 1959 // find an Objective-C class name. 1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1961 if (TypoCorrection C = 1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1966 Id = IDecl->getIdentifier(); 1967 } 1968 } 1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1970 // This routine must always return a class definition, if any. 1971 if (Def && Def->getDefinition()) 1972 Def = Def->getDefinition(); 1973 return Def; 1974 } 1975 1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1977 /// from S, where a non-field would be declared. This routine copes 1978 /// with the difference between C and C++ scoping rules in structs and 1979 /// unions. For example, the following code is well-formed in C but 1980 /// ill-formed in C++: 1981 /// @code 1982 /// struct S6 { 1983 /// enum { BAR } e; 1984 /// }; 1985 /// 1986 /// void test_S6() { 1987 /// struct S6 a; 1988 /// a.e = BAR; 1989 /// } 1990 /// @endcode 1991 /// For the declaration of BAR, this routine will return a different 1992 /// scope. The scope S will be the scope of the unnamed enumeration 1993 /// within S6. In C++, this routine will return the scope associated 1994 /// with S6, because the enumeration's scope is a transparent 1995 /// context but structures can contain non-field names. In C, this 1996 /// routine will return the translation unit scope, since the 1997 /// enumeration's scope is a transparent context and structures cannot 1998 /// contain non-field names. 1999 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2000 while (((S->getFlags() & Scope::DeclScope) == 0) || 2001 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2002 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2003 S = S->getParent(); 2004 return S; 2005 } 2006 2007 /// Looks up the declaration of "struct objc_super" and 2008 /// saves it for later use in building builtin declaration of 2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2010 /// pre-existing declaration exists no action takes place. 2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2012 IdentifierInfo *II) { 2013 if (!II->isStr("objc_msgSendSuper")) 2014 return; 2015 ASTContext &Context = ThisSema.Context; 2016 2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2018 SourceLocation(), Sema::LookupTagName); 2019 ThisSema.LookupName(Result, S); 2020 if (Result.getResultKind() == LookupResult::Found) 2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2022 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2023 } 2024 2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2026 ASTContext::GetBuiltinTypeError Error) { 2027 switch (Error) { 2028 case ASTContext::GE_None: 2029 return ""; 2030 case ASTContext::GE_Missing_type: 2031 return BuiltinInfo.getHeaderName(ID); 2032 case ASTContext::GE_Missing_stdio: 2033 return "stdio.h"; 2034 case ASTContext::GE_Missing_setjmp: 2035 return "setjmp.h"; 2036 case ASTContext::GE_Missing_ucontext: 2037 return "ucontext.h"; 2038 } 2039 llvm_unreachable("unhandled error kind"); 2040 } 2041 2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2043 /// file scope. lazily create a decl for it. ForRedeclaration is true 2044 /// if we're creating this built-in in anticipation of redeclaring the 2045 /// built-in. 2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2047 Scope *S, bool ForRedeclaration, 2048 SourceLocation Loc) { 2049 LookupPredefedObjCSuperType(*this, S, II); 2050 2051 ASTContext::GetBuiltinTypeError Error; 2052 QualType R = Context.GetBuiltinType(ID, Error); 2053 if (Error) { 2054 if (!ForRedeclaration) 2055 return nullptr; 2056 2057 // If we have a builtin without an associated type we should not emit a 2058 // warning when we were not able to find a type for it. 2059 if (Error == ASTContext::GE_Missing_type) 2060 return nullptr; 2061 2062 // If we could not find a type for setjmp it is because the jmp_buf type was 2063 // not defined prior to the setjmp declaration. 2064 if (Error == ASTContext::GE_Missing_setjmp) { 2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2066 << Context.BuiltinInfo.getName(ID); 2067 return nullptr; 2068 } 2069 2070 // Generally, we emit a warning that the declaration requires the 2071 // appropriate header. 2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2073 << getHeaderName(Context.BuiltinInfo, ID, Error) 2074 << Context.BuiltinInfo.getName(ID); 2075 return nullptr; 2076 } 2077 2078 if (!ForRedeclaration && 2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2081 Diag(Loc, diag::ext_implicit_lib_function_decl) 2082 << Context.BuiltinInfo.getName(ID) << R; 2083 if (Context.BuiltinInfo.getHeaderName(ID) && 2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2085 Diag(Loc, diag::note_include_header_or_declare) 2086 << Context.BuiltinInfo.getHeaderName(ID) 2087 << Context.BuiltinInfo.getName(ID); 2088 } 2089 2090 if (R.isNull()) 2091 return nullptr; 2092 2093 DeclContext *Parent = Context.getTranslationUnitDecl(); 2094 if (getLangOpts().CPlusPlus) { 2095 LinkageSpecDecl *CLinkageDecl = 2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2097 LinkageSpecDecl::lang_c, false); 2098 CLinkageDecl->setImplicit(); 2099 Parent->addDecl(CLinkageDecl); 2100 Parent = CLinkageDecl; 2101 } 2102 2103 FunctionDecl *New = FunctionDecl::Create(Context, 2104 Parent, 2105 Loc, Loc, II, R, /*TInfo=*/nullptr, 2106 SC_Extern, 2107 false, 2108 R->isFunctionProtoType()); 2109 New->setImplicit(); 2110 2111 // Create Decl objects for each parameter, adding them to the 2112 // FunctionDecl. 2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2114 SmallVector<ParmVarDecl*, 16> Params; 2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2116 ParmVarDecl *parm = 2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2119 SC_None, nullptr); 2120 parm->setScopeInfo(0, i); 2121 Params.push_back(parm); 2122 } 2123 New->setParams(Params); 2124 } 2125 2126 AddKnownFunctionAttributes(New); 2127 RegisterLocallyScopedExternCDecl(New, S); 2128 2129 // TUScope is the translation-unit scope to insert this function into. 2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2131 // relate Scopes to DeclContexts, and probably eliminate CurContext 2132 // entirely, but we're not there yet. 2133 DeclContext *SavedContext = CurContext; 2134 CurContext = Parent; 2135 PushOnScopeChains(New, TUScope); 2136 CurContext = SavedContext; 2137 return New; 2138 } 2139 2140 /// Typedef declarations don't have linkage, but they still denote the same 2141 /// entity if their types are the same. 2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2143 /// isSameEntity. 2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2145 TypedefNameDecl *Decl, 2146 LookupResult &Previous) { 2147 // This is only interesting when modules are enabled. 2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2149 return; 2150 2151 // Empty sets are uninteresting. 2152 if (Previous.empty()) 2153 return; 2154 2155 LookupResult::Filter Filter = Previous.makeFilter(); 2156 while (Filter.hasNext()) { 2157 NamedDecl *Old = Filter.next(); 2158 2159 // Non-hidden declarations are never ignored. 2160 if (S.isVisible(Old)) 2161 continue; 2162 2163 // Declarations of the same entity are not ignored, even if they have 2164 // different linkages. 2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2167 Decl->getUnderlyingType())) 2168 continue; 2169 2170 // If both declarations give a tag declaration a typedef name for linkage 2171 // purposes, then they declare the same entity. 2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2173 Decl->getAnonDeclWithTypedefName()) 2174 continue; 2175 } 2176 2177 Filter.erase(); 2178 } 2179 2180 Filter.done(); 2181 } 2182 2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2184 QualType OldType; 2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2186 OldType = OldTypedef->getUnderlyingType(); 2187 else 2188 OldType = Context.getTypeDeclType(Old); 2189 QualType NewType = New->getUnderlyingType(); 2190 2191 if (NewType->isVariablyModifiedType()) { 2192 // Must not redefine a typedef with a variably-modified type. 2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2195 << Kind << NewType; 2196 if (Old->getLocation().isValid()) 2197 notePreviousDefinition(Old, New->getLocation()); 2198 New->setInvalidDecl(); 2199 return true; 2200 } 2201 2202 if (OldType != NewType && 2203 !OldType->isDependentType() && 2204 !NewType->isDependentType() && 2205 !Context.hasSameType(OldType, NewType)) { 2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2208 << Kind << NewType << OldType; 2209 if (Old->getLocation().isValid()) 2210 notePreviousDefinition(Old, New->getLocation()); 2211 New->setInvalidDecl(); 2212 return true; 2213 } 2214 return false; 2215 } 2216 2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2218 /// same name and scope as a previous declaration 'Old'. Figure out 2219 /// how to resolve this situation, merging decls or emitting 2220 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2221 /// 2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2223 LookupResult &OldDecls) { 2224 // If the new decl is known invalid already, don't bother doing any 2225 // merging checks. 2226 if (New->isInvalidDecl()) return; 2227 2228 // Allow multiple definitions for ObjC built-in typedefs. 2229 // FIXME: Verify the underlying types are equivalent! 2230 if (getLangOpts().ObjC) { 2231 const IdentifierInfo *TypeID = New->getIdentifier(); 2232 switch (TypeID->getLength()) { 2233 default: break; 2234 case 2: 2235 { 2236 if (!TypeID->isStr("id")) 2237 break; 2238 QualType T = New->getUnderlyingType(); 2239 if (!T->isPointerType()) 2240 break; 2241 if (!T->isVoidPointerType()) { 2242 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2243 if (!PT->isStructureType()) 2244 break; 2245 } 2246 Context.setObjCIdRedefinitionType(T); 2247 // Install the built-in type for 'id', ignoring the current definition. 2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2249 return; 2250 } 2251 case 5: 2252 if (!TypeID->isStr("Class")) 2253 break; 2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2255 // Install the built-in type for 'Class', ignoring the current definition. 2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2257 return; 2258 case 3: 2259 if (!TypeID->isStr("SEL")) 2260 break; 2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2262 // Install the built-in type for 'SEL', ignoring the current definition. 2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2264 return; 2265 } 2266 // Fall through - the typedef name was not a builtin type. 2267 } 2268 2269 // Verify the old decl was also a type. 2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2271 if (!Old) { 2272 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2273 << New->getDeclName(); 2274 2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2276 if (OldD->getLocation().isValid()) 2277 notePreviousDefinition(OldD, New->getLocation()); 2278 2279 return New->setInvalidDecl(); 2280 } 2281 2282 // If the old declaration is invalid, just give up here. 2283 if (Old->isInvalidDecl()) 2284 return New->setInvalidDecl(); 2285 2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2288 auto *NewTag = New->getAnonDeclWithTypedefName(); 2289 NamedDecl *Hidden = nullptr; 2290 if (OldTag && NewTag && 2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2292 !hasVisibleDefinition(OldTag, &Hidden)) { 2293 // There is a definition of this tag, but it is not visible. Use it 2294 // instead of our tag. 2295 New->setTypeForDecl(OldTD->getTypeForDecl()); 2296 if (OldTD->isModed()) 2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2298 OldTD->getUnderlyingType()); 2299 else 2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2301 2302 // Make the old tag definition visible. 2303 makeMergedDefinitionVisible(Hidden); 2304 2305 // If this was an unscoped enumeration, yank all of its enumerators 2306 // out of the scope. 2307 if (isa<EnumDecl>(NewTag)) { 2308 Scope *EnumScope = getNonFieldDeclScope(S); 2309 for (auto *D : NewTag->decls()) { 2310 auto *ED = cast<EnumConstantDecl>(D); 2311 assert(EnumScope->isDeclScope(ED)); 2312 EnumScope->RemoveDecl(ED); 2313 IdResolver.RemoveDecl(ED); 2314 ED->getLexicalDeclContext()->removeDecl(ED); 2315 } 2316 } 2317 } 2318 } 2319 2320 // If the typedef types are not identical, reject them in all languages and 2321 // with any extensions enabled. 2322 if (isIncompatibleTypedef(Old, New)) 2323 return; 2324 2325 // The types match. Link up the redeclaration chain and merge attributes if 2326 // the old declaration was a typedef. 2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2328 New->setPreviousDecl(Typedef); 2329 mergeDeclAttributes(New, Old); 2330 } 2331 2332 if (getLangOpts().MicrosoftExt) 2333 return; 2334 2335 if (getLangOpts().CPlusPlus) { 2336 // C++ [dcl.typedef]p2: 2337 // In a given non-class scope, a typedef specifier can be used to 2338 // redefine the name of any type declared in that scope to refer 2339 // to the type to which it already refers. 2340 if (!isa<CXXRecordDecl>(CurContext)) 2341 return; 2342 2343 // C++0x [dcl.typedef]p4: 2344 // In a given class scope, a typedef specifier can be used to redefine 2345 // any class-name declared in that scope that is not also a typedef-name 2346 // to refer to the type to which it already refers. 2347 // 2348 // This wording came in via DR424, which was a correction to the 2349 // wording in DR56, which accidentally banned code like: 2350 // 2351 // struct S { 2352 // typedef struct A { } A; 2353 // }; 2354 // 2355 // in the C++03 standard. We implement the C++0x semantics, which 2356 // allow the above but disallow 2357 // 2358 // struct S { 2359 // typedef int I; 2360 // typedef int I; 2361 // }; 2362 // 2363 // since that was the intent of DR56. 2364 if (!isa<TypedefNameDecl>(Old)) 2365 return; 2366 2367 Diag(New->getLocation(), diag::err_redefinition) 2368 << New->getDeclName(); 2369 notePreviousDefinition(Old, New->getLocation()); 2370 return New->setInvalidDecl(); 2371 } 2372 2373 // Modules always permit redefinition of typedefs, as does C11. 2374 if (getLangOpts().Modules || getLangOpts().C11) 2375 return; 2376 2377 // If we have a redefinition of a typedef in C, emit a warning. This warning 2378 // is normally mapped to an error, but can be controlled with 2379 // -Wtypedef-redefinition. If either the original or the redefinition is 2380 // in a system header, don't emit this for compatibility with GCC. 2381 if (getDiagnostics().getSuppressSystemWarnings() && 2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2383 (Old->isImplicit() || 2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2385 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2386 return; 2387 2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2389 << New->getDeclName(); 2390 notePreviousDefinition(Old, New->getLocation()); 2391 } 2392 2393 /// DeclhasAttr - returns true if decl Declaration already has the target 2394 /// attribute. 2395 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2398 for (const auto *i : D->attrs()) 2399 if (i->getKind() == A->getKind()) { 2400 if (Ann) { 2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2402 return true; 2403 continue; 2404 } 2405 // FIXME: Don't hardcode this check 2406 if (OA && isa<OwnershipAttr>(i)) 2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2408 return true; 2409 } 2410 2411 return false; 2412 } 2413 2414 static bool isAttributeTargetADefinition(Decl *D) { 2415 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2416 return VD->isThisDeclarationADefinition(); 2417 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2418 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2419 return true; 2420 } 2421 2422 /// Merge alignment attributes from \p Old to \p New, taking into account the 2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2424 /// 2425 /// \return \c true if any attributes were added to \p New. 2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2427 // Look for alignas attributes on Old, and pick out whichever attribute 2428 // specifies the strictest alignment requirement. 2429 AlignedAttr *OldAlignasAttr = nullptr; 2430 AlignedAttr *OldStrictestAlignAttr = nullptr; 2431 unsigned OldAlign = 0; 2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2433 // FIXME: We have no way of representing inherited dependent alignments 2434 // in a case like: 2435 // template<int A, int B> struct alignas(A) X; 2436 // template<int A, int B> struct alignas(B) X {}; 2437 // For now, we just ignore any alignas attributes which are not on the 2438 // definition in such a case. 2439 if (I->isAlignmentDependent()) 2440 return false; 2441 2442 if (I->isAlignas()) 2443 OldAlignasAttr = I; 2444 2445 unsigned Align = I->getAlignment(S.Context); 2446 if (Align > OldAlign) { 2447 OldAlign = Align; 2448 OldStrictestAlignAttr = I; 2449 } 2450 } 2451 2452 // Look for alignas attributes on New. 2453 AlignedAttr *NewAlignasAttr = nullptr; 2454 unsigned NewAlign = 0; 2455 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2456 if (I->isAlignmentDependent()) 2457 return false; 2458 2459 if (I->isAlignas()) 2460 NewAlignasAttr = I; 2461 2462 unsigned Align = I->getAlignment(S.Context); 2463 if (Align > NewAlign) 2464 NewAlign = Align; 2465 } 2466 2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2468 // Both declarations have 'alignas' attributes. We require them to match. 2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2470 // fall short. (If two declarations both have alignas, they must both match 2471 // every definition, and so must match each other if there is a definition.) 2472 2473 // If either declaration only contains 'alignas(0)' specifiers, then it 2474 // specifies the natural alignment for the type. 2475 if (OldAlign == 0 || NewAlign == 0) { 2476 QualType Ty; 2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2478 Ty = VD->getType(); 2479 else 2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2481 2482 if (OldAlign == 0) 2483 OldAlign = S.Context.getTypeAlign(Ty); 2484 if (NewAlign == 0) 2485 NewAlign = S.Context.getTypeAlign(Ty); 2486 } 2487 2488 if (OldAlign != NewAlign) { 2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2493 } 2494 } 2495 2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2497 // C++11 [dcl.align]p6: 2498 // if any declaration of an entity has an alignment-specifier, 2499 // every defining declaration of that entity shall specify an 2500 // equivalent alignment. 2501 // C11 6.7.5/7: 2502 // If the definition of an object does not have an alignment 2503 // specifier, any other declaration of that object shall also 2504 // have no alignment specifier. 2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2506 << OldAlignasAttr; 2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2508 << OldAlignasAttr; 2509 } 2510 2511 bool AnyAdded = false; 2512 2513 // Ensure we have an attribute representing the strictest alignment. 2514 if (OldAlign > NewAlign) { 2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2516 Clone->setInherited(true); 2517 New->addAttr(Clone); 2518 AnyAdded = true; 2519 } 2520 2521 // Ensure we have an alignas attribute if the old declaration had one. 2522 if (OldAlignasAttr && !NewAlignasAttr && 2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2525 Clone->setInherited(true); 2526 New->addAttr(Clone); 2527 AnyAdded = true; 2528 } 2529 2530 return AnyAdded; 2531 } 2532 2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2534 const InheritableAttr *Attr, 2535 Sema::AvailabilityMergeKind AMK) { 2536 // This function copies an attribute Attr from a previous declaration to the 2537 // new declaration D if the new declaration doesn't itself have that attribute 2538 // yet or if that attribute allows duplicates. 2539 // If you're adding a new attribute that requires logic different from 2540 // "use explicit attribute on decl if present, else use attribute from 2541 // previous decl", for example if the attribute needs to be consistent 2542 // between redeclarations, you need to call a custom merge function here. 2543 InheritableAttr *NewAttr = nullptr; 2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2545 NewAttr = S.mergeAvailabilityAttr( 2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2549 AA->getPriority()); 2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2560 FA->getFirstArg()); 2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2567 IA->getInheritanceModel()); 2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2570 &S.Context.Idents.get(AA->getSpelling())); 2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2573 isa<CUDAGlobalAttr>(Attr))) { 2574 // CUDA target attributes are part of function signature for 2575 // overloading purposes and must not be merged. 2576 return false; 2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2578 NewAttr = S.mergeMinSizeAttr(D, *MA); 2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2584 NewAttr = S.mergeCommonAttr(D, *CommonA); 2585 else if (isa<AlignedAttr>(Attr)) 2586 // AlignedAttrs are handled separately, because we need to handle all 2587 // such attributes on a declaration at the same time. 2588 NewAttr = nullptr; 2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2590 (AMK == Sema::AMK_Override || 2591 AMK == Sema::AMK_ProtocolImplementation)) 2592 NewAttr = nullptr; 2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2601 2602 if (NewAttr) { 2603 NewAttr->setInherited(true); 2604 D->addAttr(NewAttr); 2605 if (isa<MSInheritanceAttr>(NewAttr)) 2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2607 return true; 2608 } 2609 2610 return false; 2611 } 2612 2613 static const NamedDecl *getDefinition(const Decl *D) { 2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2615 return TD->getDefinition(); 2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2617 const VarDecl *Def = VD->getDefinition(); 2618 if (Def) 2619 return Def; 2620 return VD->getActingDefinition(); 2621 } 2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2623 return FD->getDefinition(); 2624 return nullptr; 2625 } 2626 2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2628 for (const auto *Attribute : D->attrs()) 2629 if (Attribute->getKind() == Kind) 2630 return true; 2631 return false; 2632 } 2633 2634 /// checkNewAttributesAfterDef - If we already have a definition, check that 2635 /// there are no new attributes in this declaration. 2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2637 if (!New->hasAttrs()) 2638 return; 2639 2640 const NamedDecl *Def = getDefinition(Old); 2641 if (!Def || Def == New) 2642 return; 2643 2644 AttrVec &NewAttributes = New->getAttrs(); 2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2646 const Attr *NewAttribute = NewAttributes[I]; 2647 2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2650 Sema::SkipBodyInfo SkipBody; 2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2652 2653 // If we're skipping this definition, drop the "alias" attribute. 2654 if (SkipBody.ShouldSkip) { 2655 NewAttributes.erase(NewAttributes.begin() + I); 2656 --E; 2657 continue; 2658 } 2659 } else { 2660 VarDecl *VD = cast<VarDecl>(New); 2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2662 VarDecl::TentativeDefinition 2663 ? diag::err_alias_after_tentative 2664 : diag::err_redefinition; 2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2666 if (Diag == diag::err_redefinition) 2667 S.notePreviousDefinition(Def, VD->getLocation()); 2668 else 2669 S.Diag(Def->getLocation(), diag::note_previous_definition); 2670 VD->setInvalidDecl(); 2671 } 2672 ++I; 2673 continue; 2674 } 2675 2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2677 // Tentative definitions are only interesting for the alias check above. 2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2679 ++I; 2680 continue; 2681 } 2682 } 2683 2684 if (hasAttribute(Def, NewAttribute->getKind())) { 2685 ++I; 2686 continue; // regular attr merging will take care of validating this. 2687 } 2688 2689 if (isa<C11NoReturnAttr>(NewAttribute)) { 2690 // C's _Noreturn is allowed to be added to a function after it is defined. 2691 ++I; 2692 continue; 2693 } else if (isa<UuidAttr>(NewAttribute)) { 2694 // msvc will allow a subsequent definition to add an uuid to a class 2695 ++I; 2696 continue; 2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2698 if (AA->isAlignas()) { 2699 // C++11 [dcl.align]p6: 2700 // if any declaration of an entity has an alignment-specifier, 2701 // every defining declaration of that entity shall specify an 2702 // equivalent alignment. 2703 // C11 6.7.5/7: 2704 // If the definition of an object does not have an alignment 2705 // specifier, any other declaration of that object shall also 2706 // have no alignment specifier. 2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2708 << AA; 2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2710 << AA; 2711 NewAttributes.erase(NewAttributes.begin() + I); 2712 --E; 2713 continue; 2714 } 2715 } else if (isa<SelectAnyAttr>(NewAttribute) && 2716 cast<VarDecl>(New)->isInline() && 2717 !cast<VarDecl>(New)->isInlineSpecified()) { 2718 // Don't warn about applying selectany to implicitly inline variables. 2719 // Older compilers and language modes would require the use of selectany 2720 // to make such variables inline, and it would have no effect if we 2721 // honored it. 2722 ++I; 2723 continue; 2724 } 2725 2726 S.Diag(NewAttribute->getLocation(), 2727 diag::warn_attribute_precede_definition); 2728 S.Diag(Def->getLocation(), diag::note_previous_definition); 2729 NewAttributes.erase(NewAttributes.begin() + I); 2730 --E; 2731 } 2732 } 2733 2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2735 const ConstInitAttr *CIAttr, 2736 bool AttrBeforeInit) { 2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2738 2739 // Figure out a good way to write this specifier on the old declaration. 2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2741 // enough of the attribute list spelling information to extract that without 2742 // heroics. 2743 std::string SuitableSpelling; 2744 if (S.getLangOpts().CPlusPlus2a) 2745 SuitableSpelling = std::string( 2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2748 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2749 InsertLoc, {tok::l_square, tok::l_square, 2750 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2751 S.PP.getIdentifierInfo("require_constant_initialization"), 2752 tok::r_square, tok::r_square})); 2753 if (SuitableSpelling.empty()) 2754 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2755 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2756 S.PP.getIdentifierInfo("require_constant_initialization"), 2757 tok::r_paren, tok::r_paren})); 2758 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2759 SuitableSpelling = "constinit"; 2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2761 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2762 if (SuitableSpelling.empty()) 2763 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2764 SuitableSpelling += " "; 2765 2766 if (AttrBeforeInit) { 2767 // extern constinit int a; 2768 // int a = 0; // error (missing 'constinit'), accepted as extension 2769 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2770 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2771 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2772 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2773 } else { 2774 // int a = 0; 2775 // constinit extern int a; // error (missing 'constinit') 2776 S.Diag(CIAttr->getLocation(), 2777 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2778 : diag::warn_require_const_init_added_too_late) 2779 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2780 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2781 << CIAttr->isConstinit() 2782 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2783 } 2784 } 2785 2786 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2787 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2788 AvailabilityMergeKind AMK) { 2789 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2790 UsedAttr *NewAttr = OldAttr->clone(Context); 2791 NewAttr->setInherited(true); 2792 New->addAttr(NewAttr); 2793 } 2794 2795 if (!Old->hasAttrs() && !New->hasAttrs()) 2796 return; 2797 2798 // [dcl.constinit]p1: 2799 // If the [constinit] specifier is applied to any declaration of a 2800 // variable, it shall be applied to the initializing declaration. 2801 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2802 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2803 if (bool(OldConstInit) != bool(NewConstInit)) { 2804 const auto *OldVD = cast<VarDecl>(Old); 2805 auto *NewVD = cast<VarDecl>(New); 2806 2807 // Find the initializing declaration. Note that we might not have linked 2808 // the new declaration into the redeclaration chain yet. 2809 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2810 if (!InitDecl && 2811 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2812 InitDecl = NewVD; 2813 2814 if (InitDecl == NewVD) { 2815 // This is the initializing declaration. If it would inherit 'constinit', 2816 // that's ill-formed. (Note that we do not apply this to the attribute 2817 // form). 2818 if (OldConstInit && OldConstInit->isConstinit()) 2819 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2820 /*AttrBeforeInit=*/true); 2821 } else if (NewConstInit) { 2822 // This is the first time we've been told that this declaration should 2823 // have a constant initializer. If we already saw the initializing 2824 // declaration, this is too late. 2825 if (InitDecl && InitDecl != NewVD) { 2826 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2827 /*AttrBeforeInit=*/false); 2828 NewVD->dropAttr<ConstInitAttr>(); 2829 } 2830 } 2831 } 2832 2833 // Attributes declared post-definition are currently ignored. 2834 checkNewAttributesAfterDef(*this, New, Old); 2835 2836 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2837 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2838 if (!OldA->isEquivalent(NewA)) { 2839 // This redeclaration changes __asm__ label. 2840 Diag(New->getLocation(), diag::err_different_asm_label); 2841 Diag(OldA->getLocation(), diag::note_previous_declaration); 2842 } 2843 } else if (Old->isUsed()) { 2844 // This redeclaration adds an __asm__ label to a declaration that has 2845 // already been ODR-used. 2846 Diag(New->getLocation(), diag::err_late_asm_label_name) 2847 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2848 } 2849 } 2850 2851 // Re-declaration cannot add abi_tag's. 2852 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2853 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2854 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2855 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2856 NewTag) == OldAbiTagAttr->tags_end()) { 2857 Diag(NewAbiTagAttr->getLocation(), 2858 diag::err_new_abi_tag_on_redeclaration) 2859 << NewTag; 2860 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2861 } 2862 } 2863 } else { 2864 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2865 Diag(Old->getLocation(), diag::note_previous_declaration); 2866 } 2867 } 2868 2869 // This redeclaration adds a section attribute. 2870 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2871 if (auto *VD = dyn_cast<VarDecl>(New)) { 2872 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2873 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2874 Diag(Old->getLocation(), diag::note_previous_declaration); 2875 } 2876 } 2877 } 2878 2879 // Redeclaration adds code-seg attribute. 2880 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2881 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2882 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2883 Diag(New->getLocation(), diag::warn_mismatched_section) 2884 << 0 /*codeseg*/; 2885 Diag(Old->getLocation(), diag::note_previous_declaration); 2886 } 2887 2888 if (!Old->hasAttrs()) 2889 return; 2890 2891 bool foundAny = New->hasAttrs(); 2892 2893 // Ensure that any moving of objects within the allocated map is done before 2894 // we process them. 2895 if (!foundAny) New->setAttrs(AttrVec()); 2896 2897 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2898 // Ignore deprecated/unavailable/availability attributes if requested. 2899 AvailabilityMergeKind LocalAMK = AMK_None; 2900 if (isa<DeprecatedAttr>(I) || 2901 isa<UnavailableAttr>(I) || 2902 isa<AvailabilityAttr>(I)) { 2903 switch (AMK) { 2904 case AMK_None: 2905 continue; 2906 2907 case AMK_Redeclaration: 2908 case AMK_Override: 2909 case AMK_ProtocolImplementation: 2910 LocalAMK = AMK; 2911 break; 2912 } 2913 } 2914 2915 // Already handled. 2916 if (isa<UsedAttr>(I)) 2917 continue; 2918 2919 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2920 foundAny = true; 2921 } 2922 2923 if (mergeAlignedAttrs(*this, New, Old)) 2924 foundAny = true; 2925 2926 if (!foundAny) New->dropAttrs(); 2927 } 2928 2929 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2930 /// to the new one. 2931 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2932 const ParmVarDecl *oldDecl, 2933 Sema &S) { 2934 // C++11 [dcl.attr.depend]p2: 2935 // The first declaration of a function shall specify the 2936 // carries_dependency attribute for its declarator-id if any declaration 2937 // of the function specifies the carries_dependency attribute. 2938 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2939 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2940 S.Diag(CDA->getLocation(), 2941 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2942 // Find the first declaration of the parameter. 2943 // FIXME: Should we build redeclaration chains for function parameters? 2944 const FunctionDecl *FirstFD = 2945 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2946 const ParmVarDecl *FirstVD = 2947 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2948 S.Diag(FirstVD->getLocation(), 2949 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2950 } 2951 2952 if (!oldDecl->hasAttrs()) 2953 return; 2954 2955 bool foundAny = newDecl->hasAttrs(); 2956 2957 // Ensure that any moving of objects within the allocated map is 2958 // done before we process them. 2959 if (!foundAny) newDecl->setAttrs(AttrVec()); 2960 2961 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2962 if (!DeclHasAttr(newDecl, I)) { 2963 InheritableAttr *newAttr = 2964 cast<InheritableParamAttr>(I->clone(S.Context)); 2965 newAttr->setInherited(true); 2966 newDecl->addAttr(newAttr); 2967 foundAny = true; 2968 } 2969 } 2970 2971 if (!foundAny) newDecl->dropAttrs(); 2972 } 2973 2974 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2975 const ParmVarDecl *OldParam, 2976 Sema &S) { 2977 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2978 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2979 if (*Oldnullability != *Newnullability) { 2980 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2981 << DiagNullabilityKind( 2982 *Newnullability, 2983 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2984 != 0)) 2985 << DiagNullabilityKind( 2986 *Oldnullability, 2987 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2988 != 0)); 2989 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2990 } 2991 } else { 2992 QualType NewT = NewParam->getType(); 2993 NewT = S.Context.getAttributedType( 2994 AttributedType::getNullabilityAttrKind(*Oldnullability), 2995 NewT, NewT); 2996 NewParam->setType(NewT); 2997 } 2998 } 2999 } 3000 3001 namespace { 3002 3003 /// Used in MergeFunctionDecl to keep track of function parameters in 3004 /// C. 3005 struct GNUCompatibleParamWarning { 3006 ParmVarDecl *OldParm; 3007 ParmVarDecl *NewParm; 3008 QualType PromotedType; 3009 }; 3010 3011 } // end anonymous namespace 3012 3013 // Determine whether the previous declaration was a definition, implicit 3014 // declaration, or a declaration. 3015 template <typename T> 3016 static std::pair<diag::kind, SourceLocation> 3017 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3018 diag::kind PrevDiag; 3019 SourceLocation OldLocation = Old->getLocation(); 3020 if (Old->isThisDeclarationADefinition()) 3021 PrevDiag = diag::note_previous_definition; 3022 else if (Old->isImplicit()) { 3023 PrevDiag = diag::note_previous_implicit_declaration; 3024 if (OldLocation.isInvalid()) 3025 OldLocation = New->getLocation(); 3026 } else 3027 PrevDiag = diag::note_previous_declaration; 3028 return std::make_pair(PrevDiag, OldLocation); 3029 } 3030 3031 /// canRedefineFunction - checks if a function can be redefined. Currently, 3032 /// only extern inline functions can be redefined, and even then only in 3033 /// GNU89 mode. 3034 static bool canRedefineFunction(const FunctionDecl *FD, 3035 const LangOptions& LangOpts) { 3036 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3037 !LangOpts.CPlusPlus && 3038 FD->isInlineSpecified() && 3039 FD->getStorageClass() == SC_Extern); 3040 } 3041 3042 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3043 const AttributedType *AT = T->getAs<AttributedType>(); 3044 while (AT && !AT->isCallingConv()) 3045 AT = AT->getModifiedType()->getAs<AttributedType>(); 3046 return AT; 3047 } 3048 3049 template <typename T> 3050 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3051 const DeclContext *DC = Old->getDeclContext(); 3052 if (DC->isRecord()) 3053 return false; 3054 3055 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3056 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3057 return true; 3058 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3059 return true; 3060 return false; 3061 } 3062 3063 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3064 static bool isExternC(VarTemplateDecl *) { return false; } 3065 3066 /// Check whether a redeclaration of an entity introduced by a 3067 /// using-declaration is valid, given that we know it's not an overload 3068 /// (nor a hidden tag declaration). 3069 template<typename ExpectedDecl> 3070 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3071 ExpectedDecl *New) { 3072 // C++11 [basic.scope.declarative]p4: 3073 // Given a set of declarations in a single declarative region, each of 3074 // which specifies the same unqualified name, 3075 // -- they shall all refer to the same entity, or all refer to functions 3076 // and function templates; or 3077 // -- exactly one declaration shall declare a class name or enumeration 3078 // name that is not a typedef name and the other declarations shall all 3079 // refer to the same variable or enumerator, or all refer to functions 3080 // and function templates; in this case the class name or enumeration 3081 // name is hidden (3.3.10). 3082 3083 // C++11 [namespace.udecl]p14: 3084 // If a function declaration in namespace scope or block scope has the 3085 // same name and the same parameter-type-list as a function introduced 3086 // by a using-declaration, and the declarations do not declare the same 3087 // function, the program is ill-formed. 3088 3089 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3090 if (Old && 3091 !Old->getDeclContext()->getRedeclContext()->Equals( 3092 New->getDeclContext()->getRedeclContext()) && 3093 !(isExternC(Old) && isExternC(New))) 3094 Old = nullptr; 3095 3096 if (!Old) { 3097 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3098 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3099 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3100 return true; 3101 } 3102 return false; 3103 } 3104 3105 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3106 const FunctionDecl *B) { 3107 assert(A->getNumParams() == B->getNumParams()); 3108 3109 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3110 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3111 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3112 if (AttrA == AttrB) 3113 return true; 3114 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3115 AttrA->isDynamic() == AttrB->isDynamic(); 3116 }; 3117 3118 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3119 } 3120 3121 /// If necessary, adjust the semantic declaration context for a qualified 3122 /// declaration to name the correct inline namespace within the qualifier. 3123 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3124 DeclaratorDecl *OldD) { 3125 // The only case where we need to update the DeclContext is when 3126 // redeclaration lookup for a qualified name finds a declaration 3127 // in an inline namespace within the context named by the qualifier: 3128 // 3129 // inline namespace N { int f(); } 3130 // int ::f(); // Sema DC needs adjusting from :: to N::. 3131 // 3132 // For unqualified declarations, the semantic context *can* change 3133 // along the redeclaration chain (for local extern declarations, 3134 // extern "C" declarations, and friend declarations in particular). 3135 if (!NewD->getQualifier()) 3136 return; 3137 3138 // NewD is probably already in the right context. 3139 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3140 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3141 if (NamedDC->Equals(SemaDC)) 3142 return; 3143 3144 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3145 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3146 "unexpected context for redeclaration"); 3147 3148 auto *LexDC = NewD->getLexicalDeclContext(); 3149 auto FixSemaDC = [=](NamedDecl *D) { 3150 if (!D) 3151 return; 3152 D->setDeclContext(SemaDC); 3153 D->setLexicalDeclContext(LexDC); 3154 }; 3155 3156 FixSemaDC(NewD); 3157 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3158 FixSemaDC(FD->getDescribedFunctionTemplate()); 3159 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3160 FixSemaDC(VD->getDescribedVarTemplate()); 3161 } 3162 3163 /// MergeFunctionDecl - We just parsed a function 'New' from 3164 /// declarator D which has the same name and scope as a previous 3165 /// declaration 'Old'. Figure out how to resolve this situation, 3166 /// merging decls or emitting diagnostics as appropriate. 3167 /// 3168 /// In C++, New and Old must be declarations that are not 3169 /// overloaded. Use IsOverload to determine whether New and Old are 3170 /// overloaded, and to select the Old declaration that New should be 3171 /// merged with. 3172 /// 3173 /// Returns true if there was an error, false otherwise. 3174 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3175 Scope *S, bool MergeTypeWithOld) { 3176 // Verify the old decl was also a function. 3177 FunctionDecl *Old = OldD->getAsFunction(); 3178 if (!Old) { 3179 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3180 if (New->getFriendObjectKind()) { 3181 Diag(New->getLocation(), diag::err_using_decl_friend); 3182 Diag(Shadow->getTargetDecl()->getLocation(), 3183 diag::note_using_decl_target); 3184 Diag(Shadow->getUsingDecl()->getLocation(), 3185 diag::note_using_decl) << 0; 3186 return true; 3187 } 3188 3189 // Check whether the two declarations might declare the same function. 3190 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3191 return true; 3192 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3193 } else { 3194 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3195 << New->getDeclName(); 3196 notePreviousDefinition(OldD, New->getLocation()); 3197 return true; 3198 } 3199 } 3200 3201 // If the old declaration is invalid, just give up here. 3202 if (Old->isInvalidDecl()) 3203 return true; 3204 3205 // Disallow redeclaration of some builtins. 3206 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3207 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3208 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3209 << Old << Old->getType(); 3210 return true; 3211 } 3212 3213 diag::kind PrevDiag; 3214 SourceLocation OldLocation; 3215 std::tie(PrevDiag, OldLocation) = 3216 getNoteDiagForInvalidRedeclaration(Old, New); 3217 3218 // Don't complain about this if we're in GNU89 mode and the old function 3219 // is an extern inline function. 3220 // Don't complain about specializations. They are not supposed to have 3221 // storage classes. 3222 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3223 New->getStorageClass() == SC_Static && 3224 Old->hasExternalFormalLinkage() && 3225 !New->getTemplateSpecializationInfo() && 3226 !canRedefineFunction(Old, getLangOpts())) { 3227 if (getLangOpts().MicrosoftExt) { 3228 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3229 Diag(OldLocation, PrevDiag); 3230 } else { 3231 Diag(New->getLocation(), diag::err_static_non_static) << New; 3232 Diag(OldLocation, PrevDiag); 3233 return true; 3234 } 3235 } 3236 3237 if (New->hasAttr<InternalLinkageAttr>() && 3238 !Old->hasAttr<InternalLinkageAttr>()) { 3239 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3240 << New->getDeclName(); 3241 notePreviousDefinition(Old, New->getLocation()); 3242 New->dropAttr<InternalLinkageAttr>(); 3243 } 3244 3245 if (CheckRedeclarationModuleOwnership(New, Old)) 3246 return true; 3247 3248 if (!getLangOpts().CPlusPlus) { 3249 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3250 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3251 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3252 << New << OldOvl; 3253 3254 // Try our best to find a decl that actually has the overloadable 3255 // attribute for the note. In most cases (e.g. programs with only one 3256 // broken declaration/definition), this won't matter. 3257 // 3258 // FIXME: We could do this if we juggled some extra state in 3259 // OverloadableAttr, rather than just removing it. 3260 const Decl *DiagOld = Old; 3261 if (OldOvl) { 3262 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3263 const auto *A = D->getAttr<OverloadableAttr>(); 3264 return A && !A->isImplicit(); 3265 }); 3266 // If we've implicitly added *all* of the overloadable attrs to this 3267 // chain, emitting a "previous redecl" note is pointless. 3268 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3269 } 3270 3271 if (DiagOld) 3272 Diag(DiagOld->getLocation(), 3273 diag::note_attribute_overloadable_prev_overload) 3274 << OldOvl; 3275 3276 if (OldOvl) 3277 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3278 else 3279 New->dropAttr<OverloadableAttr>(); 3280 } 3281 } 3282 3283 // If a function is first declared with a calling convention, but is later 3284 // declared or defined without one, all following decls assume the calling 3285 // convention of the first. 3286 // 3287 // It's OK if a function is first declared without a calling convention, 3288 // but is later declared or defined with the default calling convention. 3289 // 3290 // To test if either decl has an explicit calling convention, we look for 3291 // AttributedType sugar nodes on the type as written. If they are missing or 3292 // were canonicalized away, we assume the calling convention was implicit. 3293 // 3294 // Note also that we DO NOT return at this point, because we still have 3295 // other tests to run. 3296 QualType OldQType = Context.getCanonicalType(Old->getType()); 3297 QualType NewQType = Context.getCanonicalType(New->getType()); 3298 const FunctionType *OldType = cast<FunctionType>(OldQType); 3299 const FunctionType *NewType = cast<FunctionType>(NewQType); 3300 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3301 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3302 bool RequiresAdjustment = false; 3303 3304 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3305 FunctionDecl *First = Old->getFirstDecl(); 3306 const FunctionType *FT = 3307 First->getType().getCanonicalType()->castAs<FunctionType>(); 3308 FunctionType::ExtInfo FI = FT->getExtInfo(); 3309 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3310 if (!NewCCExplicit) { 3311 // Inherit the CC from the previous declaration if it was specified 3312 // there but not here. 3313 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3314 RequiresAdjustment = true; 3315 } else if (New->getBuiltinID()) { 3316 // Calling Conventions on a Builtin aren't really useful and setting a 3317 // default calling convention and cdecl'ing some builtin redeclarations is 3318 // common, so warn and ignore the calling convention on the redeclaration. 3319 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3320 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3321 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3322 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3323 RequiresAdjustment = true; 3324 } else { 3325 // Calling conventions aren't compatible, so complain. 3326 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3327 Diag(New->getLocation(), diag::err_cconv_change) 3328 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3329 << !FirstCCExplicit 3330 << (!FirstCCExplicit ? "" : 3331 FunctionType::getNameForCallConv(FI.getCC())); 3332 3333 // Put the note on the first decl, since it is the one that matters. 3334 Diag(First->getLocation(), diag::note_previous_declaration); 3335 return true; 3336 } 3337 } 3338 3339 // FIXME: diagnose the other way around? 3340 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3341 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3342 RequiresAdjustment = true; 3343 } 3344 3345 // Merge regparm attribute. 3346 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3347 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3348 if (NewTypeInfo.getHasRegParm()) { 3349 Diag(New->getLocation(), diag::err_regparm_mismatch) 3350 << NewType->getRegParmType() 3351 << OldType->getRegParmType(); 3352 Diag(OldLocation, diag::note_previous_declaration); 3353 return true; 3354 } 3355 3356 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3357 RequiresAdjustment = true; 3358 } 3359 3360 // Merge ns_returns_retained attribute. 3361 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3362 if (NewTypeInfo.getProducesResult()) { 3363 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3364 << "'ns_returns_retained'"; 3365 Diag(OldLocation, diag::note_previous_declaration); 3366 return true; 3367 } 3368 3369 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3370 RequiresAdjustment = true; 3371 } 3372 3373 if (OldTypeInfo.getNoCallerSavedRegs() != 3374 NewTypeInfo.getNoCallerSavedRegs()) { 3375 if (NewTypeInfo.getNoCallerSavedRegs()) { 3376 AnyX86NoCallerSavedRegistersAttr *Attr = 3377 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3378 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3379 Diag(OldLocation, diag::note_previous_declaration); 3380 return true; 3381 } 3382 3383 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3384 RequiresAdjustment = true; 3385 } 3386 3387 if (RequiresAdjustment) { 3388 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3389 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3390 New->setType(QualType(AdjustedType, 0)); 3391 NewQType = Context.getCanonicalType(New->getType()); 3392 } 3393 3394 // If this redeclaration makes the function inline, we may need to add it to 3395 // UndefinedButUsed. 3396 if (!Old->isInlined() && New->isInlined() && 3397 !New->hasAttr<GNUInlineAttr>() && 3398 !getLangOpts().GNUInline && 3399 Old->isUsed(false) && 3400 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3401 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3402 SourceLocation())); 3403 3404 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3405 // about it. 3406 if (New->hasAttr<GNUInlineAttr>() && 3407 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3408 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3409 } 3410 3411 // If pass_object_size params don't match up perfectly, this isn't a valid 3412 // redeclaration. 3413 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3414 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3415 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3416 << New->getDeclName(); 3417 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3418 return true; 3419 } 3420 3421 if (getLangOpts().CPlusPlus) { 3422 // C++1z [over.load]p2 3423 // Certain function declarations cannot be overloaded: 3424 // -- Function declarations that differ only in the return type, 3425 // the exception specification, or both cannot be overloaded. 3426 3427 // Check the exception specifications match. This may recompute the type of 3428 // both Old and New if it resolved exception specifications, so grab the 3429 // types again after this. Because this updates the type, we do this before 3430 // any of the other checks below, which may update the "de facto" NewQType 3431 // but do not necessarily update the type of New. 3432 if (CheckEquivalentExceptionSpec(Old, New)) 3433 return true; 3434 OldQType = Context.getCanonicalType(Old->getType()); 3435 NewQType = Context.getCanonicalType(New->getType()); 3436 3437 // Go back to the type source info to compare the declared return types, 3438 // per C++1y [dcl.type.auto]p13: 3439 // Redeclarations or specializations of a function or function template 3440 // with a declared return type that uses a placeholder type shall also 3441 // use that placeholder, not a deduced type. 3442 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3443 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3444 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3445 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3446 OldDeclaredReturnType)) { 3447 QualType ResQT; 3448 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3449 OldDeclaredReturnType->isObjCObjectPointerType()) 3450 // FIXME: This does the wrong thing for a deduced return type. 3451 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3452 if (ResQT.isNull()) { 3453 if (New->isCXXClassMember() && New->isOutOfLine()) 3454 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3455 << New << New->getReturnTypeSourceRange(); 3456 else 3457 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3458 << New->getReturnTypeSourceRange(); 3459 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3460 << Old->getReturnTypeSourceRange(); 3461 return true; 3462 } 3463 else 3464 NewQType = ResQT; 3465 } 3466 3467 QualType OldReturnType = OldType->getReturnType(); 3468 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3469 if (OldReturnType != NewReturnType) { 3470 // If this function has a deduced return type and has already been 3471 // defined, copy the deduced value from the old declaration. 3472 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3473 if (OldAT && OldAT->isDeduced()) { 3474 New->setType( 3475 SubstAutoType(New->getType(), 3476 OldAT->isDependentType() ? Context.DependentTy 3477 : OldAT->getDeducedType())); 3478 NewQType = Context.getCanonicalType( 3479 SubstAutoType(NewQType, 3480 OldAT->isDependentType() ? Context.DependentTy 3481 : OldAT->getDeducedType())); 3482 } 3483 } 3484 3485 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3486 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3487 if (OldMethod && NewMethod) { 3488 // Preserve triviality. 3489 NewMethod->setTrivial(OldMethod->isTrivial()); 3490 3491 // MSVC allows explicit template specialization at class scope: 3492 // 2 CXXMethodDecls referring to the same function will be injected. 3493 // We don't want a redeclaration error. 3494 bool IsClassScopeExplicitSpecialization = 3495 OldMethod->isFunctionTemplateSpecialization() && 3496 NewMethod->isFunctionTemplateSpecialization(); 3497 bool isFriend = NewMethod->getFriendObjectKind(); 3498 3499 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3500 !IsClassScopeExplicitSpecialization) { 3501 // -- Member function declarations with the same name and the 3502 // same parameter types cannot be overloaded if any of them 3503 // is a static member function declaration. 3504 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3506 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3507 return true; 3508 } 3509 3510 // C++ [class.mem]p1: 3511 // [...] A member shall not be declared twice in the 3512 // member-specification, except that a nested class or member 3513 // class template can be declared and then later defined. 3514 if (!inTemplateInstantiation()) { 3515 unsigned NewDiag; 3516 if (isa<CXXConstructorDecl>(OldMethod)) 3517 NewDiag = diag::err_constructor_redeclared; 3518 else if (isa<CXXDestructorDecl>(NewMethod)) 3519 NewDiag = diag::err_destructor_redeclared; 3520 else if (isa<CXXConversionDecl>(NewMethod)) 3521 NewDiag = diag::err_conv_function_redeclared; 3522 else 3523 NewDiag = diag::err_member_redeclared; 3524 3525 Diag(New->getLocation(), NewDiag); 3526 } else { 3527 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3528 << New << New->getType(); 3529 } 3530 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3531 return true; 3532 3533 // Complain if this is an explicit declaration of a special 3534 // member that was initially declared implicitly. 3535 // 3536 // As an exception, it's okay to befriend such methods in order 3537 // to permit the implicit constructor/destructor/operator calls. 3538 } else if (OldMethod->isImplicit()) { 3539 if (isFriend) { 3540 NewMethod->setImplicit(); 3541 } else { 3542 Diag(NewMethod->getLocation(), 3543 diag::err_definition_of_implicitly_declared_member) 3544 << New << getSpecialMember(OldMethod); 3545 return true; 3546 } 3547 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3548 Diag(NewMethod->getLocation(), 3549 diag::err_definition_of_explicitly_defaulted_member) 3550 << getSpecialMember(OldMethod); 3551 return true; 3552 } 3553 } 3554 3555 // C++11 [dcl.attr.noreturn]p1: 3556 // The first declaration of a function shall specify the noreturn 3557 // attribute if any declaration of that function specifies the noreturn 3558 // attribute. 3559 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3560 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3561 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3562 Diag(Old->getFirstDecl()->getLocation(), 3563 diag::note_noreturn_missing_first_decl); 3564 } 3565 3566 // C++11 [dcl.attr.depend]p2: 3567 // The first declaration of a function shall specify the 3568 // carries_dependency attribute for its declarator-id if any declaration 3569 // of the function specifies the carries_dependency attribute. 3570 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3571 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3572 Diag(CDA->getLocation(), 3573 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3574 Diag(Old->getFirstDecl()->getLocation(), 3575 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3576 } 3577 3578 // (C++98 8.3.5p3): 3579 // All declarations for a function shall agree exactly in both the 3580 // return type and the parameter-type-list. 3581 // We also want to respect all the extended bits except noreturn. 3582 3583 // noreturn should now match unless the old type info didn't have it. 3584 QualType OldQTypeForComparison = OldQType; 3585 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3586 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3587 const FunctionType *OldTypeForComparison 3588 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3589 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3590 assert(OldQTypeForComparison.isCanonical()); 3591 } 3592 3593 if (haveIncompatibleLanguageLinkages(Old, New)) { 3594 // As a special case, retain the language linkage from previous 3595 // declarations of a friend function as an extension. 3596 // 3597 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3598 // and is useful because there's otherwise no way to specify language 3599 // linkage within class scope. 3600 // 3601 // Check cautiously as the friend object kind isn't yet complete. 3602 if (New->getFriendObjectKind() != Decl::FOK_None) { 3603 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3604 Diag(OldLocation, PrevDiag); 3605 } else { 3606 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3607 Diag(OldLocation, PrevDiag); 3608 return true; 3609 } 3610 } 3611 3612 // If the function types are compatible, merge the declarations. Ignore the 3613 // exception specifier because it was already checked above in 3614 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3615 // about incompatible types under -fms-compatibility. 3616 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3617 NewQType)) 3618 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3619 3620 // If the types are imprecise (due to dependent constructs in friends or 3621 // local extern declarations), it's OK if they differ. We'll check again 3622 // during instantiation. 3623 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3624 return false; 3625 3626 // Fall through for conflicting redeclarations and redefinitions. 3627 } 3628 3629 // C: Function types need to be compatible, not identical. This handles 3630 // duplicate function decls like "void f(int); void f(enum X);" properly. 3631 if (!getLangOpts().CPlusPlus && 3632 Context.typesAreCompatible(OldQType, NewQType)) { 3633 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3634 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3635 const FunctionProtoType *OldProto = nullptr; 3636 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3637 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3638 // The old declaration provided a function prototype, but the 3639 // new declaration does not. Merge in the prototype. 3640 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3641 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3642 NewQType = 3643 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3644 OldProto->getExtProtoInfo()); 3645 New->setType(NewQType); 3646 New->setHasInheritedPrototype(); 3647 3648 // Synthesize parameters with the same types. 3649 SmallVector<ParmVarDecl*, 16> Params; 3650 for (const auto &ParamType : OldProto->param_types()) { 3651 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3652 SourceLocation(), nullptr, 3653 ParamType, /*TInfo=*/nullptr, 3654 SC_None, nullptr); 3655 Param->setScopeInfo(0, Params.size()); 3656 Param->setImplicit(); 3657 Params.push_back(Param); 3658 } 3659 3660 New->setParams(Params); 3661 } 3662 3663 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3664 } 3665 3666 // Check if the function types are compatible when pointer size address 3667 // spaces are ignored. 3668 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3669 return false; 3670 3671 // GNU C permits a K&R definition to follow a prototype declaration 3672 // if the declared types of the parameters in the K&R definition 3673 // match the types in the prototype declaration, even when the 3674 // promoted types of the parameters from the K&R definition differ 3675 // from the types in the prototype. GCC then keeps the types from 3676 // the prototype. 3677 // 3678 // If a variadic prototype is followed by a non-variadic K&R definition, 3679 // the K&R definition becomes variadic. This is sort of an edge case, but 3680 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3681 // C99 6.9.1p8. 3682 if (!getLangOpts().CPlusPlus && 3683 Old->hasPrototype() && !New->hasPrototype() && 3684 New->getType()->getAs<FunctionProtoType>() && 3685 Old->getNumParams() == New->getNumParams()) { 3686 SmallVector<QualType, 16> ArgTypes; 3687 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3688 const FunctionProtoType *OldProto 3689 = Old->getType()->getAs<FunctionProtoType>(); 3690 const FunctionProtoType *NewProto 3691 = New->getType()->getAs<FunctionProtoType>(); 3692 3693 // Determine whether this is the GNU C extension. 3694 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3695 NewProto->getReturnType()); 3696 bool LooseCompatible = !MergedReturn.isNull(); 3697 for (unsigned Idx = 0, End = Old->getNumParams(); 3698 LooseCompatible && Idx != End; ++Idx) { 3699 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3700 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3701 if (Context.typesAreCompatible(OldParm->getType(), 3702 NewProto->getParamType(Idx))) { 3703 ArgTypes.push_back(NewParm->getType()); 3704 } else if (Context.typesAreCompatible(OldParm->getType(), 3705 NewParm->getType(), 3706 /*CompareUnqualified=*/true)) { 3707 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3708 NewProto->getParamType(Idx) }; 3709 Warnings.push_back(Warn); 3710 ArgTypes.push_back(NewParm->getType()); 3711 } else 3712 LooseCompatible = false; 3713 } 3714 3715 if (LooseCompatible) { 3716 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3717 Diag(Warnings[Warn].NewParm->getLocation(), 3718 diag::ext_param_promoted_not_compatible_with_prototype) 3719 << Warnings[Warn].PromotedType 3720 << Warnings[Warn].OldParm->getType(); 3721 if (Warnings[Warn].OldParm->getLocation().isValid()) 3722 Diag(Warnings[Warn].OldParm->getLocation(), 3723 diag::note_previous_declaration); 3724 } 3725 3726 if (MergeTypeWithOld) 3727 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3728 OldProto->getExtProtoInfo())); 3729 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3730 } 3731 3732 // Fall through to diagnose conflicting types. 3733 } 3734 3735 // A function that has already been declared has been redeclared or 3736 // defined with a different type; show an appropriate diagnostic. 3737 3738 // If the previous declaration was an implicitly-generated builtin 3739 // declaration, then at the very least we should use a specialized note. 3740 unsigned BuiltinID; 3741 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3742 // If it's actually a library-defined builtin function like 'malloc' 3743 // or 'printf', just warn about the incompatible redeclaration. 3744 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3745 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3746 Diag(OldLocation, diag::note_previous_builtin_declaration) 3747 << Old << Old->getType(); 3748 3749 // If this is a global redeclaration, just forget hereafter 3750 // about the "builtin-ness" of the function. 3751 // 3752 // Doing this for local extern declarations is problematic. If 3753 // the builtin declaration remains visible, a second invalid 3754 // local declaration will produce a hard error; if it doesn't 3755 // remain visible, a single bogus local redeclaration (which is 3756 // actually only a warning) could break all the downstream code. 3757 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3758 New->getIdentifier()->revertBuiltin(); 3759 3760 return false; 3761 } 3762 3763 PrevDiag = diag::note_previous_builtin_declaration; 3764 } 3765 3766 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3767 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3768 return true; 3769 } 3770 3771 /// Completes the merge of two function declarations that are 3772 /// known to be compatible. 3773 /// 3774 /// This routine handles the merging of attributes and other 3775 /// properties of function declarations from the old declaration to 3776 /// the new declaration, once we know that New is in fact a 3777 /// redeclaration of Old. 3778 /// 3779 /// \returns false 3780 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3781 Scope *S, bool MergeTypeWithOld) { 3782 // Merge the attributes 3783 mergeDeclAttributes(New, Old); 3784 3785 // Merge "pure" flag. 3786 if (Old->isPure()) 3787 New->setPure(); 3788 3789 // Merge "used" flag. 3790 if (Old->getMostRecentDecl()->isUsed(false)) 3791 New->setIsUsed(); 3792 3793 // Merge attributes from the parameters. These can mismatch with K&R 3794 // declarations. 3795 if (New->getNumParams() == Old->getNumParams()) 3796 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3797 ParmVarDecl *NewParam = New->getParamDecl(i); 3798 ParmVarDecl *OldParam = Old->getParamDecl(i); 3799 mergeParamDeclAttributes(NewParam, OldParam, *this); 3800 mergeParamDeclTypes(NewParam, OldParam, *this); 3801 } 3802 3803 if (getLangOpts().CPlusPlus) 3804 return MergeCXXFunctionDecl(New, Old, S); 3805 3806 // Merge the function types so the we get the composite types for the return 3807 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3808 // was visible. 3809 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3810 if (!Merged.isNull() && MergeTypeWithOld) 3811 New->setType(Merged); 3812 3813 return false; 3814 } 3815 3816 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3817 ObjCMethodDecl *oldMethod) { 3818 // Merge the attributes, including deprecated/unavailable 3819 AvailabilityMergeKind MergeKind = 3820 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3821 ? AMK_ProtocolImplementation 3822 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3823 : AMK_Override; 3824 3825 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3826 3827 // Merge attributes from the parameters. 3828 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3829 oe = oldMethod->param_end(); 3830 for (ObjCMethodDecl::param_iterator 3831 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3832 ni != ne && oi != oe; ++ni, ++oi) 3833 mergeParamDeclAttributes(*ni, *oi, *this); 3834 3835 CheckObjCMethodOverride(newMethod, oldMethod); 3836 } 3837 3838 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3839 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3840 3841 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3842 ? diag::err_redefinition_different_type 3843 : diag::err_redeclaration_different_type) 3844 << New->getDeclName() << New->getType() << Old->getType(); 3845 3846 diag::kind PrevDiag; 3847 SourceLocation OldLocation; 3848 std::tie(PrevDiag, OldLocation) 3849 = getNoteDiagForInvalidRedeclaration(Old, New); 3850 S.Diag(OldLocation, PrevDiag); 3851 New->setInvalidDecl(); 3852 } 3853 3854 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3855 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3856 /// emitting diagnostics as appropriate. 3857 /// 3858 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3859 /// to here in AddInitializerToDecl. We can't check them before the initializer 3860 /// is attached. 3861 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3862 bool MergeTypeWithOld) { 3863 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3864 return; 3865 3866 QualType MergedT; 3867 if (getLangOpts().CPlusPlus) { 3868 if (New->getType()->isUndeducedType()) { 3869 // We don't know what the new type is until the initializer is attached. 3870 return; 3871 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3872 // These could still be something that needs exception specs checked. 3873 return MergeVarDeclExceptionSpecs(New, Old); 3874 } 3875 // C++ [basic.link]p10: 3876 // [...] the types specified by all declarations referring to a given 3877 // object or function shall be identical, except that declarations for an 3878 // array object can specify array types that differ by the presence or 3879 // absence of a major array bound (8.3.4). 3880 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3882 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3883 3884 // We are merging a variable declaration New into Old. If it has an array 3885 // bound, and that bound differs from Old's bound, we should diagnose the 3886 // mismatch. 3887 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3888 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3889 PrevVD = PrevVD->getPreviousDecl()) { 3890 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3891 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3892 continue; 3893 3894 if (!Context.hasSameType(NewArray, PrevVDTy)) 3895 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3896 } 3897 } 3898 3899 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3900 if (Context.hasSameType(OldArray->getElementType(), 3901 NewArray->getElementType())) 3902 MergedT = New->getType(); 3903 } 3904 // FIXME: Check visibility. New is hidden but has a complete type. If New 3905 // has no array bound, it should not inherit one from Old, if Old is not 3906 // visible. 3907 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3908 if (Context.hasSameType(OldArray->getElementType(), 3909 NewArray->getElementType())) 3910 MergedT = Old->getType(); 3911 } 3912 } 3913 else if (New->getType()->isObjCObjectPointerType() && 3914 Old->getType()->isObjCObjectPointerType()) { 3915 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3916 Old->getType()); 3917 } 3918 } else { 3919 // C 6.2.7p2: 3920 // All declarations that refer to the same object or function shall have 3921 // compatible type. 3922 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3923 } 3924 if (MergedT.isNull()) { 3925 // It's OK if we couldn't merge types if either type is dependent, for a 3926 // block-scope variable. In other cases (static data members of class 3927 // templates, variable templates, ...), we require the types to be 3928 // equivalent. 3929 // FIXME: The C++ standard doesn't say anything about this. 3930 if ((New->getType()->isDependentType() || 3931 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3932 // If the old type was dependent, we can't merge with it, so the new type 3933 // becomes dependent for now. We'll reproduce the original type when we 3934 // instantiate the TypeSourceInfo for the variable. 3935 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3936 New->setType(Context.DependentTy); 3937 return; 3938 } 3939 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3940 } 3941 3942 // Don't actually update the type on the new declaration if the old 3943 // declaration was an extern declaration in a different scope. 3944 if (MergeTypeWithOld) 3945 New->setType(MergedT); 3946 } 3947 3948 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3949 LookupResult &Previous) { 3950 // C11 6.2.7p4: 3951 // For an identifier with internal or external linkage declared 3952 // in a scope in which a prior declaration of that identifier is 3953 // visible, if the prior declaration specifies internal or 3954 // external linkage, the type of the identifier at the later 3955 // declaration becomes the composite type. 3956 // 3957 // If the variable isn't visible, we do not merge with its type. 3958 if (Previous.isShadowed()) 3959 return false; 3960 3961 if (S.getLangOpts().CPlusPlus) { 3962 // C++11 [dcl.array]p3: 3963 // If there is a preceding declaration of the entity in the same 3964 // scope in which the bound was specified, an omitted array bound 3965 // is taken to be the same as in that earlier declaration. 3966 return NewVD->isPreviousDeclInSameBlockScope() || 3967 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3968 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3969 } else { 3970 // If the old declaration was function-local, don't merge with its 3971 // type unless we're in the same function. 3972 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3973 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3974 } 3975 } 3976 3977 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3978 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3979 /// situation, merging decls or emitting diagnostics as appropriate. 3980 /// 3981 /// Tentative definition rules (C99 6.9.2p2) are checked by 3982 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3983 /// definitions here, since the initializer hasn't been attached. 3984 /// 3985 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3986 // If the new decl is already invalid, don't do any other checking. 3987 if (New->isInvalidDecl()) 3988 return; 3989 3990 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3991 return; 3992 3993 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3994 3995 // Verify the old decl was also a variable or variable template. 3996 VarDecl *Old = nullptr; 3997 VarTemplateDecl *OldTemplate = nullptr; 3998 if (Previous.isSingleResult()) { 3999 if (NewTemplate) { 4000 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4001 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4002 4003 if (auto *Shadow = 4004 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4005 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4006 return New->setInvalidDecl(); 4007 } else { 4008 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4009 4010 if (auto *Shadow = 4011 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4012 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4013 return New->setInvalidDecl(); 4014 } 4015 } 4016 if (!Old) { 4017 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4018 << New->getDeclName(); 4019 notePreviousDefinition(Previous.getRepresentativeDecl(), 4020 New->getLocation()); 4021 return New->setInvalidDecl(); 4022 } 4023 4024 // Ensure the template parameters are compatible. 4025 if (NewTemplate && 4026 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4027 OldTemplate->getTemplateParameters(), 4028 /*Complain=*/true, TPL_TemplateMatch)) 4029 return New->setInvalidDecl(); 4030 4031 // C++ [class.mem]p1: 4032 // A member shall not be declared twice in the member-specification [...] 4033 // 4034 // Here, we need only consider static data members. 4035 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4036 Diag(New->getLocation(), diag::err_duplicate_member) 4037 << New->getIdentifier(); 4038 Diag(Old->getLocation(), diag::note_previous_declaration); 4039 New->setInvalidDecl(); 4040 } 4041 4042 mergeDeclAttributes(New, Old); 4043 // Warn if an already-declared variable is made a weak_import in a subsequent 4044 // declaration 4045 if (New->hasAttr<WeakImportAttr>() && 4046 Old->getStorageClass() == SC_None && 4047 !Old->hasAttr<WeakImportAttr>()) { 4048 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4049 notePreviousDefinition(Old, New->getLocation()); 4050 // Remove weak_import attribute on new declaration. 4051 New->dropAttr<WeakImportAttr>(); 4052 } 4053 4054 if (New->hasAttr<InternalLinkageAttr>() && 4055 !Old->hasAttr<InternalLinkageAttr>()) { 4056 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4057 << New->getDeclName(); 4058 notePreviousDefinition(Old, New->getLocation()); 4059 New->dropAttr<InternalLinkageAttr>(); 4060 } 4061 4062 // Merge the types. 4063 VarDecl *MostRecent = Old->getMostRecentDecl(); 4064 if (MostRecent != Old) { 4065 MergeVarDeclTypes(New, MostRecent, 4066 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4067 if (New->isInvalidDecl()) 4068 return; 4069 } 4070 4071 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4072 if (New->isInvalidDecl()) 4073 return; 4074 4075 diag::kind PrevDiag; 4076 SourceLocation OldLocation; 4077 std::tie(PrevDiag, OldLocation) = 4078 getNoteDiagForInvalidRedeclaration(Old, New); 4079 4080 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4081 if (New->getStorageClass() == SC_Static && 4082 !New->isStaticDataMember() && 4083 Old->hasExternalFormalLinkage()) { 4084 if (getLangOpts().MicrosoftExt) { 4085 Diag(New->getLocation(), diag::ext_static_non_static) 4086 << New->getDeclName(); 4087 Diag(OldLocation, PrevDiag); 4088 } else { 4089 Diag(New->getLocation(), diag::err_static_non_static) 4090 << New->getDeclName(); 4091 Diag(OldLocation, PrevDiag); 4092 return New->setInvalidDecl(); 4093 } 4094 } 4095 // C99 6.2.2p4: 4096 // For an identifier declared with the storage-class specifier 4097 // extern in a scope in which a prior declaration of that 4098 // identifier is visible,23) if the prior declaration specifies 4099 // internal or external linkage, the linkage of the identifier at 4100 // the later declaration is the same as the linkage specified at 4101 // the prior declaration. If no prior declaration is visible, or 4102 // if the prior declaration specifies no linkage, then the 4103 // identifier has external linkage. 4104 if (New->hasExternalStorage() && Old->hasLinkage()) 4105 /* Okay */; 4106 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4107 !New->isStaticDataMember() && 4108 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4109 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4110 Diag(OldLocation, PrevDiag); 4111 return New->setInvalidDecl(); 4112 } 4113 4114 // Check if extern is followed by non-extern and vice-versa. 4115 if (New->hasExternalStorage() && 4116 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4117 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4118 Diag(OldLocation, PrevDiag); 4119 return New->setInvalidDecl(); 4120 } 4121 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4122 !New->hasExternalStorage()) { 4123 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4124 Diag(OldLocation, PrevDiag); 4125 return New->setInvalidDecl(); 4126 } 4127 4128 if (CheckRedeclarationModuleOwnership(New, Old)) 4129 return; 4130 4131 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4132 4133 // FIXME: The test for external storage here seems wrong? We still 4134 // need to check for mismatches. 4135 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4136 // Don't complain about out-of-line definitions of static members. 4137 !(Old->getLexicalDeclContext()->isRecord() && 4138 !New->getLexicalDeclContext()->isRecord())) { 4139 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4140 Diag(OldLocation, PrevDiag); 4141 return New->setInvalidDecl(); 4142 } 4143 4144 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4145 if (VarDecl *Def = Old->getDefinition()) { 4146 // C++1z [dcl.fcn.spec]p4: 4147 // If the definition of a variable appears in a translation unit before 4148 // its first declaration as inline, the program is ill-formed. 4149 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4150 Diag(Def->getLocation(), diag::note_previous_definition); 4151 } 4152 } 4153 4154 // If this redeclaration makes the variable inline, we may need to add it to 4155 // UndefinedButUsed. 4156 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4157 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4158 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4159 SourceLocation())); 4160 4161 if (New->getTLSKind() != Old->getTLSKind()) { 4162 if (!Old->getTLSKind()) { 4163 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4164 Diag(OldLocation, PrevDiag); 4165 } else if (!New->getTLSKind()) { 4166 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4167 Diag(OldLocation, PrevDiag); 4168 } else { 4169 // Do not allow redeclaration to change the variable between requiring 4170 // static and dynamic initialization. 4171 // FIXME: GCC allows this, but uses the TLS keyword on the first 4172 // declaration to determine the kind. Do we need to be compatible here? 4173 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4174 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4175 Diag(OldLocation, PrevDiag); 4176 } 4177 } 4178 4179 // C++ doesn't have tentative definitions, so go right ahead and check here. 4180 if (getLangOpts().CPlusPlus && 4181 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4182 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4183 Old->getCanonicalDecl()->isConstexpr()) { 4184 // This definition won't be a definition any more once it's been merged. 4185 Diag(New->getLocation(), 4186 diag::warn_deprecated_redundant_constexpr_static_def); 4187 } else if (VarDecl *Def = Old->getDefinition()) { 4188 if (checkVarDeclRedefinition(Def, New)) 4189 return; 4190 } 4191 } 4192 4193 if (haveIncompatibleLanguageLinkages(Old, New)) { 4194 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4195 Diag(OldLocation, PrevDiag); 4196 New->setInvalidDecl(); 4197 return; 4198 } 4199 4200 // Merge "used" flag. 4201 if (Old->getMostRecentDecl()->isUsed(false)) 4202 New->setIsUsed(); 4203 4204 // Keep a chain of previous declarations. 4205 New->setPreviousDecl(Old); 4206 if (NewTemplate) 4207 NewTemplate->setPreviousDecl(OldTemplate); 4208 adjustDeclContextForDeclaratorDecl(New, Old); 4209 4210 // Inherit access appropriately. 4211 New->setAccess(Old->getAccess()); 4212 if (NewTemplate) 4213 NewTemplate->setAccess(New->getAccess()); 4214 4215 if (Old->isInline()) 4216 New->setImplicitlyInline(); 4217 } 4218 4219 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4220 SourceManager &SrcMgr = getSourceManager(); 4221 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4222 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4223 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4224 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4225 auto &HSI = PP.getHeaderSearchInfo(); 4226 StringRef HdrFilename = 4227 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4228 4229 auto noteFromModuleOrInclude = [&](Module *Mod, 4230 SourceLocation IncLoc) -> bool { 4231 // Redefinition errors with modules are common with non modular mapped 4232 // headers, example: a non-modular header H in module A that also gets 4233 // included directly in a TU. Pointing twice to the same header/definition 4234 // is confusing, try to get better diagnostics when modules is on. 4235 if (IncLoc.isValid()) { 4236 if (Mod) { 4237 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4238 << HdrFilename.str() << Mod->getFullModuleName(); 4239 if (!Mod->DefinitionLoc.isInvalid()) 4240 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4241 << Mod->getFullModuleName(); 4242 } else { 4243 Diag(IncLoc, diag::note_redefinition_include_same_file) 4244 << HdrFilename.str(); 4245 } 4246 return true; 4247 } 4248 4249 return false; 4250 }; 4251 4252 // Is it the same file and same offset? Provide more information on why 4253 // this leads to a redefinition error. 4254 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4255 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4256 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4257 bool EmittedDiag = 4258 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4259 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4260 4261 // If the header has no guards, emit a note suggesting one. 4262 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4263 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4264 4265 if (EmittedDiag) 4266 return; 4267 } 4268 4269 // Redefinition coming from different files or couldn't do better above. 4270 if (Old->getLocation().isValid()) 4271 Diag(Old->getLocation(), diag::note_previous_definition); 4272 } 4273 4274 /// We've just determined that \p Old and \p New both appear to be definitions 4275 /// of the same variable. Either diagnose or fix the problem. 4276 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4277 if (!hasVisibleDefinition(Old) && 4278 (New->getFormalLinkage() == InternalLinkage || 4279 New->isInline() || 4280 New->getDescribedVarTemplate() || 4281 New->getNumTemplateParameterLists() || 4282 New->getDeclContext()->isDependentContext())) { 4283 // The previous definition is hidden, and multiple definitions are 4284 // permitted (in separate TUs). Demote this to a declaration. 4285 New->demoteThisDefinitionToDeclaration(); 4286 4287 // Make the canonical definition visible. 4288 if (auto *OldTD = Old->getDescribedVarTemplate()) 4289 makeMergedDefinitionVisible(OldTD); 4290 makeMergedDefinitionVisible(Old); 4291 return false; 4292 } else { 4293 Diag(New->getLocation(), diag::err_redefinition) << New; 4294 notePreviousDefinition(Old, New->getLocation()); 4295 New->setInvalidDecl(); 4296 return true; 4297 } 4298 } 4299 4300 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4301 /// no declarator (e.g. "struct foo;") is parsed. 4302 Decl * 4303 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4304 RecordDecl *&AnonRecord) { 4305 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4306 AnonRecord); 4307 } 4308 4309 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4310 // disambiguate entities defined in different scopes. 4311 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4312 // compatibility. 4313 // We will pick our mangling number depending on which version of MSVC is being 4314 // targeted. 4315 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4316 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4317 ? S->getMSCurManglingNumber() 4318 : S->getMSLastManglingNumber(); 4319 } 4320 4321 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4322 if (!Context.getLangOpts().CPlusPlus) 4323 return; 4324 4325 if (isa<CXXRecordDecl>(Tag->getParent())) { 4326 // If this tag is the direct child of a class, number it if 4327 // it is anonymous. 4328 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4329 return; 4330 MangleNumberingContext &MCtx = 4331 Context.getManglingNumberContext(Tag->getParent()); 4332 Context.setManglingNumber( 4333 Tag, MCtx.getManglingNumber( 4334 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4335 return; 4336 } 4337 4338 // If this tag isn't a direct child of a class, number it if it is local. 4339 MangleNumberingContext *MCtx; 4340 Decl *ManglingContextDecl; 4341 std::tie(MCtx, ManglingContextDecl) = 4342 getCurrentMangleNumberContext(Tag->getDeclContext()); 4343 if (MCtx) { 4344 Context.setManglingNumber( 4345 Tag, MCtx->getManglingNumber( 4346 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4347 } 4348 } 4349 4350 namespace { 4351 struct NonCLikeKind { 4352 enum { 4353 None, 4354 BaseClass, 4355 DefaultMemberInit, 4356 Lambda, 4357 Friend, 4358 OtherMember, 4359 Invalid, 4360 } Kind = None; 4361 SourceRange Range; 4362 4363 explicit operator bool() { return Kind != None; } 4364 }; 4365 } 4366 4367 /// Determine whether a class is C-like, according to the rules of C++ 4368 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4369 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4370 if (RD->isInvalidDecl()) 4371 return {NonCLikeKind::Invalid, {}}; 4372 4373 // C++ [dcl.typedef]p9: [P1766R1] 4374 // An unnamed class with a typedef name for linkage purposes shall not 4375 // 4376 // -- have any base classes 4377 if (RD->getNumBases()) 4378 return {NonCLikeKind::BaseClass, 4379 SourceRange(RD->bases_begin()->getBeginLoc(), 4380 RD->bases_end()[-1].getEndLoc())}; 4381 bool Invalid = false; 4382 for (Decl *D : RD->decls()) { 4383 // Don't complain about things we already diagnosed. 4384 if (D->isInvalidDecl()) { 4385 Invalid = true; 4386 continue; 4387 } 4388 4389 // -- have any [...] default member initializers 4390 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4391 if (FD->hasInClassInitializer()) { 4392 auto *Init = FD->getInClassInitializer(); 4393 return {NonCLikeKind::DefaultMemberInit, 4394 Init ? Init->getSourceRange() : D->getSourceRange()}; 4395 } 4396 continue; 4397 } 4398 4399 // FIXME: We don't allow friend declarations. This violates the wording of 4400 // P1766, but not the intent. 4401 if (isa<FriendDecl>(D)) 4402 return {NonCLikeKind::Friend, D->getSourceRange()}; 4403 4404 // -- declare any members other than non-static data members, member 4405 // enumerations, or member classes, 4406 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4407 isa<EnumDecl>(D)) 4408 continue; 4409 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4410 if (!MemberRD) 4411 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4412 4413 // -- contain a lambda-expression, 4414 if (MemberRD->isLambda()) 4415 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4416 4417 // and all member classes shall also satisfy these requirements 4418 // (recursively). 4419 if (MemberRD->isThisDeclarationADefinition()) { 4420 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4421 return Kind; 4422 } 4423 } 4424 4425 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4426 } 4427 4428 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4429 TypedefNameDecl *NewTD) { 4430 if (TagFromDeclSpec->isInvalidDecl()) 4431 return; 4432 4433 // Do nothing if the tag already has a name for linkage purposes. 4434 if (TagFromDeclSpec->hasNameForLinkage()) 4435 return; 4436 4437 // A well-formed anonymous tag must always be a TUK_Definition. 4438 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4439 4440 // The type must match the tag exactly; no qualifiers allowed. 4441 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4442 Context.getTagDeclType(TagFromDeclSpec))) { 4443 if (getLangOpts().CPlusPlus) 4444 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4445 return; 4446 } 4447 4448 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4449 // An unnamed class with a typedef name for linkage purposes shall [be 4450 // C-like]. 4451 // 4452 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4453 // shouldn't happen, but there are constructs that the language rule doesn't 4454 // disallow for which we can't reasonably avoid computing linkage early. 4455 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4456 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4457 : NonCLikeKind(); 4458 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4459 if (NonCLike || ChangesLinkage) { 4460 if (NonCLike.Kind == NonCLikeKind::Invalid) 4461 return; 4462 4463 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4464 if (ChangesLinkage) { 4465 // If the linkage changes, we can't accept this as an extension. 4466 if (NonCLike.Kind == NonCLikeKind::None) 4467 DiagID = diag::err_typedef_changes_linkage; 4468 else 4469 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4470 } 4471 4472 SourceLocation FixitLoc = 4473 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4474 llvm::SmallString<40> TextToInsert; 4475 TextToInsert += ' '; 4476 TextToInsert += NewTD->getIdentifier()->getName(); 4477 4478 Diag(FixitLoc, DiagID) 4479 << isa<TypeAliasDecl>(NewTD) 4480 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4481 if (NonCLike.Kind != NonCLikeKind::None) { 4482 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4483 << NonCLike.Kind - 1 << NonCLike.Range; 4484 } 4485 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4486 << NewTD << isa<TypeAliasDecl>(NewTD); 4487 4488 if (ChangesLinkage) 4489 return; 4490 } 4491 4492 // Otherwise, set this as the anon-decl typedef for the tag. 4493 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4494 } 4495 4496 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4497 switch (T) { 4498 case DeclSpec::TST_class: 4499 return 0; 4500 case DeclSpec::TST_struct: 4501 return 1; 4502 case DeclSpec::TST_interface: 4503 return 2; 4504 case DeclSpec::TST_union: 4505 return 3; 4506 case DeclSpec::TST_enum: 4507 return 4; 4508 default: 4509 llvm_unreachable("unexpected type specifier"); 4510 } 4511 } 4512 4513 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4514 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4515 /// parameters to cope with template friend declarations. 4516 Decl * 4517 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4518 MultiTemplateParamsArg TemplateParams, 4519 bool IsExplicitInstantiation, 4520 RecordDecl *&AnonRecord) { 4521 Decl *TagD = nullptr; 4522 TagDecl *Tag = nullptr; 4523 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4524 DS.getTypeSpecType() == DeclSpec::TST_struct || 4525 DS.getTypeSpecType() == DeclSpec::TST_interface || 4526 DS.getTypeSpecType() == DeclSpec::TST_union || 4527 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4528 TagD = DS.getRepAsDecl(); 4529 4530 if (!TagD) // We probably had an error 4531 return nullptr; 4532 4533 // Note that the above type specs guarantee that the 4534 // type rep is a Decl, whereas in many of the others 4535 // it's a Type. 4536 if (isa<TagDecl>(TagD)) 4537 Tag = cast<TagDecl>(TagD); 4538 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4539 Tag = CTD->getTemplatedDecl(); 4540 } 4541 4542 if (Tag) { 4543 handleTagNumbering(Tag, S); 4544 Tag->setFreeStanding(); 4545 if (Tag->isInvalidDecl()) 4546 return Tag; 4547 } 4548 4549 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4550 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4551 // or incomplete types shall not be restrict-qualified." 4552 if (TypeQuals & DeclSpec::TQ_restrict) 4553 Diag(DS.getRestrictSpecLoc(), 4554 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4555 << DS.getSourceRange(); 4556 } 4557 4558 if (DS.isInlineSpecified()) 4559 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4560 << getLangOpts().CPlusPlus17; 4561 4562 if (DS.hasConstexprSpecifier()) { 4563 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4564 // and definitions of functions and variables. 4565 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4566 // the declaration of a function or function template 4567 if (Tag) 4568 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4569 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4570 << DS.getConstexprSpecifier(); 4571 else 4572 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4573 << DS.getConstexprSpecifier(); 4574 // Don't emit warnings after this error. 4575 return TagD; 4576 } 4577 4578 DiagnoseFunctionSpecifiers(DS); 4579 4580 if (DS.isFriendSpecified()) { 4581 // If we're dealing with a decl but not a TagDecl, assume that 4582 // whatever routines created it handled the friendship aspect. 4583 if (TagD && !Tag) 4584 return nullptr; 4585 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4586 } 4587 4588 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4589 bool IsExplicitSpecialization = 4590 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4591 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4592 !IsExplicitInstantiation && !IsExplicitSpecialization && 4593 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4594 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4595 // nested-name-specifier unless it is an explicit instantiation 4596 // or an explicit specialization. 4597 // 4598 // FIXME: We allow class template partial specializations here too, per the 4599 // obvious intent of DR1819. 4600 // 4601 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4602 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4603 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4604 return nullptr; 4605 } 4606 4607 // Track whether this decl-specifier declares anything. 4608 bool DeclaresAnything = true; 4609 4610 // Handle anonymous struct definitions. 4611 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4612 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4613 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4614 if (getLangOpts().CPlusPlus || 4615 Record->getDeclContext()->isRecord()) { 4616 // If CurContext is a DeclContext that can contain statements, 4617 // RecursiveASTVisitor won't visit the decls that 4618 // BuildAnonymousStructOrUnion() will put into CurContext. 4619 // Also store them here so that they can be part of the 4620 // DeclStmt that gets created in this case. 4621 // FIXME: Also return the IndirectFieldDecls created by 4622 // BuildAnonymousStructOr union, for the same reason? 4623 if (CurContext->isFunctionOrMethod()) 4624 AnonRecord = Record; 4625 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4626 Context.getPrintingPolicy()); 4627 } 4628 4629 DeclaresAnything = false; 4630 } 4631 } 4632 4633 // C11 6.7.2.1p2: 4634 // A struct-declaration that does not declare an anonymous structure or 4635 // anonymous union shall contain a struct-declarator-list. 4636 // 4637 // This rule also existed in C89 and C99; the grammar for struct-declaration 4638 // did not permit a struct-declaration without a struct-declarator-list. 4639 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4640 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4641 // Check for Microsoft C extension: anonymous struct/union member. 4642 // Handle 2 kinds of anonymous struct/union: 4643 // struct STRUCT; 4644 // union UNION; 4645 // and 4646 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4647 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4648 if ((Tag && Tag->getDeclName()) || 4649 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4650 RecordDecl *Record = nullptr; 4651 if (Tag) 4652 Record = dyn_cast<RecordDecl>(Tag); 4653 else if (const RecordType *RT = 4654 DS.getRepAsType().get()->getAsStructureType()) 4655 Record = RT->getDecl(); 4656 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4657 Record = UT->getDecl(); 4658 4659 if (Record && getLangOpts().MicrosoftExt) { 4660 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4661 << Record->isUnion() << DS.getSourceRange(); 4662 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4663 } 4664 4665 DeclaresAnything = false; 4666 } 4667 } 4668 4669 // Skip all the checks below if we have a type error. 4670 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4671 (TagD && TagD->isInvalidDecl())) 4672 return TagD; 4673 4674 if (getLangOpts().CPlusPlus && 4675 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4676 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4677 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4678 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4679 DeclaresAnything = false; 4680 4681 if (!DS.isMissingDeclaratorOk()) { 4682 // Customize diagnostic for a typedef missing a name. 4683 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4684 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4685 << DS.getSourceRange(); 4686 else 4687 DeclaresAnything = false; 4688 } 4689 4690 if (DS.isModulePrivateSpecified() && 4691 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4692 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4693 << Tag->getTagKind() 4694 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4695 4696 ActOnDocumentableDecl(TagD); 4697 4698 // C 6.7/2: 4699 // A declaration [...] shall declare at least a declarator [...], a tag, 4700 // or the members of an enumeration. 4701 // C++ [dcl.dcl]p3: 4702 // [If there are no declarators], and except for the declaration of an 4703 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4704 // names into the program, or shall redeclare a name introduced by a 4705 // previous declaration. 4706 if (!DeclaresAnything) { 4707 // In C, we allow this as a (popular) extension / bug. Don't bother 4708 // producing further diagnostics for redundant qualifiers after this. 4709 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4710 return TagD; 4711 } 4712 4713 // C++ [dcl.stc]p1: 4714 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4715 // init-declarator-list of the declaration shall not be empty. 4716 // C++ [dcl.fct.spec]p1: 4717 // If a cv-qualifier appears in a decl-specifier-seq, the 4718 // init-declarator-list of the declaration shall not be empty. 4719 // 4720 // Spurious qualifiers here appear to be valid in C. 4721 unsigned DiagID = diag::warn_standalone_specifier; 4722 if (getLangOpts().CPlusPlus) 4723 DiagID = diag::ext_standalone_specifier; 4724 4725 // Note that a linkage-specification sets a storage class, but 4726 // 'extern "C" struct foo;' is actually valid and not theoretically 4727 // useless. 4728 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4729 if (SCS == DeclSpec::SCS_mutable) 4730 // Since mutable is not a viable storage class specifier in C, there is 4731 // no reason to treat it as an extension. Instead, diagnose as an error. 4732 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4733 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4734 Diag(DS.getStorageClassSpecLoc(), DiagID) 4735 << DeclSpec::getSpecifierName(SCS); 4736 } 4737 4738 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4739 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4740 << DeclSpec::getSpecifierName(TSCS); 4741 if (DS.getTypeQualifiers()) { 4742 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4743 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4744 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4745 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4746 // Restrict is covered above. 4747 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4748 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4749 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4750 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4751 } 4752 4753 // Warn about ignored type attributes, for example: 4754 // __attribute__((aligned)) struct A; 4755 // Attributes should be placed after tag to apply to type declaration. 4756 if (!DS.getAttributes().empty()) { 4757 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4758 if (TypeSpecType == DeclSpec::TST_class || 4759 TypeSpecType == DeclSpec::TST_struct || 4760 TypeSpecType == DeclSpec::TST_interface || 4761 TypeSpecType == DeclSpec::TST_union || 4762 TypeSpecType == DeclSpec::TST_enum) { 4763 for (const ParsedAttr &AL : DS.getAttributes()) 4764 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4765 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4766 } 4767 } 4768 4769 return TagD; 4770 } 4771 4772 /// We are trying to inject an anonymous member into the given scope; 4773 /// check if there's an existing declaration that can't be overloaded. 4774 /// 4775 /// \return true if this is a forbidden redeclaration 4776 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4777 Scope *S, 4778 DeclContext *Owner, 4779 DeclarationName Name, 4780 SourceLocation NameLoc, 4781 bool IsUnion) { 4782 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4783 Sema::ForVisibleRedeclaration); 4784 if (!SemaRef.LookupName(R, S)) return false; 4785 4786 // Pick a representative declaration. 4787 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4788 assert(PrevDecl && "Expected a non-null Decl"); 4789 4790 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4791 return false; 4792 4793 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4794 << IsUnion << Name; 4795 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4796 4797 return true; 4798 } 4799 4800 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4801 /// anonymous struct or union AnonRecord into the owning context Owner 4802 /// and scope S. This routine will be invoked just after we realize 4803 /// that an unnamed union or struct is actually an anonymous union or 4804 /// struct, e.g., 4805 /// 4806 /// @code 4807 /// union { 4808 /// int i; 4809 /// float f; 4810 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4811 /// // f into the surrounding scope.x 4812 /// @endcode 4813 /// 4814 /// This routine is recursive, injecting the names of nested anonymous 4815 /// structs/unions into the owning context and scope as well. 4816 static bool 4817 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4818 RecordDecl *AnonRecord, AccessSpecifier AS, 4819 SmallVectorImpl<NamedDecl *> &Chaining) { 4820 bool Invalid = false; 4821 4822 // Look every FieldDecl and IndirectFieldDecl with a name. 4823 for (auto *D : AnonRecord->decls()) { 4824 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4825 cast<NamedDecl>(D)->getDeclName()) { 4826 ValueDecl *VD = cast<ValueDecl>(D); 4827 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4828 VD->getLocation(), 4829 AnonRecord->isUnion())) { 4830 // C++ [class.union]p2: 4831 // The names of the members of an anonymous union shall be 4832 // distinct from the names of any other entity in the 4833 // scope in which the anonymous union is declared. 4834 Invalid = true; 4835 } else { 4836 // C++ [class.union]p2: 4837 // For the purpose of name lookup, after the anonymous union 4838 // definition, the members of the anonymous union are 4839 // considered to have been defined in the scope in which the 4840 // anonymous union is declared. 4841 unsigned OldChainingSize = Chaining.size(); 4842 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4843 Chaining.append(IF->chain_begin(), IF->chain_end()); 4844 else 4845 Chaining.push_back(VD); 4846 4847 assert(Chaining.size() >= 2); 4848 NamedDecl **NamedChain = 4849 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4850 for (unsigned i = 0; i < Chaining.size(); i++) 4851 NamedChain[i] = Chaining[i]; 4852 4853 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4854 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4855 VD->getType(), {NamedChain, Chaining.size()}); 4856 4857 for (const auto *Attr : VD->attrs()) 4858 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4859 4860 IndirectField->setAccess(AS); 4861 IndirectField->setImplicit(); 4862 SemaRef.PushOnScopeChains(IndirectField, S); 4863 4864 // That includes picking up the appropriate access specifier. 4865 if (AS != AS_none) IndirectField->setAccess(AS); 4866 4867 Chaining.resize(OldChainingSize); 4868 } 4869 } 4870 } 4871 4872 return Invalid; 4873 } 4874 4875 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4876 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4877 /// illegal input values are mapped to SC_None. 4878 static StorageClass 4879 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4880 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4881 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4882 "Parser allowed 'typedef' as storage class VarDecl."); 4883 switch (StorageClassSpec) { 4884 case DeclSpec::SCS_unspecified: return SC_None; 4885 case DeclSpec::SCS_extern: 4886 if (DS.isExternInLinkageSpec()) 4887 return SC_None; 4888 return SC_Extern; 4889 case DeclSpec::SCS_static: return SC_Static; 4890 case DeclSpec::SCS_auto: return SC_Auto; 4891 case DeclSpec::SCS_register: return SC_Register; 4892 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4893 // Illegal SCSs map to None: error reporting is up to the caller. 4894 case DeclSpec::SCS_mutable: // Fall through. 4895 case DeclSpec::SCS_typedef: return SC_None; 4896 } 4897 llvm_unreachable("unknown storage class specifier"); 4898 } 4899 4900 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4901 assert(Record->hasInClassInitializer()); 4902 4903 for (const auto *I : Record->decls()) { 4904 const auto *FD = dyn_cast<FieldDecl>(I); 4905 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4906 FD = IFD->getAnonField(); 4907 if (FD && FD->hasInClassInitializer()) 4908 return FD->getLocation(); 4909 } 4910 4911 llvm_unreachable("couldn't find in-class initializer"); 4912 } 4913 4914 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4915 SourceLocation DefaultInitLoc) { 4916 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4917 return; 4918 4919 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4920 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4921 } 4922 4923 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4924 CXXRecordDecl *AnonUnion) { 4925 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4926 return; 4927 4928 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4929 } 4930 4931 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4932 /// anonymous structure or union. Anonymous unions are a C++ feature 4933 /// (C++ [class.union]) and a C11 feature; anonymous structures 4934 /// are a C11 feature and GNU C++ extension. 4935 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4936 AccessSpecifier AS, 4937 RecordDecl *Record, 4938 const PrintingPolicy &Policy) { 4939 DeclContext *Owner = Record->getDeclContext(); 4940 4941 // Diagnose whether this anonymous struct/union is an extension. 4942 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4943 Diag(Record->getLocation(), diag::ext_anonymous_union); 4944 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4945 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4946 else if (!Record->isUnion() && !getLangOpts().C11) 4947 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4948 4949 // C and C++ require different kinds of checks for anonymous 4950 // structs/unions. 4951 bool Invalid = false; 4952 if (getLangOpts().CPlusPlus) { 4953 const char *PrevSpec = nullptr; 4954 if (Record->isUnion()) { 4955 // C++ [class.union]p6: 4956 // C++17 [class.union.anon]p2: 4957 // Anonymous unions declared in a named namespace or in the 4958 // global namespace shall be declared static. 4959 unsigned DiagID; 4960 DeclContext *OwnerScope = Owner->getRedeclContext(); 4961 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4962 (OwnerScope->isTranslationUnit() || 4963 (OwnerScope->isNamespace() && 4964 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4965 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4966 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4967 4968 // Recover by adding 'static'. 4969 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4970 PrevSpec, DiagID, Policy); 4971 } 4972 // C++ [class.union]p6: 4973 // A storage class is not allowed in a declaration of an 4974 // anonymous union in a class scope. 4975 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4976 isa<RecordDecl>(Owner)) { 4977 Diag(DS.getStorageClassSpecLoc(), 4978 diag::err_anonymous_union_with_storage_spec) 4979 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4980 4981 // Recover by removing the storage specifier. 4982 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4983 SourceLocation(), 4984 PrevSpec, DiagID, Context.getPrintingPolicy()); 4985 } 4986 } 4987 4988 // Ignore const/volatile/restrict qualifiers. 4989 if (DS.getTypeQualifiers()) { 4990 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4991 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4992 << Record->isUnion() << "const" 4993 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4994 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4995 Diag(DS.getVolatileSpecLoc(), 4996 diag::ext_anonymous_struct_union_qualified) 4997 << Record->isUnion() << "volatile" 4998 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4999 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5000 Diag(DS.getRestrictSpecLoc(), 5001 diag::ext_anonymous_struct_union_qualified) 5002 << Record->isUnion() << "restrict" 5003 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5004 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5005 Diag(DS.getAtomicSpecLoc(), 5006 diag::ext_anonymous_struct_union_qualified) 5007 << Record->isUnion() << "_Atomic" 5008 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5009 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5010 Diag(DS.getUnalignedSpecLoc(), 5011 diag::ext_anonymous_struct_union_qualified) 5012 << Record->isUnion() << "__unaligned" 5013 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5014 5015 DS.ClearTypeQualifiers(); 5016 } 5017 5018 // C++ [class.union]p2: 5019 // The member-specification of an anonymous union shall only 5020 // define non-static data members. [Note: nested types and 5021 // functions cannot be declared within an anonymous union. ] 5022 for (auto *Mem : Record->decls()) { 5023 // Ignore invalid declarations; we already diagnosed them. 5024 if (Mem->isInvalidDecl()) 5025 continue; 5026 5027 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5028 // C++ [class.union]p3: 5029 // An anonymous union shall not have private or protected 5030 // members (clause 11). 5031 assert(FD->getAccess() != AS_none); 5032 if (FD->getAccess() != AS_public) { 5033 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5034 << Record->isUnion() << (FD->getAccess() == AS_protected); 5035 Invalid = true; 5036 } 5037 5038 // C++ [class.union]p1 5039 // An object of a class with a non-trivial constructor, a non-trivial 5040 // copy constructor, a non-trivial destructor, or a non-trivial copy 5041 // assignment operator cannot be a member of a union, nor can an 5042 // array of such objects. 5043 if (CheckNontrivialField(FD)) 5044 Invalid = true; 5045 } else if (Mem->isImplicit()) { 5046 // Any implicit members are fine. 5047 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5048 // This is a type that showed up in an 5049 // elaborated-type-specifier inside the anonymous struct or 5050 // union, but which actually declares a type outside of the 5051 // anonymous struct or union. It's okay. 5052 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5053 if (!MemRecord->isAnonymousStructOrUnion() && 5054 MemRecord->getDeclName()) { 5055 // Visual C++ allows type definition in anonymous struct or union. 5056 if (getLangOpts().MicrosoftExt) 5057 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5058 << Record->isUnion(); 5059 else { 5060 // This is a nested type declaration. 5061 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5062 << Record->isUnion(); 5063 Invalid = true; 5064 } 5065 } else { 5066 // This is an anonymous type definition within another anonymous type. 5067 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5068 // not part of standard C++. 5069 Diag(MemRecord->getLocation(), 5070 diag::ext_anonymous_record_with_anonymous_type) 5071 << Record->isUnion(); 5072 } 5073 } else if (isa<AccessSpecDecl>(Mem)) { 5074 // Any access specifier is fine. 5075 } else if (isa<StaticAssertDecl>(Mem)) { 5076 // In C++1z, static_assert declarations are also fine. 5077 } else { 5078 // We have something that isn't a non-static data 5079 // member. Complain about it. 5080 unsigned DK = diag::err_anonymous_record_bad_member; 5081 if (isa<TypeDecl>(Mem)) 5082 DK = diag::err_anonymous_record_with_type; 5083 else if (isa<FunctionDecl>(Mem)) 5084 DK = diag::err_anonymous_record_with_function; 5085 else if (isa<VarDecl>(Mem)) 5086 DK = diag::err_anonymous_record_with_static; 5087 5088 // Visual C++ allows type definition in anonymous struct or union. 5089 if (getLangOpts().MicrosoftExt && 5090 DK == diag::err_anonymous_record_with_type) 5091 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5092 << Record->isUnion(); 5093 else { 5094 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5095 Invalid = true; 5096 } 5097 } 5098 } 5099 5100 // C++11 [class.union]p8 (DR1460): 5101 // At most one variant member of a union may have a 5102 // brace-or-equal-initializer. 5103 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5104 Owner->isRecord()) 5105 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5106 cast<CXXRecordDecl>(Record)); 5107 } 5108 5109 if (!Record->isUnion() && !Owner->isRecord()) { 5110 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5111 << getLangOpts().CPlusPlus; 5112 Invalid = true; 5113 } 5114 5115 // C++ [dcl.dcl]p3: 5116 // [If there are no declarators], and except for the declaration of an 5117 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5118 // names into the program 5119 // C++ [class.mem]p2: 5120 // each such member-declaration shall either declare at least one member 5121 // name of the class or declare at least one unnamed bit-field 5122 // 5123 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5124 if (getLangOpts().CPlusPlus && Record->field_empty()) 5125 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5126 5127 // Mock up a declarator. 5128 Declarator Dc(DS, DeclaratorContext::MemberContext); 5129 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5130 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5131 5132 // Create a declaration for this anonymous struct/union. 5133 NamedDecl *Anon = nullptr; 5134 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5135 Anon = FieldDecl::Create( 5136 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5137 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5138 /*BitWidth=*/nullptr, /*Mutable=*/false, 5139 /*InitStyle=*/ICIS_NoInit); 5140 Anon->setAccess(AS); 5141 ProcessDeclAttributes(S, Anon, Dc); 5142 5143 if (getLangOpts().CPlusPlus) 5144 FieldCollector->Add(cast<FieldDecl>(Anon)); 5145 } else { 5146 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5147 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5148 if (SCSpec == DeclSpec::SCS_mutable) { 5149 // mutable can only appear on non-static class members, so it's always 5150 // an error here 5151 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5152 Invalid = true; 5153 SC = SC_None; 5154 } 5155 5156 assert(DS.getAttributes().empty() && "No attribute expected"); 5157 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5158 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5159 Context.getTypeDeclType(Record), TInfo, SC); 5160 5161 // Default-initialize the implicit variable. This initialization will be 5162 // trivial in almost all cases, except if a union member has an in-class 5163 // initializer: 5164 // union { int n = 0; }; 5165 ActOnUninitializedDecl(Anon); 5166 } 5167 Anon->setImplicit(); 5168 5169 // Mark this as an anonymous struct/union type. 5170 Record->setAnonymousStructOrUnion(true); 5171 5172 // Add the anonymous struct/union object to the current 5173 // context. We'll be referencing this object when we refer to one of 5174 // its members. 5175 Owner->addDecl(Anon); 5176 5177 // Inject the members of the anonymous struct/union into the owning 5178 // context and into the identifier resolver chain for name lookup 5179 // purposes. 5180 SmallVector<NamedDecl*, 2> Chain; 5181 Chain.push_back(Anon); 5182 5183 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5184 Invalid = true; 5185 5186 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5187 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5188 MangleNumberingContext *MCtx; 5189 Decl *ManglingContextDecl; 5190 std::tie(MCtx, ManglingContextDecl) = 5191 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5192 if (MCtx) { 5193 Context.setManglingNumber( 5194 NewVD, MCtx->getManglingNumber( 5195 NewVD, getMSManglingNumber(getLangOpts(), S))); 5196 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5197 } 5198 } 5199 } 5200 5201 if (Invalid) 5202 Anon->setInvalidDecl(); 5203 5204 return Anon; 5205 } 5206 5207 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5208 /// Microsoft C anonymous structure. 5209 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5210 /// Example: 5211 /// 5212 /// struct A { int a; }; 5213 /// struct B { struct A; int b; }; 5214 /// 5215 /// void foo() { 5216 /// B var; 5217 /// var.a = 3; 5218 /// } 5219 /// 5220 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5221 RecordDecl *Record) { 5222 assert(Record && "expected a record!"); 5223 5224 // Mock up a declarator. 5225 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5226 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5227 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5228 5229 auto *ParentDecl = cast<RecordDecl>(CurContext); 5230 QualType RecTy = Context.getTypeDeclType(Record); 5231 5232 // Create a declaration for this anonymous struct. 5233 NamedDecl *Anon = 5234 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5235 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5236 /*BitWidth=*/nullptr, /*Mutable=*/false, 5237 /*InitStyle=*/ICIS_NoInit); 5238 Anon->setImplicit(); 5239 5240 // Add the anonymous struct object to the current context. 5241 CurContext->addDecl(Anon); 5242 5243 // Inject the members of the anonymous struct into the current 5244 // context and into the identifier resolver chain for name lookup 5245 // purposes. 5246 SmallVector<NamedDecl*, 2> Chain; 5247 Chain.push_back(Anon); 5248 5249 RecordDecl *RecordDef = Record->getDefinition(); 5250 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5251 diag::err_field_incomplete_or_sizeless) || 5252 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5253 AS_none, Chain)) { 5254 Anon->setInvalidDecl(); 5255 ParentDecl->setInvalidDecl(); 5256 } 5257 5258 return Anon; 5259 } 5260 5261 /// GetNameForDeclarator - Determine the full declaration name for the 5262 /// given Declarator. 5263 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5264 return GetNameFromUnqualifiedId(D.getName()); 5265 } 5266 5267 /// Retrieves the declaration name from a parsed unqualified-id. 5268 DeclarationNameInfo 5269 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5270 DeclarationNameInfo NameInfo; 5271 NameInfo.setLoc(Name.StartLocation); 5272 5273 switch (Name.getKind()) { 5274 5275 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5276 case UnqualifiedIdKind::IK_Identifier: 5277 NameInfo.setName(Name.Identifier); 5278 return NameInfo; 5279 5280 case UnqualifiedIdKind::IK_DeductionGuideName: { 5281 // C++ [temp.deduct.guide]p3: 5282 // The simple-template-id shall name a class template specialization. 5283 // The template-name shall be the same identifier as the template-name 5284 // of the simple-template-id. 5285 // These together intend to imply that the template-name shall name a 5286 // class template. 5287 // FIXME: template<typename T> struct X {}; 5288 // template<typename T> using Y = X<T>; 5289 // Y(int) -> Y<int>; 5290 // satisfies these rules but does not name a class template. 5291 TemplateName TN = Name.TemplateName.get().get(); 5292 auto *Template = TN.getAsTemplateDecl(); 5293 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5294 Diag(Name.StartLocation, 5295 diag::err_deduction_guide_name_not_class_template) 5296 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5297 if (Template) 5298 Diag(Template->getLocation(), diag::note_template_decl_here); 5299 return DeclarationNameInfo(); 5300 } 5301 5302 NameInfo.setName( 5303 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5304 return NameInfo; 5305 } 5306 5307 case UnqualifiedIdKind::IK_OperatorFunctionId: 5308 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5309 Name.OperatorFunctionId.Operator)); 5310 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5311 = Name.OperatorFunctionId.SymbolLocations[0]; 5312 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5313 = Name.EndLocation.getRawEncoding(); 5314 return NameInfo; 5315 5316 case UnqualifiedIdKind::IK_LiteralOperatorId: 5317 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5318 Name.Identifier)); 5319 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5320 return NameInfo; 5321 5322 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5323 TypeSourceInfo *TInfo; 5324 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5325 if (Ty.isNull()) 5326 return DeclarationNameInfo(); 5327 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5328 Context.getCanonicalType(Ty))); 5329 NameInfo.setNamedTypeInfo(TInfo); 5330 return NameInfo; 5331 } 5332 5333 case UnqualifiedIdKind::IK_ConstructorName: { 5334 TypeSourceInfo *TInfo; 5335 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5336 if (Ty.isNull()) 5337 return DeclarationNameInfo(); 5338 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5339 Context.getCanonicalType(Ty))); 5340 NameInfo.setNamedTypeInfo(TInfo); 5341 return NameInfo; 5342 } 5343 5344 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5345 // In well-formed code, we can only have a constructor 5346 // template-id that refers to the current context, so go there 5347 // to find the actual type being constructed. 5348 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5349 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5350 return DeclarationNameInfo(); 5351 5352 // Determine the type of the class being constructed. 5353 QualType CurClassType = Context.getTypeDeclType(CurClass); 5354 5355 // FIXME: Check two things: that the template-id names the same type as 5356 // CurClassType, and that the template-id does not occur when the name 5357 // was qualified. 5358 5359 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5360 Context.getCanonicalType(CurClassType))); 5361 // FIXME: should we retrieve TypeSourceInfo? 5362 NameInfo.setNamedTypeInfo(nullptr); 5363 return NameInfo; 5364 } 5365 5366 case UnqualifiedIdKind::IK_DestructorName: { 5367 TypeSourceInfo *TInfo; 5368 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5369 if (Ty.isNull()) 5370 return DeclarationNameInfo(); 5371 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5372 Context.getCanonicalType(Ty))); 5373 NameInfo.setNamedTypeInfo(TInfo); 5374 return NameInfo; 5375 } 5376 5377 case UnqualifiedIdKind::IK_TemplateId: { 5378 TemplateName TName = Name.TemplateId->Template.get(); 5379 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5380 return Context.getNameForTemplate(TName, TNameLoc); 5381 } 5382 5383 } // switch (Name.getKind()) 5384 5385 llvm_unreachable("Unknown name kind"); 5386 } 5387 5388 static QualType getCoreType(QualType Ty) { 5389 do { 5390 if (Ty->isPointerType() || Ty->isReferenceType()) 5391 Ty = Ty->getPointeeType(); 5392 else if (Ty->isArrayType()) 5393 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5394 else 5395 return Ty.withoutLocalFastQualifiers(); 5396 } while (true); 5397 } 5398 5399 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5400 /// and Definition have "nearly" matching parameters. This heuristic is 5401 /// used to improve diagnostics in the case where an out-of-line function 5402 /// definition doesn't match any declaration within the class or namespace. 5403 /// Also sets Params to the list of indices to the parameters that differ 5404 /// between the declaration and the definition. If hasSimilarParameters 5405 /// returns true and Params is empty, then all of the parameters match. 5406 static bool hasSimilarParameters(ASTContext &Context, 5407 FunctionDecl *Declaration, 5408 FunctionDecl *Definition, 5409 SmallVectorImpl<unsigned> &Params) { 5410 Params.clear(); 5411 if (Declaration->param_size() != Definition->param_size()) 5412 return false; 5413 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5414 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5415 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5416 5417 // The parameter types are identical 5418 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5419 continue; 5420 5421 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5422 QualType DefParamBaseTy = getCoreType(DefParamTy); 5423 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5424 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5425 5426 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5427 (DeclTyName && DeclTyName == DefTyName)) 5428 Params.push_back(Idx); 5429 else // The two parameters aren't even close 5430 return false; 5431 } 5432 5433 return true; 5434 } 5435 5436 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5437 /// declarator needs to be rebuilt in the current instantiation. 5438 /// Any bits of declarator which appear before the name are valid for 5439 /// consideration here. That's specifically the type in the decl spec 5440 /// and the base type in any member-pointer chunks. 5441 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5442 DeclarationName Name) { 5443 // The types we specifically need to rebuild are: 5444 // - typenames, typeofs, and decltypes 5445 // - types which will become injected class names 5446 // Of course, we also need to rebuild any type referencing such a 5447 // type. It's safest to just say "dependent", but we call out a 5448 // few cases here. 5449 5450 DeclSpec &DS = D.getMutableDeclSpec(); 5451 switch (DS.getTypeSpecType()) { 5452 case DeclSpec::TST_typename: 5453 case DeclSpec::TST_typeofType: 5454 case DeclSpec::TST_underlyingType: 5455 case DeclSpec::TST_atomic: { 5456 // Grab the type from the parser. 5457 TypeSourceInfo *TSI = nullptr; 5458 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5459 if (T.isNull() || !T->isDependentType()) break; 5460 5461 // Make sure there's a type source info. This isn't really much 5462 // of a waste; most dependent types should have type source info 5463 // attached already. 5464 if (!TSI) 5465 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5466 5467 // Rebuild the type in the current instantiation. 5468 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5469 if (!TSI) return true; 5470 5471 // Store the new type back in the decl spec. 5472 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5473 DS.UpdateTypeRep(LocType); 5474 break; 5475 } 5476 5477 case DeclSpec::TST_decltype: 5478 case DeclSpec::TST_typeofExpr: { 5479 Expr *E = DS.getRepAsExpr(); 5480 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5481 if (Result.isInvalid()) return true; 5482 DS.UpdateExprRep(Result.get()); 5483 break; 5484 } 5485 5486 default: 5487 // Nothing to do for these decl specs. 5488 break; 5489 } 5490 5491 // It doesn't matter what order we do this in. 5492 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5493 DeclaratorChunk &Chunk = D.getTypeObject(I); 5494 5495 // The only type information in the declarator which can come 5496 // before the declaration name is the base type of a member 5497 // pointer. 5498 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5499 continue; 5500 5501 // Rebuild the scope specifier in-place. 5502 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5503 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5504 return true; 5505 } 5506 5507 return false; 5508 } 5509 5510 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5511 D.setFunctionDefinitionKind(FDK_Declaration); 5512 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5513 5514 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5515 Dcl && Dcl->getDeclContext()->isFileContext()) 5516 Dcl->setTopLevelDeclInObjCContainer(); 5517 5518 if (getLangOpts().OpenCL) 5519 setCurrentOpenCLExtensionForDecl(Dcl); 5520 5521 return Dcl; 5522 } 5523 5524 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5525 /// If T is the name of a class, then each of the following shall have a 5526 /// name different from T: 5527 /// - every static data member of class T; 5528 /// - every member function of class T 5529 /// - every member of class T that is itself a type; 5530 /// \returns true if the declaration name violates these rules. 5531 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5532 DeclarationNameInfo NameInfo) { 5533 DeclarationName Name = NameInfo.getName(); 5534 5535 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5536 while (Record && Record->isAnonymousStructOrUnion()) 5537 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5538 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5539 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 /// Diagnose a declaration whose declarator-id has the given 5547 /// nested-name-specifier. 5548 /// 5549 /// \param SS The nested-name-specifier of the declarator-id. 5550 /// 5551 /// \param DC The declaration context to which the nested-name-specifier 5552 /// resolves. 5553 /// 5554 /// \param Name The name of the entity being declared. 5555 /// 5556 /// \param Loc The location of the name of the entity being declared. 5557 /// 5558 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5559 /// we're declaring an explicit / partial specialization / instantiation. 5560 /// 5561 /// \returns true if we cannot safely recover from this error, false otherwise. 5562 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5563 DeclarationName Name, 5564 SourceLocation Loc, bool IsTemplateId) { 5565 DeclContext *Cur = CurContext; 5566 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5567 Cur = Cur->getParent(); 5568 5569 // If the user provided a superfluous scope specifier that refers back to the 5570 // class in which the entity is already declared, diagnose and ignore it. 5571 // 5572 // class X { 5573 // void X::f(); 5574 // }; 5575 // 5576 // Note, it was once ill-formed to give redundant qualification in all 5577 // contexts, but that rule was removed by DR482. 5578 if (Cur->Equals(DC)) { 5579 if (Cur->isRecord()) { 5580 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5581 : diag::err_member_extra_qualification) 5582 << Name << FixItHint::CreateRemoval(SS.getRange()); 5583 SS.clear(); 5584 } else { 5585 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5586 } 5587 return false; 5588 } 5589 5590 // Check whether the qualifying scope encloses the scope of the original 5591 // declaration. For a template-id, we perform the checks in 5592 // CheckTemplateSpecializationScope. 5593 if (!Cur->Encloses(DC) && !IsTemplateId) { 5594 if (Cur->isRecord()) 5595 Diag(Loc, diag::err_member_qualification) 5596 << Name << SS.getRange(); 5597 else if (isa<TranslationUnitDecl>(DC)) 5598 Diag(Loc, diag::err_invalid_declarator_global_scope) 5599 << Name << SS.getRange(); 5600 else if (isa<FunctionDecl>(Cur)) 5601 Diag(Loc, diag::err_invalid_declarator_in_function) 5602 << Name << SS.getRange(); 5603 else if (isa<BlockDecl>(Cur)) 5604 Diag(Loc, diag::err_invalid_declarator_in_block) 5605 << Name << SS.getRange(); 5606 else 5607 Diag(Loc, diag::err_invalid_declarator_scope) 5608 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5609 5610 return true; 5611 } 5612 5613 if (Cur->isRecord()) { 5614 // Cannot qualify members within a class. 5615 Diag(Loc, diag::err_member_qualification) 5616 << Name << SS.getRange(); 5617 SS.clear(); 5618 5619 // C++ constructors and destructors with incorrect scopes can break 5620 // our AST invariants by having the wrong underlying types. If 5621 // that's the case, then drop this declaration entirely. 5622 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5623 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5624 !Context.hasSameType(Name.getCXXNameType(), 5625 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5626 return true; 5627 5628 return false; 5629 } 5630 5631 // C++11 [dcl.meaning]p1: 5632 // [...] "The nested-name-specifier of the qualified declarator-id shall 5633 // not begin with a decltype-specifer" 5634 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5635 while (SpecLoc.getPrefix()) 5636 SpecLoc = SpecLoc.getPrefix(); 5637 if (dyn_cast_or_null<DecltypeType>( 5638 SpecLoc.getNestedNameSpecifier()->getAsType())) 5639 Diag(Loc, diag::err_decltype_in_declarator) 5640 << SpecLoc.getTypeLoc().getSourceRange(); 5641 5642 return false; 5643 } 5644 5645 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5646 MultiTemplateParamsArg TemplateParamLists) { 5647 // TODO: consider using NameInfo for diagnostic. 5648 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5649 DeclarationName Name = NameInfo.getName(); 5650 5651 // All of these full declarators require an identifier. If it doesn't have 5652 // one, the ParsedFreeStandingDeclSpec action should be used. 5653 if (D.isDecompositionDeclarator()) { 5654 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5655 } else if (!Name) { 5656 if (!D.isInvalidType()) // Reject this if we think it is valid. 5657 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5658 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5659 return nullptr; 5660 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5661 return nullptr; 5662 5663 // The scope passed in may not be a decl scope. Zip up the scope tree until 5664 // we find one that is. 5665 while ((S->getFlags() & Scope::DeclScope) == 0 || 5666 (S->getFlags() & Scope::TemplateParamScope) != 0) 5667 S = S->getParent(); 5668 5669 DeclContext *DC = CurContext; 5670 if (D.getCXXScopeSpec().isInvalid()) 5671 D.setInvalidType(); 5672 else if (D.getCXXScopeSpec().isSet()) { 5673 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5674 UPPC_DeclarationQualifier)) 5675 return nullptr; 5676 5677 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5678 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5679 if (!DC || isa<EnumDecl>(DC)) { 5680 // If we could not compute the declaration context, it's because the 5681 // declaration context is dependent but does not refer to a class, 5682 // class template, or class template partial specialization. Complain 5683 // and return early, to avoid the coming semantic disaster. 5684 Diag(D.getIdentifierLoc(), 5685 diag::err_template_qualified_declarator_no_match) 5686 << D.getCXXScopeSpec().getScopeRep() 5687 << D.getCXXScopeSpec().getRange(); 5688 return nullptr; 5689 } 5690 bool IsDependentContext = DC->isDependentContext(); 5691 5692 if (!IsDependentContext && 5693 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5694 return nullptr; 5695 5696 // If a class is incomplete, do not parse entities inside it. 5697 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5698 Diag(D.getIdentifierLoc(), 5699 diag::err_member_def_undefined_record) 5700 << Name << DC << D.getCXXScopeSpec().getRange(); 5701 return nullptr; 5702 } 5703 if (!D.getDeclSpec().isFriendSpecified()) { 5704 if (diagnoseQualifiedDeclaration( 5705 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5706 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5707 if (DC->isRecord()) 5708 return nullptr; 5709 5710 D.setInvalidType(); 5711 } 5712 } 5713 5714 // Check whether we need to rebuild the type of the given 5715 // declaration in the current instantiation. 5716 if (EnteringContext && IsDependentContext && 5717 TemplateParamLists.size() != 0) { 5718 ContextRAII SavedContext(*this, DC); 5719 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5720 D.setInvalidType(); 5721 } 5722 } 5723 5724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5725 QualType R = TInfo->getType(); 5726 5727 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5728 UPPC_DeclarationType)) 5729 D.setInvalidType(); 5730 5731 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5732 forRedeclarationInCurContext()); 5733 5734 // See if this is a redefinition of a variable in the same scope. 5735 if (!D.getCXXScopeSpec().isSet()) { 5736 bool IsLinkageLookup = false; 5737 bool CreateBuiltins = false; 5738 5739 // If the declaration we're planning to build will be a function 5740 // or object with linkage, then look for another declaration with 5741 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5742 // 5743 // If the declaration we're planning to build will be declared with 5744 // external linkage in the translation unit, create any builtin with 5745 // the same name. 5746 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5747 /* Do nothing*/; 5748 else if (CurContext->isFunctionOrMethod() && 5749 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5750 R->isFunctionType())) { 5751 IsLinkageLookup = true; 5752 CreateBuiltins = 5753 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5754 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5755 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5756 CreateBuiltins = true; 5757 5758 if (IsLinkageLookup) { 5759 Previous.clear(LookupRedeclarationWithLinkage); 5760 Previous.setRedeclarationKind(ForExternalRedeclaration); 5761 } 5762 5763 LookupName(Previous, S, CreateBuiltins); 5764 } else { // Something like "int foo::x;" 5765 LookupQualifiedName(Previous, DC); 5766 5767 // C++ [dcl.meaning]p1: 5768 // When the declarator-id is qualified, the declaration shall refer to a 5769 // previously declared member of the class or namespace to which the 5770 // qualifier refers (or, in the case of a namespace, of an element of the 5771 // inline namespace set of that namespace (7.3.1)) or to a specialization 5772 // thereof; [...] 5773 // 5774 // Note that we already checked the context above, and that we do not have 5775 // enough information to make sure that Previous contains the declaration 5776 // we want to match. For example, given: 5777 // 5778 // class X { 5779 // void f(); 5780 // void f(float); 5781 // }; 5782 // 5783 // void X::f(int) { } // ill-formed 5784 // 5785 // In this case, Previous will point to the overload set 5786 // containing the two f's declared in X, but neither of them 5787 // matches. 5788 5789 // C++ [dcl.meaning]p1: 5790 // [...] the member shall not merely have been introduced by a 5791 // using-declaration in the scope of the class or namespace nominated by 5792 // the nested-name-specifier of the declarator-id. 5793 RemoveUsingDecls(Previous); 5794 } 5795 5796 if (Previous.isSingleResult() && 5797 Previous.getFoundDecl()->isTemplateParameter()) { 5798 // Maybe we will complain about the shadowed template parameter. 5799 if (!D.isInvalidType()) 5800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5801 Previous.getFoundDecl()); 5802 5803 // Just pretend that we didn't see the previous declaration. 5804 Previous.clear(); 5805 } 5806 5807 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5808 // Forget that the previous declaration is the injected-class-name. 5809 Previous.clear(); 5810 5811 // In C++, the previous declaration we find might be a tag type 5812 // (class or enum). In this case, the new declaration will hide the 5813 // tag type. Note that this applies to functions, function templates, and 5814 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5815 if (Previous.isSingleTagDecl() && 5816 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5817 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5818 Previous.clear(); 5819 5820 // Check that there are no default arguments other than in the parameters 5821 // of a function declaration (C++ only). 5822 if (getLangOpts().CPlusPlus) 5823 CheckExtraCXXDefaultArguments(D); 5824 5825 NamedDecl *New; 5826 5827 bool AddToScope = true; 5828 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5829 if (TemplateParamLists.size()) { 5830 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5831 return nullptr; 5832 } 5833 5834 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5835 } else if (R->isFunctionType()) { 5836 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5837 TemplateParamLists, 5838 AddToScope); 5839 } else { 5840 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5841 AddToScope); 5842 } 5843 5844 if (!New) 5845 return nullptr; 5846 5847 // If this has an identifier and is not a function template specialization, 5848 // add it to the scope stack. 5849 if (New->getDeclName() && AddToScope) 5850 PushOnScopeChains(New, S); 5851 5852 if (isInOpenMPDeclareTargetContext()) 5853 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5854 5855 return New; 5856 } 5857 5858 /// Helper method to turn variable array types into constant array 5859 /// types in certain situations which would otherwise be errors (for 5860 /// GCC compatibility). 5861 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5862 ASTContext &Context, 5863 bool &SizeIsNegative, 5864 llvm::APSInt &Oversized) { 5865 // This method tries to turn a variable array into a constant 5866 // array even when the size isn't an ICE. This is necessary 5867 // for compatibility with code that depends on gcc's buggy 5868 // constant expression folding, like struct {char x[(int)(char*)2];} 5869 SizeIsNegative = false; 5870 Oversized = 0; 5871 5872 if (T->isDependentType()) 5873 return QualType(); 5874 5875 QualifierCollector Qs; 5876 const Type *Ty = Qs.strip(T); 5877 5878 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5879 QualType Pointee = PTy->getPointeeType(); 5880 QualType FixedType = 5881 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5882 Oversized); 5883 if (FixedType.isNull()) return FixedType; 5884 FixedType = Context.getPointerType(FixedType); 5885 return Qs.apply(Context, FixedType); 5886 } 5887 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5888 QualType Inner = PTy->getInnerType(); 5889 QualType FixedType = 5890 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5891 Oversized); 5892 if (FixedType.isNull()) return FixedType; 5893 FixedType = Context.getParenType(FixedType); 5894 return Qs.apply(Context, FixedType); 5895 } 5896 5897 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5898 if (!VLATy) 5899 return QualType(); 5900 // FIXME: We should probably handle this case 5901 if (VLATy->getElementType()->isVariablyModifiedType()) 5902 return QualType(); 5903 5904 Expr::EvalResult Result; 5905 if (!VLATy->getSizeExpr() || 5906 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5907 return QualType(); 5908 5909 llvm::APSInt Res = Result.Val.getInt(); 5910 5911 // Check whether the array size is negative. 5912 if (Res.isSigned() && Res.isNegative()) { 5913 SizeIsNegative = true; 5914 return QualType(); 5915 } 5916 5917 // Check whether the array is too large to be addressed. 5918 unsigned ActiveSizeBits 5919 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5920 Res); 5921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5922 Oversized = Res; 5923 return QualType(); 5924 } 5925 5926 return Context.getConstantArrayType( 5927 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5928 } 5929 5930 static void 5931 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5932 SrcTL = SrcTL.getUnqualifiedLoc(); 5933 DstTL = DstTL.getUnqualifiedLoc(); 5934 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5935 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5936 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5937 DstPTL.getPointeeLoc()); 5938 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5939 return; 5940 } 5941 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5942 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5943 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5944 DstPTL.getInnerLoc()); 5945 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5946 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5947 return; 5948 } 5949 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5950 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5951 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5952 TypeLoc DstElemTL = DstATL.getElementLoc(); 5953 DstElemTL.initializeFullCopy(SrcElemTL); 5954 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5955 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5956 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5957 } 5958 5959 /// Helper method to turn variable array types into constant array 5960 /// types in certain situations which would otherwise be errors (for 5961 /// GCC compatibility). 5962 static TypeSourceInfo* 5963 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5964 ASTContext &Context, 5965 bool &SizeIsNegative, 5966 llvm::APSInt &Oversized) { 5967 QualType FixedTy 5968 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5969 SizeIsNegative, Oversized); 5970 if (FixedTy.isNull()) 5971 return nullptr; 5972 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5973 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5974 FixedTInfo->getTypeLoc()); 5975 return FixedTInfo; 5976 } 5977 5978 /// Register the given locally-scoped extern "C" declaration so 5979 /// that it can be found later for redeclarations. We include any extern "C" 5980 /// declaration that is not visible in the translation unit here, not just 5981 /// function-scope declarations. 5982 void 5983 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5984 if (!getLangOpts().CPlusPlus && 5985 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5986 // Don't need to track declarations in the TU in C. 5987 return; 5988 5989 // Note that we have a locally-scoped external with this name. 5990 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5991 } 5992 5993 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5994 // FIXME: We can have multiple results via __attribute__((overloadable)). 5995 auto Result = Context.getExternCContextDecl()->lookup(Name); 5996 return Result.empty() ? nullptr : *Result.begin(); 5997 } 5998 5999 /// Diagnose function specifiers on a declaration of an identifier that 6000 /// does not identify a function. 6001 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6002 // FIXME: We should probably indicate the identifier in question to avoid 6003 // confusion for constructs like "virtual int a(), b;" 6004 if (DS.isVirtualSpecified()) 6005 Diag(DS.getVirtualSpecLoc(), 6006 diag::err_virtual_non_function); 6007 6008 if (DS.hasExplicitSpecifier()) 6009 Diag(DS.getExplicitSpecLoc(), 6010 diag::err_explicit_non_function); 6011 6012 if (DS.isNoreturnSpecified()) 6013 Diag(DS.getNoreturnSpecLoc(), 6014 diag::err_noreturn_non_function); 6015 } 6016 6017 NamedDecl* 6018 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6019 TypeSourceInfo *TInfo, LookupResult &Previous) { 6020 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6021 if (D.getCXXScopeSpec().isSet()) { 6022 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6023 << D.getCXXScopeSpec().getRange(); 6024 D.setInvalidType(); 6025 // Pretend we didn't see the scope specifier. 6026 DC = CurContext; 6027 Previous.clear(); 6028 } 6029 6030 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6031 6032 if (D.getDeclSpec().isInlineSpecified()) 6033 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6034 << getLangOpts().CPlusPlus17; 6035 if (D.getDeclSpec().hasConstexprSpecifier()) 6036 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6037 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6038 6039 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6040 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6041 Diag(D.getName().StartLocation, 6042 diag::err_deduction_guide_invalid_specifier) 6043 << "typedef"; 6044 else 6045 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6046 << D.getName().getSourceRange(); 6047 return nullptr; 6048 } 6049 6050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6051 if (!NewTD) return nullptr; 6052 6053 // Handle attributes prior to checking for duplicates in MergeVarDecl 6054 ProcessDeclAttributes(S, NewTD, D); 6055 6056 CheckTypedefForVariablyModifiedType(S, NewTD); 6057 6058 bool Redeclaration = D.isRedeclaration(); 6059 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6060 D.setRedeclaration(Redeclaration); 6061 return ND; 6062 } 6063 6064 void 6065 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6066 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6067 // then it shall have block scope. 6068 // Note that variably modified types must be fixed before merging the decl so 6069 // that redeclarations will match. 6070 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6071 QualType T = TInfo->getType(); 6072 if (T->isVariablyModifiedType()) { 6073 setFunctionHasBranchProtectedScope(); 6074 6075 if (S->getFnParent() == nullptr) { 6076 bool SizeIsNegative; 6077 llvm::APSInt Oversized; 6078 TypeSourceInfo *FixedTInfo = 6079 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6080 SizeIsNegative, 6081 Oversized); 6082 if (FixedTInfo) { 6083 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6084 NewTD->setTypeSourceInfo(FixedTInfo); 6085 } else { 6086 if (SizeIsNegative) 6087 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6088 else if (T->isVariableArrayType()) 6089 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6090 else if (Oversized.getBoolValue()) 6091 Diag(NewTD->getLocation(), diag::err_array_too_large) 6092 << Oversized.toString(10); 6093 else 6094 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6095 NewTD->setInvalidDecl(); 6096 } 6097 } 6098 } 6099 } 6100 6101 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6102 /// declares a typedef-name, either using the 'typedef' type specifier or via 6103 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6104 NamedDecl* 6105 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6106 LookupResult &Previous, bool &Redeclaration) { 6107 6108 // Find the shadowed declaration before filtering for scope. 6109 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6110 6111 // Merge the decl with the existing one if appropriate. If the decl is 6112 // in an outer scope, it isn't the same thing. 6113 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6114 /*AllowInlineNamespace*/false); 6115 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6116 if (!Previous.empty()) { 6117 Redeclaration = true; 6118 MergeTypedefNameDecl(S, NewTD, Previous); 6119 } else { 6120 inferGslPointerAttribute(NewTD); 6121 } 6122 6123 if (ShadowedDecl && !Redeclaration) 6124 CheckShadow(NewTD, ShadowedDecl, Previous); 6125 6126 // If this is the C FILE type, notify the AST context. 6127 if (IdentifierInfo *II = NewTD->getIdentifier()) 6128 if (!NewTD->isInvalidDecl() && 6129 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6130 if (II->isStr("FILE")) 6131 Context.setFILEDecl(NewTD); 6132 else if (II->isStr("jmp_buf")) 6133 Context.setjmp_bufDecl(NewTD); 6134 else if (II->isStr("sigjmp_buf")) 6135 Context.setsigjmp_bufDecl(NewTD); 6136 else if (II->isStr("ucontext_t")) 6137 Context.setucontext_tDecl(NewTD); 6138 } 6139 6140 return NewTD; 6141 } 6142 6143 /// Determines whether the given declaration is an out-of-scope 6144 /// previous declaration. 6145 /// 6146 /// This routine should be invoked when name lookup has found a 6147 /// previous declaration (PrevDecl) that is not in the scope where a 6148 /// new declaration by the same name is being introduced. If the new 6149 /// declaration occurs in a local scope, previous declarations with 6150 /// linkage may still be considered previous declarations (C99 6151 /// 6.2.2p4-5, C++ [basic.link]p6). 6152 /// 6153 /// \param PrevDecl the previous declaration found by name 6154 /// lookup 6155 /// 6156 /// \param DC the context in which the new declaration is being 6157 /// declared. 6158 /// 6159 /// \returns true if PrevDecl is an out-of-scope previous declaration 6160 /// for a new delcaration with the same name. 6161 static bool 6162 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6163 ASTContext &Context) { 6164 if (!PrevDecl) 6165 return false; 6166 6167 if (!PrevDecl->hasLinkage()) 6168 return false; 6169 6170 if (Context.getLangOpts().CPlusPlus) { 6171 // C++ [basic.link]p6: 6172 // If there is a visible declaration of an entity with linkage 6173 // having the same name and type, ignoring entities declared 6174 // outside the innermost enclosing namespace scope, the block 6175 // scope declaration declares that same entity and receives the 6176 // linkage of the previous declaration. 6177 DeclContext *OuterContext = DC->getRedeclContext(); 6178 if (!OuterContext->isFunctionOrMethod()) 6179 // This rule only applies to block-scope declarations. 6180 return false; 6181 6182 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6183 if (PrevOuterContext->isRecord()) 6184 // We found a member function: ignore it. 6185 return false; 6186 6187 // Find the innermost enclosing namespace for the new and 6188 // previous declarations. 6189 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6190 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6191 6192 // The previous declaration is in a different namespace, so it 6193 // isn't the same function. 6194 if (!OuterContext->Equals(PrevOuterContext)) 6195 return false; 6196 } 6197 6198 return true; 6199 } 6200 6201 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6202 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6203 if (!SS.isSet()) return; 6204 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6205 } 6206 6207 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6208 QualType type = decl->getType(); 6209 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6210 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6211 // Various kinds of declaration aren't allowed to be __autoreleasing. 6212 unsigned kind = -1U; 6213 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6214 if (var->hasAttr<BlocksAttr>()) 6215 kind = 0; // __block 6216 else if (!var->hasLocalStorage()) 6217 kind = 1; // global 6218 } else if (isa<ObjCIvarDecl>(decl)) { 6219 kind = 3; // ivar 6220 } else if (isa<FieldDecl>(decl)) { 6221 kind = 2; // field 6222 } 6223 6224 if (kind != -1U) { 6225 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6226 << kind; 6227 } 6228 } else if (lifetime == Qualifiers::OCL_None) { 6229 // Try to infer lifetime. 6230 if (!type->isObjCLifetimeType()) 6231 return false; 6232 6233 lifetime = type->getObjCARCImplicitLifetime(); 6234 type = Context.getLifetimeQualifiedType(type, lifetime); 6235 decl->setType(type); 6236 } 6237 6238 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6239 // Thread-local variables cannot have lifetime. 6240 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6241 var->getTLSKind()) { 6242 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6243 << var->getType(); 6244 return true; 6245 } 6246 } 6247 6248 return false; 6249 } 6250 6251 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6252 if (Decl->getType().hasAddressSpace()) 6253 return; 6254 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6255 QualType Type = Var->getType(); 6256 if (Type->isSamplerT() || Type->isVoidType()) 6257 return; 6258 LangAS ImplAS = LangAS::opencl_private; 6259 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6260 Var->hasGlobalStorage()) 6261 ImplAS = LangAS::opencl_global; 6262 // If the original type from a decayed type is an array type and that array 6263 // type has no address space yet, deduce it now. 6264 if (auto DT = dyn_cast<DecayedType>(Type)) { 6265 auto OrigTy = DT->getOriginalType(); 6266 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6267 // Add the address space to the original array type and then propagate 6268 // that to the element type through `getAsArrayType`. 6269 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6270 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6271 // Re-generate the decayed type. 6272 Type = Context.getDecayedType(OrigTy); 6273 } 6274 } 6275 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6276 // Apply any qualifiers (including address space) from the array type to 6277 // the element type. This implements C99 6.7.3p8: "If the specification of 6278 // an array type includes any type qualifiers, the element type is so 6279 // qualified, not the array type." 6280 if (Type->isArrayType()) 6281 Type = QualType(Context.getAsArrayType(Type), 0); 6282 Decl->setType(Type); 6283 } 6284 } 6285 6286 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6287 // Ensure that an auto decl is deduced otherwise the checks below might cache 6288 // the wrong linkage. 6289 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6290 6291 // 'weak' only applies to declarations with external linkage. 6292 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6293 if (!ND.isExternallyVisible()) { 6294 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6295 ND.dropAttr<WeakAttr>(); 6296 } 6297 } 6298 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6299 if (ND.isExternallyVisible()) { 6300 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6301 ND.dropAttr<WeakRefAttr>(); 6302 ND.dropAttr<AliasAttr>(); 6303 } 6304 } 6305 6306 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6307 if (VD->hasInit()) { 6308 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6309 assert(VD->isThisDeclarationADefinition() && 6310 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6311 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6312 VD->dropAttr<AliasAttr>(); 6313 } 6314 } 6315 } 6316 6317 // 'selectany' only applies to externally visible variable declarations. 6318 // It does not apply to functions. 6319 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6320 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6321 S.Diag(Attr->getLocation(), 6322 diag::err_attribute_selectany_non_extern_data); 6323 ND.dropAttr<SelectAnyAttr>(); 6324 } 6325 } 6326 6327 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6328 auto *VD = dyn_cast<VarDecl>(&ND); 6329 bool IsAnonymousNS = false; 6330 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6331 if (VD) { 6332 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6333 while (NS && !IsAnonymousNS) { 6334 IsAnonymousNS = NS->isAnonymousNamespace(); 6335 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6336 } 6337 } 6338 // dll attributes require external linkage. Static locals may have external 6339 // linkage but still cannot be explicitly imported or exported. 6340 // In Microsoft mode, a variable defined in anonymous namespace must have 6341 // external linkage in order to be exported. 6342 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6343 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6344 (!AnonNSInMicrosoftMode && 6345 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6346 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6347 << &ND << Attr; 6348 ND.setInvalidDecl(); 6349 } 6350 } 6351 6352 // Virtual functions cannot be marked as 'notail'. 6353 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6354 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6355 if (MD->isVirtual()) { 6356 S.Diag(ND.getLocation(), 6357 diag::err_invalid_attribute_on_virtual_function) 6358 << Attr; 6359 ND.dropAttr<NotTailCalledAttr>(); 6360 } 6361 6362 // Check the attributes on the function type, if any. 6363 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6364 // Don't declare this variable in the second operand of the for-statement; 6365 // GCC miscompiles that by ending its lifetime before evaluating the 6366 // third operand. See gcc.gnu.org/PR86769. 6367 AttributedTypeLoc ATL; 6368 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6369 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6370 TL = ATL.getModifiedLoc()) { 6371 // The [[lifetimebound]] attribute can be applied to the implicit object 6372 // parameter of a non-static member function (other than a ctor or dtor) 6373 // by applying it to the function type. 6374 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6375 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6376 if (!MD || MD->isStatic()) { 6377 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6378 << !MD << A->getRange(); 6379 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6380 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6381 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6382 } 6383 } 6384 } 6385 } 6386 } 6387 6388 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6389 NamedDecl *NewDecl, 6390 bool IsSpecialization, 6391 bool IsDefinition) { 6392 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6393 return; 6394 6395 bool IsTemplate = false; 6396 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6397 OldDecl = OldTD->getTemplatedDecl(); 6398 IsTemplate = true; 6399 if (!IsSpecialization) 6400 IsDefinition = false; 6401 } 6402 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6403 NewDecl = NewTD->getTemplatedDecl(); 6404 IsTemplate = true; 6405 } 6406 6407 if (!OldDecl || !NewDecl) 6408 return; 6409 6410 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6411 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6412 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6413 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6414 6415 // dllimport and dllexport are inheritable attributes so we have to exclude 6416 // inherited attribute instances. 6417 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6418 (NewExportAttr && !NewExportAttr->isInherited()); 6419 6420 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6421 // the only exception being explicit specializations. 6422 // Implicitly generated declarations are also excluded for now because there 6423 // is no other way to switch these to use dllimport or dllexport. 6424 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6425 6426 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6427 // Allow with a warning for free functions and global variables. 6428 bool JustWarn = false; 6429 if (!OldDecl->isCXXClassMember()) { 6430 auto *VD = dyn_cast<VarDecl>(OldDecl); 6431 if (VD && !VD->getDescribedVarTemplate()) 6432 JustWarn = true; 6433 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6434 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6435 JustWarn = true; 6436 } 6437 6438 // We cannot change a declaration that's been used because IR has already 6439 // been emitted. Dllimported functions will still work though (modulo 6440 // address equality) as they can use the thunk. 6441 if (OldDecl->isUsed()) 6442 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6443 JustWarn = false; 6444 6445 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6446 : diag::err_attribute_dll_redeclaration; 6447 S.Diag(NewDecl->getLocation(), DiagID) 6448 << NewDecl 6449 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6450 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6451 if (!JustWarn) { 6452 NewDecl->setInvalidDecl(); 6453 return; 6454 } 6455 } 6456 6457 // A redeclaration is not allowed to drop a dllimport attribute, the only 6458 // exceptions being inline function definitions (except for function 6459 // templates), local extern declarations, qualified friend declarations or 6460 // special MSVC extension: in the last case, the declaration is treated as if 6461 // it were marked dllexport. 6462 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6463 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6464 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6465 // Ignore static data because out-of-line definitions are diagnosed 6466 // separately. 6467 IsStaticDataMember = VD->isStaticDataMember(); 6468 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6469 VarDecl::DeclarationOnly; 6470 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6471 IsInline = FD->isInlined(); 6472 IsQualifiedFriend = FD->getQualifier() && 6473 FD->getFriendObjectKind() == Decl::FOK_Declared; 6474 } 6475 6476 if (OldImportAttr && !HasNewAttr && 6477 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6478 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6479 if (IsMicrosoft && IsDefinition) { 6480 S.Diag(NewDecl->getLocation(), 6481 diag::warn_redeclaration_without_import_attribute) 6482 << NewDecl; 6483 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6484 NewDecl->dropAttr<DLLImportAttr>(); 6485 NewDecl->addAttr( 6486 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6487 } else { 6488 S.Diag(NewDecl->getLocation(), 6489 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6490 << NewDecl << OldImportAttr; 6491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6492 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6493 OldDecl->dropAttr<DLLImportAttr>(); 6494 NewDecl->dropAttr<DLLImportAttr>(); 6495 } 6496 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6497 // In MinGW, seeing a function declared inline drops the dllimport 6498 // attribute. 6499 OldDecl->dropAttr<DLLImportAttr>(); 6500 NewDecl->dropAttr<DLLImportAttr>(); 6501 S.Diag(NewDecl->getLocation(), 6502 diag::warn_dllimport_dropped_from_inline_function) 6503 << NewDecl << OldImportAttr; 6504 } 6505 6506 // A specialization of a class template member function is processed here 6507 // since it's a redeclaration. If the parent class is dllexport, the 6508 // specialization inherits that attribute. This doesn't happen automatically 6509 // since the parent class isn't instantiated until later. 6510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6511 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6512 !NewImportAttr && !NewExportAttr) { 6513 if (const DLLExportAttr *ParentExportAttr = 6514 MD->getParent()->getAttr<DLLExportAttr>()) { 6515 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6516 NewAttr->setInherited(true); 6517 NewDecl->addAttr(NewAttr); 6518 } 6519 } 6520 } 6521 } 6522 6523 /// Given that we are within the definition of the given function, 6524 /// will that definition behave like C99's 'inline', where the 6525 /// definition is discarded except for optimization purposes? 6526 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6527 // Try to avoid calling GetGVALinkageForFunction. 6528 6529 // All cases of this require the 'inline' keyword. 6530 if (!FD->isInlined()) return false; 6531 6532 // This is only possible in C++ with the gnu_inline attribute. 6533 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6534 return false; 6535 6536 // Okay, go ahead and call the relatively-more-expensive function. 6537 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6538 } 6539 6540 /// Determine whether a variable is extern "C" prior to attaching 6541 /// an initializer. We can't just call isExternC() here, because that 6542 /// will also compute and cache whether the declaration is externally 6543 /// visible, which might change when we attach the initializer. 6544 /// 6545 /// This can only be used if the declaration is known to not be a 6546 /// redeclaration of an internal linkage declaration. 6547 /// 6548 /// For instance: 6549 /// 6550 /// auto x = []{}; 6551 /// 6552 /// Attaching the initializer here makes this declaration not externally 6553 /// visible, because its type has internal linkage. 6554 /// 6555 /// FIXME: This is a hack. 6556 template<typename T> 6557 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6558 if (S.getLangOpts().CPlusPlus) { 6559 // In C++, the overloadable attribute negates the effects of extern "C". 6560 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6561 return false; 6562 6563 // So do CUDA's host/device attributes. 6564 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6565 D->template hasAttr<CUDAHostAttr>())) 6566 return false; 6567 } 6568 return D->isExternC(); 6569 } 6570 6571 static bool shouldConsiderLinkage(const VarDecl *VD) { 6572 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6573 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6574 isa<OMPDeclareMapperDecl>(DC)) 6575 return VD->hasExternalStorage(); 6576 if (DC->isFileContext()) 6577 return true; 6578 if (DC->isRecord()) 6579 return false; 6580 if (isa<RequiresExprBodyDecl>(DC)) 6581 return false; 6582 llvm_unreachable("Unexpected context"); 6583 } 6584 6585 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6586 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6587 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6588 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6589 return true; 6590 if (DC->isRecord()) 6591 return false; 6592 llvm_unreachable("Unexpected context"); 6593 } 6594 6595 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6596 ParsedAttr::Kind Kind) { 6597 // Check decl attributes on the DeclSpec. 6598 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6599 return true; 6600 6601 // Walk the declarator structure, checking decl attributes that were in a type 6602 // position to the decl itself. 6603 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6604 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6605 return true; 6606 } 6607 6608 // Finally, check attributes on the decl itself. 6609 return PD.getAttributes().hasAttribute(Kind); 6610 } 6611 6612 /// Adjust the \c DeclContext for a function or variable that might be a 6613 /// function-local external declaration. 6614 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6615 if (!DC->isFunctionOrMethod()) 6616 return false; 6617 6618 // If this is a local extern function or variable declared within a function 6619 // template, don't add it into the enclosing namespace scope until it is 6620 // instantiated; it might have a dependent type right now. 6621 if (DC->isDependentContext()) 6622 return true; 6623 6624 // C++11 [basic.link]p7: 6625 // When a block scope declaration of an entity with linkage is not found to 6626 // refer to some other declaration, then that entity is a member of the 6627 // innermost enclosing namespace. 6628 // 6629 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6630 // semantically-enclosing namespace, not a lexically-enclosing one. 6631 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6632 DC = DC->getParent(); 6633 return true; 6634 } 6635 6636 /// Returns true if given declaration has external C language linkage. 6637 static bool isDeclExternC(const Decl *D) { 6638 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6639 return FD->isExternC(); 6640 if (const auto *VD = dyn_cast<VarDecl>(D)) 6641 return VD->isExternC(); 6642 6643 llvm_unreachable("Unknown type of decl!"); 6644 } 6645 /// Returns true if there hasn't been any invalid type diagnosed. 6646 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6647 DeclContext *DC, QualType R) { 6648 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6649 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6650 // argument. 6651 if (R->isImageType() || R->isPipeType()) { 6652 Se.Diag(D.getIdentifierLoc(), 6653 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6654 << R; 6655 D.setInvalidType(); 6656 return false; 6657 } 6658 6659 // OpenCL v1.2 s6.9.r: 6660 // The event type cannot be used to declare a program scope variable. 6661 // OpenCL v2.0 s6.9.q: 6662 // The clk_event_t and reserve_id_t types cannot be declared in program 6663 // scope. 6664 if (NULL == S->getParent()) { 6665 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6666 Se.Diag(D.getIdentifierLoc(), 6667 diag::err_invalid_type_for_program_scope_var) 6668 << R; 6669 D.setInvalidType(); 6670 return false; 6671 } 6672 } 6673 6674 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6675 QualType NR = R; 6676 while (NR->isPointerType()) { 6677 if (NR->isFunctionPointerType()) { 6678 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6679 D.setInvalidType(); 6680 return false; 6681 } 6682 NR = NR->getPointeeType(); 6683 } 6684 6685 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6686 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6687 // half array type (unless the cl_khr_fp16 extension is enabled). 6688 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6689 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6690 D.setInvalidType(); 6691 return false; 6692 } 6693 } 6694 6695 // OpenCL v1.2 s6.9.r: 6696 // The event type cannot be used with the __local, __constant and __global 6697 // address space qualifiers. 6698 if (R->isEventT()) { 6699 if (R.getAddressSpace() != LangAS::opencl_private) { 6700 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6701 D.setInvalidType(); 6702 return false; 6703 } 6704 } 6705 6706 // C++ for OpenCL does not allow the thread_local storage qualifier. 6707 // OpenCL C does not support thread_local either, and 6708 // also reject all other thread storage class specifiers. 6709 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6710 if (TSC != TSCS_unspecified) { 6711 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6712 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_opencl_unknown_type_specifier) 6714 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6715 << DeclSpec::getSpecifierName(TSC) << 1; 6716 D.setInvalidType(); 6717 return false; 6718 } 6719 6720 if (R->isSamplerT()) { 6721 // OpenCL v1.2 s6.9.b p4: 6722 // The sampler type cannot be used with the __local and __global address 6723 // space qualifiers. 6724 if (R.getAddressSpace() == LangAS::opencl_local || 6725 R.getAddressSpace() == LangAS::opencl_global) { 6726 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6727 D.setInvalidType(); 6728 } 6729 6730 // OpenCL v1.2 s6.12.14.1: 6731 // A global sampler must be declared with either the constant address 6732 // space qualifier or with the const qualifier. 6733 if (DC->isTranslationUnit() && 6734 !(R.getAddressSpace() == LangAS::opencl_constant || 6735 R.isConstQualified())) { 6736 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6737 D.setInvalidType(); 6738 } 6739 if (D.isInvalidType()) 6740 return false; 6741 } 6742 return true; 6743 } 6744 6745 NamedDecl *Sema::ActOnVariableDeclarator( 6746 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6747 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6748 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6749 QualType R = TInfo->getType(); 6750 DeclarationName Name = GetNameForDeclarator(D).getName(); 6751 6752 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6753 6754 if (D.isDecompositionDeclarator()) { 6755 // Take the name of the first declarator as our name for diagnostic 6756 // purposes. 6757 auto &Decomp = D.getDecompositionDeclarator(); 6758 if (!Decomp.bindings().empty()) { 6759 II = Decomp.bindings()[0].Name; 6760 Name = II; 6761 } 6762 } else if (!II) { 6763 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6764 return nullptr; 6765 } 6766 6767 6768 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6769 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6770 6771 // dllimport globals without explicit storage class are treated as extern. We 6772 // have to change the storage class this early to get the right DeclContext. 6773 if (SC == SC_None && !DC->isRecord() && 6774 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6775 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6776 SC = SC_Extern; 6777 6778 DeclContext *OriginalDC = DC; 6779 bool IsLocalExternDecl = SC == SC_Extern && 6780 adjustContextForLocalExternDecl(DC); 6781 6782 if (SCSpec == DeclSpec::SCS_mutable) { 6783 // mutable can only appear on non-static class members, so it's always 6784 // an error here 6785 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6786 D.setInvalidType(); 6787 SC = SC_None; 6788 } 6789 6790 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6791 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6792 D.getDeclSpec().getStorageClassSpecLoc())) { 6793 // In C++11, the 'register' storage class specifier is deprecated. 6794 // Suppress the warning in system macros, it's used in macros in some 6795 // popular C system headers, such as in glibc's htonl() macro. 6796 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6797 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6798 : diag::warn_deprecated_register) 6799 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6800 } 6801 6802 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6803 6804 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6805 // C99 6.9p2: The storage-class specifiers auto and register shall not 6806 // appear in the declaration specifiers in an external declaration. 6807 // Global Register+Asm is a GNU extension we support. 6808 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6809 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6810 D.setInvalidType(); 6811 } 6812 } 6813 6814 bool IsMemberSpecialization = false; 6815 bool IsVariableTemplateSpecialization = false; 6816 bool IsPartialSpecialization = false; 6817 bool IsVariableTemplate = false; 6818 VarDecl *NewVD = nullptr; 6819 VarTemplateDecl *NewTemplate = nullptr; 6820 TemplateParameterList *TemplateParams = nullptr; 6821 if (!getLangOpts().CPlusPlus) { 6822 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6823 II, R, TInfo, SC); 6824 6825 if (R->getContainedDeducedType()) 6826 ParsingInitForAutoVars.insert(NewVD); 6827 6828 if (D.isInvalidType()) 6829 NewVD->setInvalidDecl(); 6830 6831 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6832 NewVD->hasLocalStorage()) 6833 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6834 NTCUC_AutoVar, NTCUK_Destruct); 6835 } else { 6836 bool Invalid = false; 6837 6838 if (DC->isRecord() && !CurContext->isRecord()) { 6839 // This is an out-of-line definition of a static data member. 6840 switch (SC) { 6841 case SC_None: 6842 break; 6843 case SC_Static: 6844 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6845 diag::err_static_out_of_line) 6846 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6847 break; 6848 case SC_Auto: 6849 case SC_Register: 6850 case SC_Extern: 6851 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6852 // to names of variables declared in a block or to function parameters. 6853 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6854 // of class members 6855 6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6857 diag::err_storage_class_for_static_member) 6858 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6859 break; 6860 case SC_PrivateExtern: 6861 llvm_unreachable("C storage class in c++!"); 6862 } 6863 } 6864 6865 if (SC == SC_Static && CurContext->isRecord()) { 6866 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6867 // C++ [class.static.data]p2: 6868 // A static data member shall not be a direct member of an unnamed 6869 // or local class 6870 // FIXME: or of a (possibly indirectly) nested class thereof. 6871 if (RD->isLocalClass()) { 6872 Diag(D.getIdentifierLoc(), 6873 diag::err_static_data_member_not_allowed_in_local_class) 6874 << Name << RD->getDeclName() << RD->getTagKind(); 6875 } else if (!RD->getDeclName()) { 6876 Diag(D.getIdentifierLoc(), 6877 diag::err_static_data_member_not_allowed_in_anon_struct) 6878 << Name << RD->getTagKind(); 6879 Invalid = true; 6880 } else if (RD->isUnion()) { 6881 // C++98 [class.union]p1: If a union contains a static data member, 6882 // the program is ill-formed. C++11 drops this restriction. 6883 Diag(D.getIdentifierLoc(), 6884 getLangOpts().CPlusPlus11 6885 ? diag::warn_cxx98_compat_static_data_member_in_union 6886 : diag::ext_static_data_member_in_union) << Name; 6887 } 6888 } 6889 } 6890 6891 // Match up the template parameter lists with the scope specifier, then 6892 // determine whether we have a template or a template specialization. 6893 bool InvalidScope = false; 6894 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6895 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6896 D.getCXXScopeSpec(), 6897 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6898 ? D.getName().TemplateId 6899 : nullptr, 6900 TemplateParamLists, 6901 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6902 Invalid |= InvalidScope; 6903 6904 if (TemplateParams) { 6905 if (!TemplateParams->size() && 6906 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6907 // There is an extraneous 'template<>' for this variable. Complain 6908 // about it, but allow the declaration of the variable. 6909 Diag(TemplateParams->getTemplateLoc(), 6910 diag::err_template_variable_noparams) 6911 << II 6912 << SourceRange(TemplateParams->getTemplateLoc(), 6913 TemplateParams->getRAngleLoc()); 6914 TemplateParams = nullptr; 6915 } else { 6916 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6917 // This is an explicit specialization or a partial specialization. 6918 // FIXME: Check that we can declare a specialization here. 6919 IsVariableTemplateSpecialization = true; 6920 IsPartialSpecialization = TemplateParams->size() > 0; 6921 } else { // if (TemplateParams->size() > 0) 6922 // This is a template declaration. 6923 IsVariableTemplate = true; 6924 6925 // Check that we can declare a template here. 6926 if (CheckTemplateDeclScope(S, TemplateParams)) 6927 return nullptr; 6928 6929 // Only C++1y supports variable templates (N3651). 6930 Diag(D.getIdentifierLoc(), 6931 getLangOpts().CPlusPlus14 6932 ? diag::warn_cxx11_compat_variable_template 6933 : diag::ext_variable_template); 6934 } 6935 } 6936 } else { 6937 assert((Invalid || 6938 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6939 "should have a 'template<>' for this decl"); 6940 } 6941 6942 if (IsVariableTemplateSpecialization) { 6943 SourceLocation TemplateKWLoc = 6944 TemplateParamLists.size() > 0 6945 ? TemplateParamLists[0]->getTemplateLoc() 6946 : SourceLocation(); 6947 DeclResult Res = ActOnVarTemplateSpecialization( 6948 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6949 IsPartialSpecialization); 6950 if (Res.isInvalid()) 6951 return nullptr; 6952 NewVD = cast<VarDecl>(Res.get()); 6953 AddToScope = false; 6954 } else if (D.isDecompositionDeclarator()) { 6955 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6956 D.getIdentifierLoc(), R, TInfo, SC, 6957 Bindings); 6958 } else 6959 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6960 D.getIdentifierLoc(), II, R, TInfo, SC); 6961 6962 // If this is supposed to be a variable template, create it as such. 6963 if (IsVariableTemplate) { 6964 NewTemplate = 6965 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6966 TemplateParams, NewVD); 6967 NewVD->setDescribedVarTemplate(NewTemplate); 6968 } 6969 6970 // If this decl has an auto type in need of deduction, make a note of the 6971 // Decl so we can diagnose uses of it in its own initializer. 6972 if (R->getContainedDeducedType()) 6973 ParsingInitForAutoVars.insert(NewVD); 6974 6975 if (D.isInvalidType() || Invalid) { 6976 NewVD->setInvalidDecl(); 6977 if (NewTemplate) 6978 NewTemplate->setInvalidDecl(); 6979 } 6980 6981 SetNestedNameSpecifier(*this, NewVD, D); 6982 6983 // If we have any template parameter lists that don't directly belong to 6984 // the variable (matching the scope specifier), store them. 6985 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6986 if (TemplateParamLists.size() > VDTemplateParamLists) 6987 NewVD->setTemplateParameterListsInfo( 6988 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6989 } 6990 6991 if (D.getDeclSpec().isInlineSpecified()) { 6992 if (!getLangOpts().CPlusPlus) { 6993 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6994 << 0; 6995 } else if (CurContext->isFunctionOrMethod()) { 6996 // 'inline' is not allowed on block scope variable declaration. 6997 Diag(D.getDeclSpec().getInlineSpecLoc(), 6998 diag::err_inline_declaration_block_scope) << Name 6999 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7000 } else { 7001 Diag(D.getDeclSpec().getInlineSpecLoc(), 7002 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7003 : diag::ext_inline_variable); 7004 NewVD->setInlineSpecified(); 7005 } 7006 } 7007 7008 // Set the lexical context. If the declarator has a C++ scope specifier, the 7009 // lexical context will be different from the semantic context. 7010 NewVD->setLexicalDeclContext(CurContext); 7011 if (NewTemplate) 7012 NewTemplate->setLexicalDeclContext(CurContext); 7013 7014 if (IsLocalExternDecl) { 7015 if (D.isDecompositionDeclarator()) 7016 for (auto *B : Bindings) 7017 B->setLocalExternDecl(); 7018 else 7019 NewVD->setLocalExternDecl(); 7020 } 7021 7022 bool EmitTLSUnsupportedError = false; 7023 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7024 // C++11 [dcl.stc]p4: 7025 // When thread_local is applied to a variable of block scope the 7026 // storage-class-specifier static is implied if it does not appear 7027 // explicitly. 7028 // Core issue: 'static' is not implied if the variable is declared 7029 // 'extern'. 7030 if (NewVD->hasLocalStorage() && 7031 (SCSpec != DeclSpec::SCS_unspecified || 7032 TSCS != DeclSpec::TSCS_thread_local || 7033 !DC->isFunctionOrMethod())) 7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7035 diag::err_thread_non_global) 7036 << DeclSpec::getSpecifierName(TSCS); 7037 else if (!Context.getTargetInfo().isTLSSupported()) { 7038 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7039 // Postpone error emission until we've collected attributes required to 7040 // figure out whether it's a host or device variable and whether the 7041 // error should be ignored. 7042 EmitTLSUnsupportedError = true; 7043 // We still need to mark the variable as TLS so it shows up in AST with 7044 // proper storage class for other tools to use even if we're not going 7045 // to emit any code for it. 7046 NewVD->setTSCSpec(TSCS); 7047 } else 7048 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7049 diag::err_thread_unsupported); 7050 } else 7051 NewVD->setTSCSpec(TSCS); 7052 } 7053 7054 switch (D.getDeclSpec().getConstexprSpecifier()) { 7055 case CSK_unspecified: 7056 break; 7057 7058 case CSK_consteval: 7059 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7060 diag::err_constexpr_wrong_decl_kind) 7061 << D.getDeclSpec().getConstexprSpecifier(); 7062 LLVM_FALLTHROUGH; 7063 7064 case CSK_constexpr: 7065 NewVD->setConstexpr(true); 7066 // C++1z [dcl.spec.constexpr]p1: 7067 // A static data member declared with the constexpr specifier is 7068 // implicitly an inline variable. 7069 if (NewVD->isStaticDataMember() && 7070 (getLangOpts().CPlusPlus17 || 7071 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7072 NewVD->setImplicitlyInline(); 7073 break; 7074 7075 case CSK_constinit: 7076 if (!NewVD->hasGlobalStorage()) 7077 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7078 diag::err_constinit_local_variable); 7079 else 7080 NewVD->addAttr(ConstInitAttr::Create( 7081 Context, D.getDeclSpec().getConstexprSpecLoc(), 7082 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7083 break; 7084 } 7085 7086 // C99 6.7.4p3 7087 // An inline definition of a function with external linkage shall 7088 // not contain a definition of a modifiable object with static or 7089 // thread storage duration... 7090 // We only apply this when the function is required to be defined 7091 // elsewhere, i.e. when the function is not 'extern inline'. Note 7092 // that a local variable with thread storage duration still has to 7093 // be marked 'static'. Also note that it's possible to get these 7094 // semantics in C++ using __attribute__((gnu_inline)). 7095 if (SC == SC_Static && S->getFnParent() != nullptr && 7096 !NewVD->getType().isConstQualified()) { 7097 FunctionDecl *CurFD = getCurFunctionDecl(); 7098 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7099 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7100 diag::warn_static_local_in_extern_inline); 7101 MaybeSuggestAddingStaticToDecl(CurFD); 7102 } 7103 } 7104 7105 if (D.getDeclSpec().isModulePrivateSpecified()) { 7106 if (IsVariableTemplateSpecialization) 7107 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7108 << (IsPartialSpecialization ? 1 : 0) 7109 << FixItHint::CreateRemoval( 7110 D.getDeclSpec().getModulePrivateSpecLoc()); 7111 else if (IsMemberSpecialization) 7112 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7113 << 2 7114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7115 else if (NewVD->hasLocalStorage()) 7116 Diag(NewVD->getLocation(), diag::err_module_private_local) 7117 << 0 << NewVD->getDeclName() 7118 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7119 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7120 else { 7121 NewVD->setModulePrivate(); 7122 if (NewTemplate) 7123 NewTemplate->setModulePrivate(); 7124 for (auto *B : Bindings) 7125 B->setModulePrivate(); 7126 } 7127 } 7128 7129 if (getLangOpts().OpenCL) { 7130 7131 deduceOpenCLAddressSpace(NewVD); 7132 7133 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7134 } 7135 7136 // Handle attributes prior to checking for duplicates in MergeVarDecl 7137 ProcessDeclAttributes(S, NewVD, D); 7138 7139 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7140 if (EmitTLSUnsupportedError && 7141 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7142 (getLangOpts().OpenMPIsDevice && 7143 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7145 diag::err_thread_unsupported); 7146 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7147 // storage [duration]." 7148 if (SC == SC_None && S->getFnParent() != nullptr && 7149 (NewVD->hasAttr<CUDASharedAttr>() || 7150 NewVD->hasAttr<CUDAConstantAttr>())) { 7151 NewVD->setStorageClass(SC_Static); 7152 } 7153 } 7154 7155 // Ensure that dllimport globals without explicit storage class are treated as 7156 // extern. The storage class is set above using parsed attributes. Now we can 7157 // check the VarDecl itself. 7158 assert(!NewVD->hasAttr<DLLImportAttr>() || 7159 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7160 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7161 7162 // In auto-retain/release, infer strong retension for variables of 7163 // retainable type. 7164 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7165 NewVD->setInvalidDecl(); 7166 7167 // Handle GNU asm-label extension (encoded as an attribute). 7168 if (Expr *E = (Expr*)D.getAsmLabel()) { 7169 // The parser guarantees this is a string. 7170 StringLiteral *SE = cast<StringLiteral>(E); 7171 StringRef Label = SE->getString(); 7172 if (S->getFnParent() != nullptr) { 7173 switch (SC) { 7174 case SC_None: 7175 case SC_Auto: 7176 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7177 break; 7178 case SC_Register: 7179 // Local Named register 7180 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7181 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7182 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7183 break; 7184 case SC_Static: 7185 case SC_Extern: 7186 case SC_PrivateExtern: 7187 break; 7188 } 7189 } else if (SC == SC_Register) { 7190 // Global Named register 7191 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7192 const auto &TI = Context.getTargetInfo(); 7193 bool HasSizeMismatch; 7194 7195 if (!TI.isValidGCCRegisterName(Label)) 7196 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7197 else if (!TI.validateGlobalRegisterVariable(Label, 7198 Context.getTypeSize(R), 7199 HasSizeMismatch)) 7200 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7201 else if (HasSizeMismatch) 7202 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7203 } 7204 7205 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7206 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7207 NewVD->setInvalidDecl(true); 7208 } 7209 } 7210 7211 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7212 /*IsLiteralLabel=*/true, 7213 SE->getStrTokenLoc(0))); 7214 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7215 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7216 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7217 if (I != ExtnameUndeclaredIdentifiers.end()) { 7218 if (isDeclExternC(NewVD)) { 7219 NewVD->addAttr(I->second); 7220 ExtnameUndeclaredIdentifiers.erase(I); 7221 } else 7222 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7223 << /*Variable*/1 << NewVD; 7224 } 7225 } 7226 7227 // Find the shadowed declaration before filtering for scope. 7228 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7229 ? getShadowedDeclaration(NewVD, Previous) 7230 : nullptr; 7231 7232 // Don't consider existing declarations that are in a different 7233 // scope and are out-of-semantic-context declarations (if the new 7234 // declaration has linkage). 7235 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7236 D.getCXXScopeSpec().isNotEmpty() || 7237 IsMemberSpecialization || 7238 IsVariableTemplateSpecialization); 7239 7240 // Check whether the previous declaration is in the same block scope. This 7241 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7242 if (getLangOpts().CPlusPlus && 7243 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7244 NewVD->setPreviousDeclInSameBlockScope( 7245 Previous.isSingleResult() && !Previous.isShadowed() && 7246 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7247 7248 if (!getLangOpts().CPlusPlus) { 7249 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7250 } else { 7251 // If this is an explicit specialization of a static data member, check it. 7252 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7253 CheckMemberSpecialization(NewVD, Previous)) 7254 NewVD->setInvalidDecl(); 7255 7256 // Merge the decl with the existing one if appropriate. 7257 if (!Previous.empty()) { 7258 if (Previous.isSingleResult() && 7259 isa<FieldDecl>(Previous.getFoundDecl()) && 7260 D.getCXXScopeSpec().isSet()) { 7261 // The user tried to define a non-static data member 7262 // out-of-line (C++ [dcl.meaning]p1). 7263 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7264 << D.getCXXScopeSpec().getRange(); 7265 Previous.clear(); 7266 NewVD->setInvalidDecl(); 7267 } 7268 } else if (D.getCXXScopeSpec().isSet()) { 7269 // No previous declaration in the qualifying scope. 7270 Diag(D.getIdentifierLoc(), diag::err_no_member) 7271 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7272 << D.getCXXScopeSpec().getRange(); 7273 NewVD->setInvalidDecl(); 7274 } 7275 7276 if (!IsVariableTemplateSpecialization) 7277 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7278 7279 if (NewTemplate) { 7280 VarTemplateDecl *PrevVarTemplate = 7281 NewVD->getPreviousDecl() 7282 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7283 : nullptr; 7284 7285 // Check the template parameter list of this declaration, possibly 7286 // merging in the template parameter list from the previous variable 7287 // template declaration. 7288 if (CheckTemplateParameterList( 7289 TemplateParams, 7290 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7291 : nullptr, 7292 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7293 DC->isDependentContext()) 7294 ? TPC_ClassTemplateMember 7295 : TPC_VarTemplate)) 7296 NewVD->setInvalidDecl(); 7297 7298 // If we are providing an explicit specialization of a static variable 7299 // template, make a note of that. 7300 if (PrevVarTemplate && 7301 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7302 PrevVarTemplate->setMemberSpecialization(); 7303 } 7304 } 7305 7306 // Diagnose shadowed variables iff this isn't a redeclaration. 7307 if (ShadowedDecl && !D.isRedeclaration()) 7308 CheckShadow(NewVD, ShadowedDecl, Previous); 7309 7310 ProcessPragmaWeak(S, NewVD); 7311 7312 // If this is the first declaration of an extern C variable, update 7313 // the map of such variables. 7314 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7315 isIncompleteDeclExternC(*this, NewVD)) 7316 RegisterLocallyScopedExternCDecl(NewVD, S); 7317 7318 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7319 MangleNumberingContext *MCtx; 7320 Decl *ManglingContextDecl; 7321 std::tie(MCtx, ManglingContextDecl) = 7322 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7323 if (MCtx) { 7324 Context.setManglingNumber( 7325 NewVD, MCtx->getManglingNumber( 7326 NewVD, getMSManglingNumber(getLangOpts(), S))); 7327 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7328 } 7329 } 7330 7331 // Special handling of variable named 'main'. 7332 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7333 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7334 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7335 7336 // C++ [basic.start.main]p3 7337 // A program that declares a variable main at global scope is ill-formed. 7338 if (getLangOpts().CPlusPlus) 7339 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7340 7341 // In C, and external-linkage variable named main results in undefined 7342 // behavior. 7343 else if (NewVD->hasExternalFormalLinkage()) 7344 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7345 } 7346 7347 if (D.isRedeclaration() && !Previous.empty()) { 7348 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7349 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7350 D.isFunctionDefinition()); 7351 } 7352 7353 if (NewTemplate) { 7354 if (NewVD->isInvalidDecl()) 7355 NewTemplate->setInvalidDecl(); 7356 ActOnDocumentableDecl(NewTemplate); 7357 return NewTemplate; 7358 } 7359 7360 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7361 CompleteMemberSpecialization(NewVD, Previous); 7362 7363 return NewVD; 7364 } 7365 7366 /// Enum describing the %select options in diag::warn_decl_shadow. 7367 enum ShadowedDeclKind { 7368 SDK_Local, 7369 SDK_Global, 7370 SDK_StaticMember, 7371 SDK_Field, 7372 SDK_Typedef, 7373 SDK_Using 7374 }; 7375 7376 /// Determine what kind of declaration we're shadowing. 7377 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7378 const DeclContext *OldDC) { 7379 if (isa<TypeAliasDecl>(ShadowedDecl)) 7380 return SDK_Using; 7381 else if (isa<TypedefDecl>(ShadowedDecl)) 7382 return SDK_Typedef; 7383 else if (isa<RecordDecl>(OldDC)) 7384 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7385 7386 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7387 } 7388 7389 /// Return the location of the capture if the given lambda captures the given 7390 /// variable \p VD, or an invalid source location otherwise. 7391 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7392 const VarDecl *VD) { 7393 for (const Capture &Capture : LSI->Captures) { 7394 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7395 return Capture.getLocation(); 7396 } 7397 return SourceLocation(); 7398 } 7399 7400 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7401 const LookupResult &R) { 7402 // Only diagnose if we're shadowing an unambiguous field or variable. 7403 if (R.getResultKind() != LookupResult::Found) 7404 return false; 7405 7406 // Return false if warning is ignored. 7407 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7408 } 7409 7410 /// Return the declaration shadowed by the given variable \p D, or null 7411 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7412 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7413 const LookupResult &R) { 7414 if (!shouldWarnIfShadowedDecl(Diags, R)) 7415 return nullptr; 7416 7417 // Don't diagnose declarations at file scope. 7418 if (D->hasGlobalStorage()) 7419 return nullptr; 7420 7421 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7422 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7423 ? ShadowedDecl 7424 : nullptr; 7425 } 7426 7427 /// Return the declaration shadowed by the given typedef \p D, or null 7428 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7429 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7430 const LookupResult &R) { 7431 // Don't warn if typedef declaration is part of a class 7432 if (D->getDeclContext()->isRecord()) 7433 return nullptr; 7434 7435 if (!shouldWarnIfShadowedDecl(Diags, R)) 7436 return nullptr; 7437 7438 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7439 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7440 } 7441 7442 /// Diagnose variable or built-in function shadowing. Implements 7443 /// -Wshadow. 7444 /// 7445 /// This method is called whenever a VarDecl is added to a "useful" 7446 /// scope. 7447 /// 7448 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7449 /// \param R the lookup of the name 7450 /// 7451 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7452 const LookupResult &R) { 7453 DeclContext *NewDC = D->getDeclContext(); 7454 7455 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7456 // Fields are not shadowed by variables in C++ static methods. 7457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7458 if (MD->isStatic()) 7459 return; 7460 7461 // Fields shadowed by constructor parameters are a special case. Usually 7462 // the constructor initializes the field with the parameter. 7463 if (isa<CXXConstructorDecl>(NewDC)) 7464 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7465 // Remember that this was shadowed so we can either warn about its 7466 // modification or its existence depending on warning settings. 7467 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7468 return; 7469 } 7470 } 7471 7472 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7473 if (shadowedVar->isExternC()) { 7474 // For shadowing external vars, make sure that we point to the global 7475 // declaration, not a locally scoped extern declaration. 7476 for (auto I : shadowedVar->redecls()) 7477 if (I->isFileVarDecl()) { 7478 ShadowedDecl = I; 7479 break; 7480 } 7481 } 7482 7483 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7484 7485 unsigned WarningDiag = diag::warn_decl_shadow; 7486 SourceLocation CaptureLoc; 7487 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7488 isa<CXXMethodDecl>(NewDC)) { 7489 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7490 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7491 if (RD->getLambdaCaptureDefault() == LCD_None) { 7492 // Try to avoid warnings for lambdas with an explicit capture list. 7493 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7494 // Warn only when the lambda captures the shadowed decl explicitly. 7495 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7496 if (CaptureLoc.isInvalid()) 7497 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7498 } else { 7499 // Remember that this was shadowed so we can avoid the warning if the 7500 // shadowed decl isn't captured and the warning settings allow it. 7501 cast<LambdaScopeInfo>(getCurFunction()) 7502 ->ShadowingDecls.push_back( 7503 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7504 return; 7505 } 7506 } 7507 7508 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7509 // A variable can't shadow a local variable in an enclosing scope, if 7510 // they are separated by a non-capturing declaration context. 7511 for (DeclContext *ParentDC = NewDC; 7512 ParentDC && !ParentDC->Equals(OldDC); 7513 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7514 // Only block literals, captured statements, and lambda expressions 7515 // can capture; other scopes don't. 7516 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7517 !isLambdaCallOperator(ParentDC)) { 7518 return; 7519 } 7520 } 7521 } 7522 } 7523 } 7524 7525 // Only warn about certain kinds of shadowing for class members. 7526 if (NewDC && NewDC->isRecord()) { 7527 // In particular, don't warn about shadowing non-class members. 7528 if (!OldDC->isRecord()) 7529 return; 7530 7531 // TODO: should we warn about static data members shadowing 7532 // static data members from base classes? 7533 7534 // TODO: don't diagnose for inaccessible shadowed members. 7535 // This is hard to do perfectly because we might friend the 7536 // shadowing context, but that's just a false negative. 7537 } 7538 7539 7540 DeclarationName Name = R.getLookupName(); 7541 7542 // Emit warning and note. 7543 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7544 return; 7545 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7546 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7547 if (!CaptureLoc.isInvalid()) 7548 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7549 << Name << /*explicitly*/ 1; 7550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7551 } 7552 7553 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7554 /// when these variables are captured by the lambda. 7555 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7556 for (const auto &Shadow : LSI->ShadowingDecls) { 7557 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7558 // Try to avoid the warning when the shadowed decl isn't captured. 7559 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7560 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7561 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7562 ? diag::warn_decl_shadow_uncaptured_local 7563 : diag::warn_decl_shadow) 7564 << Shadow.VD->getDeclName() 7565 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7566 if (!CaptureLoc.isInvalid()) 7567 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7568 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7569 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7570 } 7571 } 7572 7573 /// Check -Wshadow without the advantage of a previous lookup. 7574 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7575 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7576 return; 7577 7578 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7579 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7580 LookupName(R, S); 7581 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7582 CheckShadow(D, ShadowedDecl, R); 7583 } 7584 7585 /// Check if 'E', which is an expression that is about to be modified, refers 7586 /// to a constructor parameter that shadows a field. 7587 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7588 // Quickly ignore expressions that can't be shadowing ctor parameters. 7589 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7590 return; 7591 E = E->IgnoreParenImpCasts(); 7592 auto *DRE = dyn_cast<DeclRefExpr>(E); 7593 if (!DRE) 7594 return; 7595 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7596 auto I = ShadowingDecls.find(D); 7597 if (I == ShadowingDecls.end()) 7598 return; 7599 const NamedDecl *ShadowedDecl = I->second; 7600 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7601 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7602 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7604 7605 // Avoid issuing multiple warnings about the same decl. 7606 ShadowingDecls.erase(I); 7607 } 7608 7609 /// Check for conflict between this global or extern "C" declaration and 7610 /// previous global or extern "C" declarations. This is only used in C++. 7611 template<typename T> 7612 static bool checkGlobalOrExternCConflict( 7613 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7614 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7615 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7616 7617 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7618 // The common case: this global doesn't conflict with any extern "C" 7619 // declaration. 7620 return false; 7621 } 7622 7623 if (Prev) { 7624 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7625 // Both the old and new declarations have C language linkage. This is a 7626 // redeclaration. 7627 Previous.clear(); 7628 Previous.addDecl(Prev); 7629 return true; 7630 } 7631 7632 // This is a global, non-extern "C" declaration, and there is a previous 7633 // non-global extern "C" declaration. Diagnose if this is a variable 7634 // declaration. 7635 if (!isa<VarDecl>(ND)) 7636 return false; 7637 } else { 7638 // The declaration is extern "C". Check for any declaration in the 7639 // translation unit which might conflict. 7640 if (IsGlobal) { 7641 // We have already performed the lookup into the translation unit. 7642 IsGlobal = false; 7643 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7644 I != E; ++I) { 7645 if (isa<VarDecl>(*I)) { 7646 Prev = *I; 7647 break; 7648 } 7649 } 7650 } else { 7651 DeclContext::lookup_result R = 7652 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7653 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7654 I != E; ++I) { 7655 if (isa<VarDecl>(*I)) { 7656 Prev = *I; 7657 break; 7658 } 7659 // FIXME: If we have any other entity with this name in global scope, 7660 // the declaration is ill-formed, but that is a defect: it breaks the 7661 // 'stat' hack, for instance. Only variables can have mangled name 7662 // clashes with extern "C" declarations, so only they deserve a 7663 // diagnostic. 7664 } 7665 } 7666 7667 if (!Prev) 7668 return false; 7669 } 7670 7671 // Use the first declaration's location to ensure we point at something which 7672 // is lexically inside an extern "C" linkage-spec. 7673 assert(Prev && "should have found a previous declaration to diagnose"); 7674 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7675 Prev = FD->getFirstDecl(); 7676 else 7677 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7678 7679 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7680 << IsGlobal << ND; 7681 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7682 << IsGlobal; 7683 return false; 7684 } 7685 7686 /// Apply special rules for handling extern "C" declarations. Returns \c true 7687 /// if we have found that this is a redeclaration of some prior entity. 7688 /// 7689 /// Per C++ [dcl.link]p6: 7690 /// Two declarations [for a function or variable] with C language linkage 7691 /// with the same name that appear in different scopes refer to the same 7692 /// [entity]. An entity with C language linkage shall not be declared with 7693 /// the same name as an entity in global scope. 7694 template<typename T> 7695 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7696 LookupResult &Previous) { 7697 if (!S.getLangOpts().CPlusPlus) { 7698 // In C, when declaring a global variable, look for a corresponding 'extern' 7699 // variable declared in function scope. We don't need this in C++, because 7700 // we find local extern decls in the surrounding file-scope DeclContext. 7701 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7702 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7703 Previous.clear(); 7704 Previous.addDecl(Prev); 7705 return true; 7706 } 7707 } 7708 return false; 7709 } 7710 7711 // A declaration in the translation unit can conflict with an extern "C" 7712 // declaration. 7713 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7714 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7715 7716 // An extern "C" declaration can conflict with a declaration in the 7717 // translation unit or can be a redeclaration of an extern "C" declaration 7718 // in another scope. 7719 if (isIncompleteDeclExternC(S,ND)) 7720 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7721 7722 // Neither global nor extern "C": nothing to do. 7723 return false; 7724 } 7725 7726 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7727 // If the decl is already known invalid, don't check it. 7728 if (NewVD->isInvalidDecl()) 7729 return; 7730 7731 QualType T = NewVD->getType(); 7732 7733 // Defer checking an 'auto' type until its initializer is attached. 7734 if (T->isUndeducedType()) 7735 return; 7736 7737 if (NewVD->hasAttrs()) 7738 CheckAlignasUnderalignment(NewVD); 7739 7740 if (T->isObjCObjectType()) { 7741 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7742 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7743 T = Context.getObjCObjectPointerType(T); 7744 NewVD->setType(T); 7745 } 7746 7747 // Emit an error if an address space was applied to decl with local storage. 7748 // This includes arrays of objects with address space qualifiers, but not 7749 // automatic variables that point to other address spaces. 7750 // ISO/IEC TR 18037 S5.1.2 7751 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7752 T.getAddressSpace() != LangAS::Default) { 7753 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7754 NewVD->setInvalidDecl(); 7755 return; 7756 } 7757 7758 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7759 // scope. 7760 if (getLangOpts().OpenCLVersion == 120 && 7761 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7762 NewVD->isStaticLocal()) { 7763 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7764 NewVD->setInvalidDecl(); 7765 return; 7766 } 7767 7768 if (getLangOpts().OpenCL) { 7769 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7770 if (NewVD->hasAttr<BlocksAttr>()) { 7771 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7772 return; 7773 } 7774 7775 if (T->isBlockPointerType()) { 7776 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7777 // can't use 'extern' storage class. 7778 if (!T.isConstQualified()) { 7779 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7780 << 0 /*const*/; 7781 NewVD->setInvalidDecl(); 7782 return; 7783 } 7784 if (NewVD->hasExternalStorage()) { 7785 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7786 NewVD->setInvalidDecl(); 7787 return; 7788 } 7789 } 7790 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7791 // __constant address space. 7792 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7793 // variables inside a function can also be declared in the global 7794 // address space. 7795 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7796 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7797 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7798 NewVD->hasExternalStorage()) { 7799 if (!T->isSamplerT() && 7800 !(T.getAddressSpace() == LangAS::opencl_constant || 7801 (T.getAddressSpace() == LangAS::opencl_global && 7802 (getLangOpts().OpenCLVersion == 200 || 7803 getLangOpts().OpenCLCPlusPlus)))) { 7804 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7805 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7806 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7807 << Scope << "global or constant"; 7808 else 7809 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7810 << Scope << "constant"; 7811 NewVD->setInvalidDecl(); 7812 return; 7813 } 7814 } else { 7815 if (T.getAddressSpace() == LangAS::opencl_global) { 7816 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7817 << 1 /*is any function*/ << "global"; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 if (T.getAddressSpace() == LangAS::opencl_constant || 7822 T.getAddressSpace() == LangAS::opencl_local) { 7823 FunctionDecl *FD = getCurFunctionDecl(); 7824 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7825 // in functions. 7826 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7827 if (T.getAddressSpace() == LangAS::opencl_constant) 7828 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7829 << 0 /*non-kernel only*/ << "constant"; 7830 else 7831 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7832 << 0 /*non-kernel only*/ << "local"; 7833 NewVD->setInvalidDecl(); 7834 return; 7835 } 7836 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7837 // in the outermost scope of a kernel function. 7838 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7839 if (!getCurScope()->isFunctionScope()) { 7840 if (T.getAddressSpace() == LangAS::opencl_constant) 7841 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7842 << "constant"; 7843 else 7844 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7845 << "local"; 7846 NewVD->setInvalidDecl(); 7847 return; 7848 } 7849 } 7850 } else if (T.getAddressSpace() != LangAS::opencl_private && 7851 // If we are parsing a template we didn't deduce an addr 7852 // space yet. 7853 T.getAddressSpace() != LangAS::Default) { 7854 // Do not allow other address spaces on automatic variable. 7855 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7856 NewVD->setInvalidDecl(); 7857 return; 7858 } 7859 } 7860 } 7861 7862 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7863 && !NewVD->hasAttr<BlocksAttr>()) { 7864 if (getLangOpts().getGC() != LangOptions::NonGC) 7865 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7866 else { 7867 assert(!getLangOpts().ObjCAutoRefCount); 7868 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7869 } 7870 } 7871 7872 bool isVM = T->isVariablyModifiedType(); 7873 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7874 NewVD->hasAttr<BlocksAttr>()) 7875 setFunctionHasBranchProtectedScope(); 7876 7877 if ((isVM && NewVD->hasLinkage()) || 7878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7879 bool SizeIsNegative; 7880 llvm::APSInt Oversized; 7881 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7883 QualType FixedT; 7884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7885 FixedT = FixedTInfo->getType(); 7886 else if (FixedTInfo) { 7887 // Type and type-as-written are canonically different. We need to fix up 7888 // both types separately. 7889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7890 Oversized); 7891 } 7892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7893 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7894 // FIXME: This won't give the correct result for 7895 // int a[10][n]; 7896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7897 7898 if (NewVD->isFileVarDecl()) 7899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7900 << SizeRange; 7901 else if (NewVD->isStaticLocal()) 7902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7903 << SizeRange; 7904 else 7905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7906 << SizeRange; 7907 NewVD->setInvalidDecl(); 7908 return; 7909 } 7910 7911 if (!FixedTInfo) { 7912 if (NewVD->isFileVarDecl()) 7913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7914 else 7915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7916 NewVD->setInvalidDecl(); 7917 return; 7918 } 7919 7920 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7921 NewVD->setType(FixedT); 7922 NewVD->setTypeSourceInfo(FixedTInfo); 7923 } 7924 7925 if (T->isVoidType()) { 7926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7927 // of objects and functions. 7928 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7930 << T; 7931 NewVD->setInvalidDecl(); 7932 return; 7933 } 7934 } 7935 7936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7938 NewVD->setInvalidDecl(); 7939 return; 7940 } 7941 7942 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 7943 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 7944 NewVD->setInvalidDecl(); 7945 return; 7946 } 7947 7948 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7949 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7950 NewVD->setInvalidDecl(); 7951 return; 7952 } 7953 7954 if (NewVD->isConstexpr() && !T->isDependentType() && 7955 RequireLiteralType(NewVD->getLocation(), T, 7956 diag::err_constexpr_var_non_literal)) { 7957 NewVD->setInvalidDecl(); 7958 return; 7959 } 7960 } 7961 7962 /// Perform semantic checking on a newly-created variable 7963 /// declaration. 7964 /// 7965 /// This routine performs all of the type-checking required for a 7966 /// variable declaration once it has been built. It is used both to 7967 /// check variables after they have been parsed and their declarators 7968 /// have been translated into a declaration, and to check variables 7969 /// that have been instantiated from a template. 7970 /// 7971 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7972 /// 7973 /// Returns true if the variable declaration is a redeclaration. 7974 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7975 CheckVariableDeclarationType(NewVD); 7976 7977 // If the decl is already known invalid, don't check it. 7978 if (NewVD->isInvalidDecl()) 7979 return false; 7980 7981 // If we did not find anything by this name, look for a non-visible 7982 // extern "C" declaration with the same name. 7983 if (Previous.empty() && 7984 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7985 Previous.setShadowed(); 7986 7987 if (!Previous.empty()) { 7988 MergeVarDecl(NewVD, Previous); 7989 return true; 7990 } 7991 return false; 7992 } 7993 7994 namespace { 7995 struct FindOverriddenMethod { 7996 Sema *S; 7997 CXXMethodDecl *Method; 7998 7999 /// Member lookup function that determines whether a given C++ 8000 /// method overrides a method in a base class, to be used with 8001 /// CXXRecordDecl::lookupInBases(). 8002 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8003 RecordDecl *BaseRecord = 8004 Specifier->getType()->castAs<RecordType>()->getDecl(); 8005 8006 DeclarationName Name = Method->getDeclName(); 8007 8008 // FIXME: Do we care about other names here too? 8009 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8010 // We really want to find the base class destructor here. 8011 QualType T = S->Context.getTypeDeclType(BaseRecord); 8012 CanQualType CT = S->Context.getCanonicalType(T); 8013 8014 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8015 } 8016 8017 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8018 Path.Decls = Path.Decls.slice(1)) { 8019 NamedDecl *D = Path.Decls.front(); 8020 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8021 if (MD->isVirtual() && 8022 !S->IsOverload( 8023 Method, MD, /*UseMemberUsingDeclRules=*/false, 8024 /*ConsiderCudaAttrs=*/true, 8025 // C++2a [class.virtual]p2 does not consider requires clauses 8026 // when overriding. 8027 /*ConsiderRequiresClauses=*/false)) 8028 return true; 8029 } 8030 } 8031 8032 return false; 8033 } 8034 }; 8035 } // end anonymous namespace 8036 8037 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8038 /// and if so, check that it's a valid override and remember it. 8039 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8040 // Look for methods in base classes that this method might override. 8041 CXXBasePaths Paths; 8042 FindOverriddenMethod FOM; 8043 FOM.Method = MD; 8044 FOM.S = this; 8045 bool AddedAny = false; 8046 if (DC->lookupInBases(FOM, Paths)) { 8047 for (auto *I : Paths.found_decls()) { 8048 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8049 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8050 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8051 !CheckOverridingFunctionAttributes(MD, OldMD) && 8052 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8053 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8054 AddedAny = true; 8055 } 8056 } 8057 } 8058 } 8059 8060 return AddedAny; 8061 } 8062 8063 namespace { 8064 // Struct for holding all of the extra arguments needed by 8065 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8066 struct ActOnFDArgs { 8067 Scope *S; 8068 Declarator &D; 8069 MultiTemplateParamsArg TemplateParamLists; 8070 bool AddToScope; 8071 }; 8072 } // end anonymous namespace 8073 8074 namespace { 8075 8076 // Callback to only accept typo corrections that have a non-zero edit distance. 8077 // Also only accept corrections that have the same parent decl. 8078 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8079 public: 8080 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8081 CXXRecordDecl *Parent) 8082 : Context(Context), OriginalFD(TypoFD), 8083 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8084 8085 bool ValidateCandidate(const TypoCorrection &candidate) override { 8086 if (candidate.getEditDistance() == 0) 8087 return false; 8088 8089 SmallVector<unsigned, 1> MismatchedParams; 8090 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8091 CDeclEnd = candidate.end(); 8092 CDecl != CDeclEnd; ++CDecl) { 8093 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8094 8095 if (FD && !FD->hasBody() && 8096 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8097 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8098 CXXRecordDecl *Parent = MD->getParent(); 8099 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8100 return true; 8101 } else if (!ExpectedParent) { 8102 return true; 8103 } 8104 } 8105 } 8106 8107 return false; 8108 } 8109 8110 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8111 return std::make_unique<DifferentNameValidatorCCC>(*this); 8112 } 8113 8114 private: 8115 ASTContext &Context; 8116 FunctionDecl *OriginalFD; 8117 CXXRecordDecl *ExpectedParent; 8118 }; 8119 8120 } // end anonymous namespace 8121 8122 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8123 TypoCorrectedFunctionDefinitions.insert(F); 8124 } 8125 8126 /// Generate diagnostics for an invalid function redeclaration. 8127 /// 8128 /// This routine handles generating the diagnostic messages for an invalid 8129 /// function redeclaration, including finding possible similar declarations 8130 /// or performing typo correction if there are no previous declarations with 8131 /// the same name. 8132 /// 8133 /// Returns a NamedDecl iff typo correction was performed and substituting in 8134 /// the new declaration name does not cause new errors. 8135 static NamedDecl *DiagnoseInvalidRedeclaration( 8136 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8137 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8138 DeclarationName Name = NewFD->getDeclName(); 8139 DeclContext *NewDC = NewFD->getDeclContext(); 8140 SmallVector<unsigned, 1> MismatchedParams; 8141 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8142 TypoCorrection Correction; 8143 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8144 unsigned DiagMsg = 8145 IsLocalFriend ? diag::err_no_matching_local_friend : 8146 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8147 diag::err_member_decl_does_not_match; 8148 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8149 IsLocalFriend ? Sema::LookupLocalFriendName 8150 : Sema::LookupOrdinaryName, 8151 Sema::ForVisibleRedeclaration); 8152 8153 NewFD->setInvalidDecl(); 8154 if (IsLocalFriend) 8155 SemaRef.LookupName(Prev, S); 8156 else 8157 SemaRef.LookupQualifiedName(Prev, NewDC); 8158 assert(!Prev.isAmbiguous() && 8159 "Cannot have an ambiguity in previous-declaration lookup"); 8160 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8161 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8162 MD ? MD->getParent() : nullptr); 8163 if (!Prev.empty()) { 8164 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8165 Func != FuncEnd; ++Func) { 8166 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8167 if (FD && 8168 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8169 // Add 1 to the index so that 0 can mean the mismatch didn't 8170 // involve a parameter 8171 unsigned ParamNum = 8172 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8173 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8174 } 8175 } 8176 // If the qualified name lookup yielded nothing, try typo correction 8177 } else if ((Correction = SemaRef.CorrectTypo( 8178 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8179 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8180 IsLocalFriend ? nullptr : NewDC))) { 8181 // Set up everything for the call to ActOnFunctionDeclarator 8182 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8183 ExtraArgs.D.getIdentifierLoc()); 8184 Previous.clear(); 8185 Previous.setLookupName(Correction.getCorrection()); 8186 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8187 CDeclEnd = Correction.end(); 8188 CDecl != CDeclEnd; ++CDecl) { 8189 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8190 if (FD && !FD->hasBody() && 8191 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8192 Previous.addDecl(FD); 8193 } 8194 } 8195 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8196 8197 NamedDecl *Result; 8198 // Retry building the function declaration with the new previous 8199 // declarations, and with errors suppressed. 8200 { 8201 // Trap errors. 8202 Sema::SFINAETrap Trap(SemaRef); 8203 8204 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8205 // pieces need to verify the typo-corrected C++ declaration and hopefully 8206 // eliminate the need for the parameter pack ExtraArgs. 8207 Result = SemaRef.ActOnFunctionDeclarator( 8208 ExtraArgs.S, ExtraArgs.D, 8209 Correction.getCorrectionDecl()->getDeclContext(), 8210 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8211 ExtraArgs.AddToScope); 8212 8213 if (Trap.hasErrorOccurred()) 8214 Result = nullptr; 8215 } 8216 8217 if (Result) { 8218 // Determine which correction we picked. 8219 Decl *Canonical = Result->getCanonicalDecl(); 8220 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8221 I != E; ++I) 8222 if ((*I)->getCanonicalDecl() == Canonical) 8223 Correction.setCorrectionDecl(*I); 8224 8225 // Let Sema know about the correction. 8226 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8227 SemaRef.diagnoseTypo( 8228 Correction, 8229 SemaRef.PDiag(IsLocalFriend 8230 ? diag::err_no_matching_local_friend_suggest 8231 : diag::err_member_decl_does_not_match_suggest) 8232 << Name << NewDC << IsDefinition); 8233 return Result; 8234 } 8235 8236 // Pretend the typo correction never occurred 8237 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8238 ExtraArgs.D.getIdentifierLoc()); 8239 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8240 Previous.clear(); 8241 Previous.setLookupName(Name); 8242 } 8243 8244 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8245 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8246 8247 bool NewFDisConst = false; 8248 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8249 NewFDisConst = NewMD->isConst(); 8250 8251 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8252 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8253 NearMatch != NearMatchEnd; ++NearMatch) { 8254 FunctionDecl *FD = NearMatch->first; 8255 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8256 bool FDisConst = MD && MD->isConst(); 8257 bool IsMember = MD || !IsLocalFriend; 8258 8259 // FIXME: These notes are poorly worded for the local friend case. 8260 if (unsigned Idx = NearMatch->second) { 8261 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8262 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8263 if (Loc.isInvalid()) Loc = FD->getLocation(); 8264 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8265 : diag::note_local_decl_close_param_match) 8266 << Idx << FDParam->getType() 8267 << NewFD->getParamDecl(Idx - 1)->getType(); 8268 } else if (FDisConst != NewFDisConst) { 8269 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8270 << NewFDisConst << FD->getSourceRange().getEnd(); 8271 } else 8272 SemaRef.Diag(FD->getLocation(), 8273 IsMember ? diag::note_member_def_close_match 8274 : diag::note_local_decl_close_match); 8275 } 8276 return nullptr; 8277 } 8278 8279 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8280 switch (D.getDeclSpec().getStorageClassSpec()) { 8281 default: llvm_unreachable("Unknown storage class!"); 8282 case DeclSpec::SCS_auto: 8283 case DeclSpec::SCS_register: 8284 case DeclSpec::SCS_mutable: 8285 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8286 diag::err_typecheck_sclass_func); 8287 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8288 D.setInvalidType(); 8289 break; 8290 case DeclSpec::SCS_unspecified: break; 8291 case DeclSpec::SCS_extern: 8292 if (D.getDeclSpec().isExternInLinkageSpec()) 8293 return SC_None; 8294 return SC_Extern; 8295 case DeclSpec::SCS_static: { 8296 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8297 // C99 6.7.1p5: 8298 // The declaration of an identifier for a function that has 8299 // block scope shall have no explicit storage-class specifier 8300 // other than extern 8301 // See also (C++ [dcl.stc]p4). 8302 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8303 diag::err_static_block_func); 8304 break; 8305 } else 8306 return SC_Static; 8307 } 8308 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8309 } 8310 8311 // No explicit storage class has already been returned 8312 return SC_None; 8313 } 8314 8315 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8316 DeclContext *DC, QualType &R, 8317 TypeSourceInfo *TInfo, 8318 StorageClass SC, 8319 bool &IsVirtualOkay) { 8320 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8321 DeclarationName Name = NameInfo.getName(); 8322 8323 FunctionDecl *NewFD = nullptr; 8324 bool isInline = D.getDeclSpec().isInlineSpecified(); 8325 8326 if (!SemaRef.getLangOpts().CPlusPlus) { 8327 // Determine whether the function was written with a 8328 // prototype. This true when: 8329 // - there is a prototype in the declarator, or 8330 // - the type R of the function is some kind of typedef or other non- 8331 // attributed reference to a type name (which eventually refers to a 8332 // function type). 8333 bool HasPrototype = 8334 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8335 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8336 8337 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8338 R, TInfo, SC, isInline, HasPrototype, 8339 CSK_unspecified, 8340 /*TrailingRequiresClause=*/nullptr); 8341 if (D.isInvalidType()) 8342 NewFD->setInvalidDecl(); 8343 8344 return NewFD; 8345 } 8346 8347 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8348 8349 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8350 if (ConstexprKind == CSK_constinit) { 8351 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8352 diag::err_constexpr_wrong_decl_kind) 8353 << ConstexprKind; 8354 ConstexprKind = CSK_unspecified; 8355 D.getMutableDeclSpec().ClearConstexprSpec(); 8356 } 8357 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8358 8359 // Check that the return type is not an abstract class type. 8360 // For record types, this is done by the AbstractClassUsageDiagnoser once 8361 // the class has been completely parsed. 8362 if (!DC->isRecord() && 8363 SemaRef.RequireNonAbstractType( 8364 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8365 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8366 D.setInvalidType(); 8367 8368 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8369 // This is a C++ constructor declaration. 8370 assert(DC->isRecord() && 8371 "Constructors can only be declared in a member context"); 8372 8373 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8374 return CXXConstructorDecl::Create( 8375 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8376 TInfo, ExplicitSpecifier, isInline, 8377 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8378 TrailingRequiresClause); 8379 8380 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8381 // This is a C++ destructor declaration. 8382 if (DC->isRecord()) { 8383 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8384 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8385 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8386 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8387 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8388 TrailingRequiresClause); 8389 8390 // If the destructor needs an implicit exception specification, set it 8391 // now. FIXME: It'd be nice to be able to create the right type to start 8392 // with, but the type needs to reference the destructor declaration. 8393 if (SemaRef.getLangOpts().CPlusPlus11) 8394 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8395 8396 IsVirtualOkay = true; 8397 return NewDD; 8398 8399 } else { 8400 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8401 D.setInvalidType(); 8402 8403 // Create a FunctionDecl to satisfy the function definition parsing 8404 // code path. 8405 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8406 D.getIdentifierLoc(), Name, R, TInfo, SC, 8407 isInline, 8408 /*hasPrototype=*/true, ConstexprKind, 8409 TrailingRequiresClause); 8410 } 8411 8412 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8413 if (!DC->isRecord()) { 8414 SemaRef.Diag(D.getIdentifierLoc(), 8415 diag::err_conv_function_not_member); 8416 return nullptr; 8417 } 8418 8419 SemaRef.CheckConversionDeclarator(D, R, SC); 8420 if (D.isInvalidType()) 8421 return nullptr; 8422 8423 IsVirtualOkay = true; 8424 return CXXConversionDecl::Create( 8425 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8426 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8427 TrailingRequiresClause); 8428 8429 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8430 if (TrailingRequiresClause) 8431 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8432 diag::err_trailing_requires_clause_on_deduction_guide) 8433 << TrailingRequiresClause->getSourceRange(); 8434 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8435 8436 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8437 ExplicitSpecifier, NameInfo, R, TInfo, 8438 D.getEndLoc()); 8439 } else if (DC->isRecord()) { 8440 // If the name of the function is the same as the name of the record, 8441 // then this must be an invalid constructor that has a return type. 8442 // (The parser checks for a return type and makes the declarator a 8443 // constructor if it has no return type). 8444 if (Name.getAsIdentifierInfo() && 8445 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8446 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8447 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8448 << SourceRange(D.getIdentifierLoc()); 8449 return nullptr; 8450 } 8451 8452 // This is a C++ method declaration. 8453 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8454 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8455 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8456 TrailingRequiresClause); 8457 IsVirtualOkay = !Ret->isStatic(); 8458 return Ret; 8459 } else { 8460 bool isFriend = 8461 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8462 if (!isFriend && SemaRef.CurContext->isRecord()) 8463 return nullptr; 8464 8465 // Determine whether the function was written with a 8466 // prototype. This true when: 8467 // - we're in C++ (where every function has a prototype), 8468 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8469 R, TInfo, SC, isInline, true /*HasPrototype*/, 8470 ConstexprKind, TrailingRequiresClause); 8471 } 8472 } 8473 8474 enum OpenCLParamType { 8475 ValidKernelParam, 8476 PtrPtrKernelParam, 8477 PtrKernelParam, 8478 InvalidAddrSpacePtrKernelParam, 8479 InvalidKernelParam, 8480 RecordKernelParam 8481 }; 8482 8483 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8484 // Size dependent types are just typedefs to normal integer types 8485 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8486 // integers other than by their names. 8487 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8488 8489 // Remove typedefs one by one until we reach a typedef 8490 // for a size dependent type. 8491 QualType DesugaredTy = Ty; 8492 do { 8493 ArrayRef<StringRef> Names(SizeTypeNames); 8494 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8495 if (Names.end() != Match) 8496 return true; 8497 8498 Ty = DesugaredTy; 8499 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8500 } while (DesugaredTy != Ty); 8501 8502 return false; 8503 } 8504 8505 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8506 if (PT->isPointerType()) { 8507 QualType PointeeType = PT->getPointeeType(); 8508 if (PointeeType->isPointerType()) 8509 return PtrPtrKernelParam; 8510 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8511 PointeeType.getAddressSpace() == LangAS::opencl_private || 8512 PointeeType.getAddressSpace() == LangAS::Default) 8513 return InvalidAddrSpacePtrKernelParam; 8514 return PtrKernelParam; 8515 } 8516 8517 // OpenCL v1.2 s6.9.k: 8518 // Arguments to kernel functions in a program cannot be declared with the 8519 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8520 // uintptr_t or a struct and/or union that contain fields declared to be one 8521 // of these built-in scalar types. 8522 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8523 return InvalidKernelParam; 8524 8525 if (PT->isImageType()) 8526 return PtrKernelParam; 8527 8528 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8529 return InvalidKernelParam; 8530 8531 // OpenCL extension spec v1.2 s9.5: 8532 // This extension adds support for half scalar and vector types as built-in 8533 // types that can be used for arithmetic operations, conversions etc. 8534 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8535 return InvalidKernelParam; 8536 8537 if (PT->isRecordType()) 8538 return RecordKernelParam; 8539 8540 // Look into an array argument to check if it has a forbidden type. 8541 if (PT->isArrayType()) { 8542 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8543 // Call ourself to check an underlying type of an array. Since the 8544 // getPointeeOrArrayElementType returns an innermost type which is not an 8545 // array, this recursive call only happens once. 8546 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8547 } 8548 8549 return ValidKernelParam; 8550 } 8551 8552 static void checkIsValidOpenCLKernelParameter( 8553 Sema &S, 8554 Declarator &D, 8555 ParmVarDecl *Param, 8556 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8557 QualType PT = Param->getType(); 8558 8559 // Cache the valid types we encounter to avoid rechecking structs that are 8560 // used again 8561 if (ValidTypes.count(PT.getTypePtr())) 8562 return; 8563 8564 switch (getOpenCLKernelParameterType(S, PT)) { 8565 case PtrPtrKernelParam: 8566 // OpenCL v1.2 s6.9.a: 8567 // A kernel function argument cannot be declared as a 8568 // pointer to a pointer type. 8569 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8570 D.setInvalidType(); 8571 return; 8572 8573 case InvalidAddrSpacePtrKernelParam: 8574 // OpenCL v1.0 s6.5: 8575 // __kernel function arguments declared to be a pointer of a type can point 8576 // to one of the following address spaces only : __global, __local or 8577 // __constant. 8578 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8579 D.setInvalidType(); 8580 return; 8581 8582 // OpenCL v1.2 s6.9.k: 8583 // Arguments to kernel functions in a program cannot be declared with the 8584 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8585 // uintptr_t or a struct and/or union that contain fields declared to be 8586 // one of these built-in scalar types. 8587 8588 case InvalidKernelParam: 8589 // OpenCL v1.2 s6.8 n: 8590 // A kernel function argument cannot be declared 8591 // of event_t type. 8592 // Do not diagnose half type since it is diagnosed as invalid argument 8593 // type for any function elsewhere. 8594 if (!PT->isHalfType()) { 8595 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8596 8597 // Explain what typedefs are involved. 8598 const TypedefType *Typedef = nullptr; 8599 while ((Typedef = PT->getAs<TypedefType>())) { 8600 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8601 // SourceLocation may be invalid for a built-in type. 8602 if (Loc.isValid()) 8603 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8604 PT = Typedef->desugar(); 8605 } 8606 } 8607 8608 D.setInvalidType(); 8609 return; 8610 8611 case PtrKernelParam: 8612 case ValidKernelParam: 8613 ValidTypes.insert(PT.getTypePtr()); 8614 return; 8615 8616 case RecordKernelParam: 8617 break; 8618 } 8619 8620 // Track nested structs we will inspect 8621 SmallVector<const Decl *, 4> VisitStack; 8622 8623 // Track where we are in the nested structs. Items will migrate from 8624 // VisitStack to HistoryStack as we do the DFS for bad field. 8625 SmallVector<const FieldDecl *, 4> HistoryStack; 8626 HistoryStack.push_back(nullptr); 8627 8628 // At this point we already handled everything except of a RecordType or 8629 // an ArrayType of a RecordType. 8630 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8631 const RecordType *RecTy = 8632 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8633 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8634 8635 VisitStack.push_back(RecTy->getDecl()); 8636 assert(VisitStack.back() && "First decl null?"); 8637 8638 do { 8639 const Decl *Next = VisitStack.pop_back_val(); 8640 if (!Next) { 8641 assert(!HistoryStack.empty()); 8642 // Found a marker, we have gone up a level 8643 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8644 ValidTypes.insert(Hist->getType().getTypePtr()); 8645 8646 continue; 8647 } 8648 8649 // Adds everything except the original parameter declaration (which is not a 8650 // field itself) to the history stack. 8651 const RecordDecl *RD; 8652 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8653 HistoryStack.push_back(Field); 8654 8655 QualType FieldTy = Field->getType(); 8656 // Other field types (known to be valid or invalid) are handled while we 8657 // walk around RecordDecl::fields(). 8658 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8659 "Unexpected type."); 8660 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8661 8662 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8663 } else { 8664 RD = cast<RecordDecl>(Next); 8665 } 8666 8667 // Add a null marker so we know when we've gone back up a level 8668 VisitStack.push_back(nullptr); 8669 8670 for (const auto *FD : RD->fields()) { 8671 QualType QT = FD->getType(); 8672 8673 if (ValidTypes.count(QT.getTypePtr())) 8674 continue; 8675 8676 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8677 if (ParamType == ValidKernelParam) 8678 continue; 8679 8680 if (ParamType == RecordKernelParam) { 8681 VisitStack.push_back(FD); 8682 continue; 8683 } 8684 8685 // OpenCL v1.2 s6.9.p: 8686 // Arguments to kernel functions that are declared to be a struct or union 8687 // do not allow OpenCL objects to be passed as elements of the struct or 8688 // union. 8689 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8690 ParamType == InvalidAddrSpacePtrKernelParam) { 8691 S.Diag(Param->getLocation(), 8692 diag::err_record_with_pointers_kernel_param) 8693 << PT->isUnionType() 8694 << PT; 8695 } else { 8696 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8697 } 8698 8699 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8700 << OrigRecDecl->getDeclName(); 8701 8702 // We have an error, now let's go back up through history and show where 8703 // the offending field came from 8704 for (ArrayRef<const FieldDecl *>::const_iterator 8705 I = HistoryStack.begin() + 1, 8706 E = HistoryStack.end(); 8707 I != E; ++I) { 8708 const FieldDecl *OuterField = *I; 8709 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8710 << OuterField->getType(); 8711 } 8712 8713 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8714 << QT->isPointerType() 8715 << QT; 8716 D.setInvalidType(); 8717 return; 8718 } 8719 } while (!VisitStack.empty()); 8720 } 8721 8722 /// Find the DeclContext in which a tag is implicitly declared if we see an 8723 /// elaborated type specifier in the specified context, and lookup finds 8724 /// nothing. 8725 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8726 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8727 DC = DC->getParent(); 8728 return DC; 8729 } 8730 8731 /// Find the Scope in which a tag is implicitly declared if we see an 8732 /// elaborated type specifier in the specified context, and lookup finds 8733 /// nothing. 8734 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8735 while (S->isClassScope() || 8736 (LangOpts.CPlusPlus && 8737 S->isFunctionPrototypeScope()) || 8738 ((S->getFlags() & Scope::DeclScope) == 0) || 8739 (S->getEntity() && S->getEntity()->isTransparentContext())) 8740 S = S->getParent(); 8741 return S; 8742 } 8743 8744 NamedDecl* 8745 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8746 TypeSourceInfo *TInfo, LookupResult &Previous, 8747 MultiTemplateParamsArg TemplateParamListsRef, 8748 bool &AddToScope) { 8749 QualType R = TInfo->getType(); 8750 8751 assert(R->isFunctionType()); 8752 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8753 for (TemplateParameterList *TPL : TemplateParamListsRef) 8754 TemplateParamLists.push_back(TPL); 8755 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8756 if (!TemplateParamLists.empty() && 8757 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8758 TemplateParamLists.back() = Invented; 8759 else 8760 TemplateParamLists.push_back(Invented); 8761 } 8762 8763 // TODO: consider using NameInfo for diagnostic. 8764 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8765 DeclarationName Name = NameInfo.getName(); 8766 StorageClass SC = getFunctionStorageClass(*this, D); 8767 8768 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8769 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8770 diag::err_invalid_thread) 8771 << DeclSpec::getSpecifierName(TSCS); 8772 8773 if (D.isFirstDeclarationOfMember()) 8774 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8775 D.getIdentifierLoc()); 8776 8777 bool isFriend = false; 8778 FunctionTemplateDecl *FunctionTemplate = nullptr; 8779 bool isMemberSpecialization = false; 8780 bool isFunctionTemplateSpecialization = false; 8781 8782 bool isDependentClassScopeExplicitSpecialization = false; 8783 bool HasExplicitTemplateArgs = false; 8784 TemplateArgumentListInfo TemplateArgs; 8785 8786 bool isVirtualOkay = false; 8787 8788 DeclContext *OriginalDC = DC; 8789 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8790 8791 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8792 isVirtualOkay); 8793 if (!NewFD) return nullptr; 8794 8795 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8796 NewFD->setTopLevelDeclInObjCContainer(); 8797 8798 // Set the lexical context. If this is a function-scope declaration, or has a 8799 // C++ scope specifier, or is the object of a friend declaration, the lexical 8800 // context will be different from the semantic context. 8801 NewFD->setLexicalDeclContext(CurContext); 8802 8803 if (IsLocalExternDecl) 8804 NewFD->setLocalExternDecl(); 8805 8806 if (getLangOpts().CPlusPlus) { 8807 bool isInline = D.getDeclSpec().isInlineSpecified(); 8808 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8809 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8810 isFriend = D.getDeclSpec().isFriendSpecified(); 8811 if (isFriend && !isInline && D.isFunctionDefinition()) { 8812 // C++ [class.friend]p5 8813 // A function can be defined in a friend declaration of a 8814 // class . . . . Such a function is implicitly inline. 8815 NewFD->setImplicitlyInline(); 8816 } 8817 8818 // If this is a method defined in an __interface, and is not a constructor 8819 // or an overloaded operator, then set the pure flag (isVirtual will already 8820 // return true). 8821 if (const CXXRecordDecl *Parent = 8822 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8823 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8824 NewFD->setPure(true); 8825 8826 // C++ [class.union]p2 8827 // A union can have member functions, but not virtual functions. 8828 if (isVirtual && Parent->isUnion()) 8829 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8830 } 8831 8832 SetNestedNameSpecifier(*this, NewFD, D); 8833 isMemberSpecialization = false; 8834 isFunctionTemplateSpecialization = false; 8835 if (D.isInvalidType()) 8836 NewFD->setInvalidDecl(); 8837 8838 // Match up the template parameter lists with the scope specifier, then 8839 // determine whether we have a template or a template specialization. 8840 bool Invalid = false; 8841 TemplateParameterList *TemplateParams = 8842 MatchTemplateParametersToScopeSpecifier( 8843 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8844 D.getCXXScopeSpec(), 8845 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8846 ? D.getName().TemplateId 8847 : nullptr, 8848 TemplateParamLists, isFriend, isMemberSpecialization, 8849 Invalid); 8850 if (TemplateParams) { 8851 if (TemplateParams->size() > 0) { 8852 // This is a function template 8853 8854 // Check that we can declare a template here. 8855 if (CheckTemplateDeclScope(S, TemplateParams)) 8856 NewFD->setInvalidDecl(); 8857 8858 // A destructor cannot be a template. 8859 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8860 Diag(NewFD->getLocation(), diag::err_destructor_template); 8861 NewFD->setInvalidDecl(); 8862 } 8863 8864 // If we're adding a template to a dependent context, we may need to 8865 // rebuilding some of the types used within the template parameter list, 8866 // now that we know what the current instantiation is. 8867 if (DC->isDependentContext()) { 8868 ContextRAII SavedContext(*this, DC); 8869 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8870 Invalid = true; 8871 } 8872 8873 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8874 NewFD->getLocation(), 8875 Name, TemplateParams, 8876 NewFD); 8877 FunctionTemplate->setLexicalDeclContext(CurContext); 8878 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8879 8880 // For source fidelity, store the other template param lists. 8881 if (TemplateParamLists.size() > 1) { 8882 NewFD->setTemplateParameterListsInfo(Context, 8883 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8884 .drop_back(1)); 8885 } 8886 } else { 8887 // This is a function template specialization. 8888 isFunctionTemplateSpecialization = true; 8889 // For source fidelity, store all the template param lists. 8890 if (TemplateParamLists.size() > 0) 8891 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8892 8893 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8894 if (isFriend) { 8895 // We want to remove the "template<>", found here. 8896 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8897 8898 // If we remove the template<> and the name is not a 8899 // template-id, we're actually silently creating a problem: 8900 // the friend declaration will refer to an untemplated decl, 8901 // and clearly the user wants a template specialization. So 8902 // we need to insert '<>' after the name. 8903 SourceLocation InsertLoc; 8904 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8905 InsertLoc = D.getName().getSourceRange().getEnd(); 8906 InsertLoc = getLocForEndOfToken(InsertLoc); 8907 } 8908 8909 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8910 << Name << RemoveRange 8911 << FixItHint::CreateRemoval(RemoveRange) 8912 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8913 } 8914 } 8915 } else { 8916 // All template param lists were matched against the scope specifier: 8917 // this is NOT (an explicit specialization of) a template. 8918 if (TemplateParamLists.size() > 0) 8919 // For source fidelity, store all the template param lists. 8920 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8921 } 8922 8923 if (Invalid) { 8924 NewFD->setInvalidDecl(); 8925 if (FunctionTemplate) 8926 FunctionTemplate->setInvalidDecl(); 8927 } 8928 8929 // C++ [dcl.fct.spec]p5: 8930 // The virtual specifier shall only be used in declarations of 8931 // nonstatic class member functions that appear within a 8932 // member-specification of a class declaration; see 10.3. 8933 // 8934 if (isVirtual && !NewFD->isInvalidDecl()) { 8935 if (!isVirtualOkay) { 8936 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8937 diag::err_virtual_non_function); 8938 } else if (!CurContext->isRecord()) { 8939 // 'virtual' was specified outside of the class. 8940 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8941 diag::err_virtual_out_of_class) 8942 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8943 } else if (NewFD->getDescribedFunctionTemplate()) { 8944 // C++ [temp.mem]p3: 8945 // A member function template shall not be virtual. 8946 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8947 diag::err_virtual_member_function_template) 8948 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8949 } else { 8950 // Okay: Add virtual to the method. 8951 NewFD->setVirtualAsWritten(true); 8952 } 8953 8954 if (getLangOpts().CPlusPlus14 && 8955 NewFD->getReturnType()->isUndeducedType()) 8956 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8957 } 8958 8959 if (getLangOpts().CPlusPlus14 && 8960 (NewFD->isDependentContext() || 8961 (isFriend && CurContext->isDependentContext())) && 8962 NewFD->getReturnType()->isUndeducedType()) { 8963 // If the function template is referenced directly (for instance, as a 8964 // member of the current instantiation), pretend it has a dependent type. 8965 // This is not really justified by the standard, but is the only sane 8966 // thing to do. 8967 // FIXME: For a friend function, we have not marked the function as being 8968 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8969 const FunctionProtoType *FPT = 8970 NewFD->getType()->castAs<FunctionProtoType>(); 8971 QualType Result = 8972 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8973 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8974 FPT->getExtProtoInfo())); 8975 } 8976 8977 // C++ [dcl.fct.spec]p3: 8978 // The inline specifier shall not appear on a block scope function 8979 // declaration. 8980 if (isInline && !NewFD->isInvalidDecl()) { 8981 if (CurContext->isFunctionOrMethod()) { 8982 // 'inline' is not allowed on block scope function declaration. 8983 Diag(D.getDeclSpec().getInlineSpecLoc(), 8984 diag::err_inline_declaration_block_scope) << Name 8985 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8986 } 8987 } 8988 8989 // C++ [dcl.fct.spec]p6: 8990 // The explicit specifier shall be used only in the declaration of a 8991 // constructor or conversion function within its class definition; 8992 // see 12.3.1 and 12.3.2. 8993 if (hasExplicit && !NewFD->isInvalidDecl() && 8994 !isa<CXXDeductionGuideDecl>(NewFD)) { 8995 if (!CurContext->isRecord()) { 8996 // 'explicit' was specified outside of the class. 8997 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8998 diag::err_explicit_out_of_class) 8999 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9000 } else if (!isa<CXXConstructorDecl>(NewFD) && 9001 !isa<CXXConversionDecl>(NewFD)) { 9002 // 'explicit' was specified on a function that wasn't a constructor 9003 // or conversion function. 9004 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9005 diag::err_explicit_non_ctor_or_conv_function) 9006 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9007 } 9008 } 9009 9010 if (ConstexprSpecKind ConstexprKind = 9011 D.getDeclSpec().getConstexprSpecifier()) { 9012 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9013 // are implicitly inline. 9014 NewFD->setImplicitlyInline(); 9015 9016 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9017 // be either constructors or to return a literal type. Therefore, 9018 // destructors cannot be declared constexpr. 9019 if (isa<CXXDestructorDecl>(NewFD) && 9020 (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) { 9021 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9022 << ConstexprKind; 9023 NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr); 9024 } 9025 // C++20 [dcl.constexpr]p2: An allocation function, or a 9026 // deallocation function shall not be declared with the consteval 9027 // specifier. 9028 if (ConstexprKind == CSK_consteval && 9029 (NewFD->getOverloadedOperator() == OO_New || 9030 NewFD->getOverloadedOperator() == OO_Array_New || 9031 NewFD->getOverloadedOperator() == OO_Delete || 9032 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9033 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9034 diag::err_invalid_consteval_decl_kind) 9035 << NewFD; 9036 NewFD->setConstexprKind(CSK_constexpr); 9037 } 9038 } 9039 9040 // If __module_private__ was specified, mark the function accordingly. 9041 if (D.getDeclSpec().isModulePrivateSpecified()) { 9042 if (isFunctionTemplateSpecialization) { 9043 SourceLocation ModulePrivateLoc 9044 = D.getDeclSpec().getModulePrivateSpecLoc(); 9045 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9046 << 0 9047 << FixItHint::CreateRemoval(ModulePrivateLoc); 9048 } else { 9049 NewFD->setModulePrivate(); 9050 if (FunctionTemplate) 9051 FunctionTemplate->setModulePrivate(); 9052 } 9053 } 9054 9055 if (isFriend) { 9056 if (FunctionTemplate) { 9057 FunctionTemplate->setObjectOfFriendDecl(); 9058 FunctionTemplate->setAccess(AS_public); 9059 } 9060 NewFD->setObjectOfFriendDecl(); 9061 NewFD->setAccess(AS_public); 9062 } 9063 9064 // If a function is defined as defaulted or deleted, mark it as such now. 9065 // We'll do the relevant checks on defaulted / deleted functions later. 9066 switch (D.getFunctionDefinitionKind()) { 9067 case FDK_Declaration: 9068 case FDK_Definition: 9069 break; 9070 9071 case FDK_Defaulted: 9072 NewFD->setDefaulted(); 9073 break; 9074 9075 case FDK_Deleted: 9076 NewFD->setDeletedAsWritten(); 9077 break; 9078 } 9079 9080 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9081 D.isFunctionDefinition()) { 9082 // C++ [class.mfct]p2: 9083 // A member function may be defined (8.4) in its class definition, in 9084 // which case it is an inline member function (7.1.2) 9085 NewFD->setImplicitlyInline(); 9086 } 9087 9088 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9089 !CurContext->isRecord()) { 9090 // C++ [class.static]p1: 9091 // A data or function member of a class may be declared static 9092 // in a class definition, in which case it is a static member of 9093 // the class. 9094 9095 // Complain about the 'static' specifier if it's on an out-of-line 9096 // member function definition. 9097 9098 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9099 // member function template declaration and class member template 9100 // declaration (MSVC versions before 2015), warn about this. 9101 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9102 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9103 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9104 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9105 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9106 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9107 } 9108 9109 // C++11 [except.spec]p15: 9110 // A deallocation function with no exception-specification is treated 9111 // as if it were specified with noexcept(true). 9112 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9113 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9114 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9115 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9116 NewFD->setType(Context.getFunctionType( 9117 FPT->getReturnType(), FPT->getParamTypes(), 9118 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9119 } 9120 9121 // Filter out previous declarations that don't match the scope. 9122 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9123 D.getCXXScopeSpec().isNotEmpty() || 9124 isMemberSpecialization || 9125 isFunctionTemplateSpecialization); 9126 9127 // Handle GNU asm-label extension (encoded as an attribute). 9128 if (Expr *E = (Expr*) D.getAsmLabel()) { 9129 // The parser guarantees this is a string. 9130 StringLiteral *SE = cast<StringLiteral>(E); 9131 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9132 /*IsLiteralLabel=*/true, 9133 SE->getStrTokenLoc(0))); 9134 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9135 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9136 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9137 if (I != ExtnameUndeclaredIdentifiers.end()) { 9138 if (isDeclExternC(NewFD)) { 9139 NewFD->addAttr(I->second); 9140 ExtnameUndeclaredIdentifiers.erase(I); 9141 } else 9142 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9143 << /*Variable*/0 << NewFD; 9144 } 9145 } 9146 9147 // Copy the parameter declarations from the declarator D to the function 9148 // declaration NewFD, if they are available. First scavenge them into Params. 9149 SmallVector<ParmVarDecl*, 16> Params; 9150 unsigned FTIIdx; 9151 if (D.isFunctionDeclarator(FTIIdx)) { 9152 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9153 9154 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9155 // function that takes no arguments, not a function that takes a 9156 // single void argument. 9157 // We let through "const void" here because Sema::GetTypeForDeclarator 9158 // already checks for that case. 9159 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9160 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9161 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9162 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9163 Param->setDeclContext(NewFD); 9164 Params.push_back(Param); 9165 9166 if (Param->isInvalidDecl()) 9167 NewFD->setInvalidDecl(); 9168 } 9169 } 9170 9171 if (!getLangOpts().CPlusPlus) { 9172 // In C, find all the tag declarations from the prototype and move them 9173 // into the function DeclContext. Remove them from the surrounding tag 9174 // injection context of the function, which is typically but not always 9175 // the TU. 9176 DeclContext *PrototypeTagContext = 9177 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9178 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9179 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9180 9181 // We don't want to reparent enumerators. Look at their parent enum 9182 // instead. 9183 if (!TD) { 9184 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9185 TD = cast<EnumDecl>(ECD->getDeclContext()); 9186 } 9187 if (!TD) 9188 continue; 9189 DeclContext *TagDC = TD->getLexicalDeclContext(); 9190 if (!TagDC->containsDecl(TD)) 9191 continue; 9192 TagDC->removeDecl(TD); 9193 TD->setDeclContext(NewFD); 9194 NewFD->addDecl(TD); 9195 9196 // Preserve the lexical DeclContext if it is not the surrounding tag 9197 // injection context of the FD. In this example, the semantic context of 9198 // E will be f and the lexical context will be S, while both the 9199 // semantic and lexical contexts of S will be f: 9200 // void f(struct S { enum E { a } f; } s); 9201 if (TagDC != PrototypeTagContext) 9202 TD->setLexicalDeclContext(TagDC); 9203 } 9204 } 9205 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9206 // When we're declaring a function with a typedef, typeof, etc as in the 9207 // following example, we'll need to synthesize (unnamed) 9208 // parameters for use in the declaration. 9209 // 9210 // @code 9211 // typedef void fn(int); 9212 // fn f; 9213 // @endcode 9214 9215 // Synthesize a parameter for each argument type. 9216 for (const auto &AI : FT->param_types()) { 9217 ParmVarDecl *Param = 9218 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9219 Param->setScopeInfo(0, Params.size()); 9220 Params.push_back(Param); 9221 } 9222 } else { 9223 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9224 "Should not need args for typedef of non-prototype fn"); 9225 } 9226 9227 // Finally, we know we have the right number of parameters, install them. 9228 NewFD->setParams(Params); 9229 9230 if (D.getDeclSpec().isNoreturnSpecified()) 9231 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9232 D.getDeclSpec().getNoreturnSpecLoc(), 9233 AttributeCommonInfo::AS_Keyword)); 9234 9235 // Functions returning a variably modified type violate C99 6.7.5.2p2 9236 // because all functions have linkage. 9237 if (!NewFD->isInvalidDecl() && 9238 NewFD->getReturnType()->isVariablyModifiedType()) { 9239 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9240 NewFD->setInvalidDecl(); 9241 } 9242 9243 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9244 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9245 !NewFD->hasAttr<SectionAttr>()) 9246 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9247 Context, PragmaClangTextSection.SectionName, 9248 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9249 9250 // Apply an implicit SectionAttr if #pragma code_seg is active. 9251 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9252 !NewFD->hasAttr<SectionAttr>()) { 9253 NewFD->addAttr(SectionAttr::CreateImplicit( 9254 Context, CodeSegStack.CurrentValue->getString(), 9255 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9256 SectionAttr::Declspec_allocate)); 9257 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9258 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9259 ASTContext::PSF_Read, 9260 NewFD)) 9261 NewFD->dropAttr<SectionAttr>(); 9262 } 9263 9264 // Apply an implicit CodeSegAttr from class declspec or 9265 // apply an implicit SectionAttr from #pragma code_seg if active. 9266 if (!NewFD->hasAttr<CodeSegAttr>()) { 9267 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9268 D.isFunctionDefinition())) { 9269 NewFD->addAttr(SAttr); 9270 } 9271 } 9272 9273 // Handle attributes. 9274 ProcessDeclAttributes(S, NewFD, D); 9275 9276 if (getLangOpts().OpenCL) { 9277 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9278 // type declaration will generate a compilation error. 9279 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9280 if (AddressSpace != LangAS::Default) { 9281 Diag(NewFD->getLocation(), 9282 diag::err_opencl_return_value_with_address_space); 9283 NewFD->setInvalidDecl(); 9284 } 9285 } 9286 9287 if (!getLangOpts().CPlusPlus) { 9288 // Perform semantic checking on the function declaration. 9289 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9290 CheckMain(NewFD, D.getDeclSpec()); 9291 9292 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9293 CheckMSVCRTEntryPoint(NewFD); 9294 9295 if (!NewFD->isInvalidDecl()) 9296 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9297 isMemberSpecialization)); 9298 else if (!Previous.empty()) 9299 // Recover gracefully from an invalid redeclaration. 9300 D.setRedeclaration(true); 9301 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9302 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9303 "previous declaration set still overloaded"); 9304 9305 // Diagnose no-prototype function declarations with calling conventions that 9306 // don't support variadic calls. Only do this in C and do it after merging 9307 // possibly prototyped redeclarations. 9308 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9309 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9310 CallingConv CC = FT->getExtInfo().getCC(); 9311 if (!supportsVariadicCall(CC)) { 9312 // Windows system headers sometimes accidentally use stdcall without 9313 // (void) parameters, so we relax this to a warning. 9314 int DiagID = 9315 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9316 Diag(NewFD->getLocation(), DiagID) 9317 << FunctionType::getNameForCallConv(CC); 9318 } 9319 } 9320 9321 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9322 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9323 checkNonTrivialCUnion(NewFD->getReturnType(), 9324 NewFD->getReturnTypeSourceRange().getBegin(), 9325 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9326 } else { 9327 // C++11 [replacement.functions]p3: 9328 // The program's definitions shall not be specified as inline. 9329 // 9330 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9331 // 9332 // Suppress the diagnostic if the function is __attribute__((used)), since 9333 // that forces an external definition to be emitted. 9334 if (D.getDeclSpec().isInlineSpecified() && 9335 NewFD->isReplaceableGlobalAllocationFunction() && 9336 !NewFD->hasAttr<UsedAttr>()) 9337 Diag(D.getDeclSpec().getInlineSpecLoc(), 9338 diag::ext_operator_new_delete_declared_inline) 9339 << NewFD->getDeclName(); 9340 9341 // If the declarator is a template-id, translate the parser's template 9342 // argument list into our AST format. 9343 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9344 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9345 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9346 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9347 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9348 TemplateId->NumArgs); 9349 translateTemplateArguments(TemplateArgsPtr, 9350 TemplateArgs); 9351 9352 HasExplicitTemplateArgs = true; 9353 9354 if (NewFD->isInvalidDecl()) { 9355 HasExplicitTemplateArgs = false; 9356 } else if (FunctionTemplate) { 9357 // Function template with explicit template arguments. 9358 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9359 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9360 9361 HasExplicitTemplateArgs = false; 9362 } else { 9363 assert((isFunctionTemplateSpecialization || 9364 D.getDeclSpec().isFriendSpecified()) && 9365 "should have a 'template<>' for this decl"); 9366 // "friend void foo<>(int);" is an implicit specialization decl. 9367 isFunctionTemplateSpecialization = true; 9368 } 9369 } else if (isFriend && isFunctionTemplateSpecialization) { 9370 // This combination is only possible in a recovery case; the user 9371 // wrote something like: 9372 // template <> friend void foo(int); 9373 // which we're recovering from as if the user had written: 9374 // friend void foo<>(int); 9375 // Go ahead and fake up a template id. 9376 HasExplicitTemplateArgs = true; 9377 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9378 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9379 } 9380 9381 // We do not add HD attributes to specializations here because 9382 // they may have different constexpr-ness compared to their 9383 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9384 // may end up with different effective targets. Instead, a 9385 // specialization inherits its target attributes from its template 9386 // in the CheckFunctionTemplateSpecialization() call below. 9387 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9388 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9389 9390 // If it's a friend (and only if it's a friend), it's possible 9391 // that either the specialized function type or the specialized 9392 // template is dependent, and therefore matching will fail. In 9393 // this case, don't check the specialization yet. 9394 bool InstantiationDependent = false; 9395 if (isFunctionTemplateSpecialization && isFriend && 9396 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9397 TemplateSpecializationType::anyDependentTemplateArguments( 9398 TemplateArgs, 9399 InstantiationDependent))) { 9400 assert(HasExplicitTemplateArgs && 9401 "friend function specialization without template args"); 9402 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9403 Previous)) 9404 NewFD->setInvalidDecl(); 9405 } else if (isFunctionTemplateSpecialization) { 9406 if (CurContext->isDependentContext() && CurContext->isRecord() 9407 && !isFriend) { 9408 isDependentClassScopeExplicitSpecialization = true; 9409 } else if (!NewFD->isInvalidDecl() && 9410 CheckFunctionTemplateSpecialization( 9411 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9412 Previous)) 9413 NewFD->setInvalidDecl(); 9414 9415 // C++ [dcl.stc]p1: 9416 // A storage-class-specifier shall not be specified in an explicit 9417 // specialization (14.7.3) 9418 FunctionTemplateSpecializationInfo *Info = 9419 NewFD->getTemplateSpecializationInfo(); 9420 if (Info && SC != SC_None) { 9421 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9422 Diag(NewFD->getLocation(), 9423 diag::err_explicit_specialization_inconsistent_storage_class) 9424 << SC 9425 << FixItHint::CreateRemoval( 9426 D.getDeclSpec().getStorageClassSpecLoc()); 9427 9428 else 9429 Diag(NewFD->getLocation(), 9430 diag::ext_explicit_specialization_storage_class) 9431 << FixItHint::CreateRemoval( 9432 D.getDeclSpec().getStorageClassSpecLoc()); 9433 } 9434 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9435 if (CheckMemberSpecialization(NewFD, Previous)) 9436 NewFD->setInvalidDecl(); 9437 } 9438 9439 // Perform semantic checking on the function declaration. 9440 if (!isDependentClassScopeExplicitSpecialization) { 9441 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9442 CheckMain(NewFD, D.getDeclSpec()); 9443 9444 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9445 CheckMSVCRTEntryPoint(NewFD); 9446 9447 if (!NewFD->isInvalidDecl()) 9448 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9449 isMemberSpecialization)); 9450 else if (!Previous.empty()) 9451 // Recover gracefully from an invalid redeclaration. 9452 D.setRedeclaration(true); 9453 } 9454 9455 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9456 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9457 "previous declaration set still overloaded"); 9458 9459 NamedDecl *PrincipalDecl = (FunctionTemplate 9460 ? cast<NamedDecl>(FunctionTemplate) 9461 : NewFD); 9462 9463 if (isFriend && NewFD->getPreviousDecl()) { 9464 AccessSpecifier Access = AS_public; 9465 if (!NewFD->isInvalidDecl()) 9466 Access = NewFD->getPreviousDecl()->getAccess(); 9467 9468 NewFD->setAccess(Access); 9469 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9470 } 9471 9472 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9473 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9474 PrincipalDecl->setNonMemberOperator(); 9475 9476 // If we have a function template, check the template parameter 9477 // list. This will check and merge default template arguments. 9478 if (FunctionTemplate) { 9479 FunctionTemplateDecl *PrevTemplate = 9480 FunctionTemplate->getPreviousDecl(); 9481 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9482 PrevTemplate ? PrevTemplate->getTemplateParameters() 9483 : nullptr, 9484 D.getDeclSpec().isFriendSpecified() 9485 ? (D.isFunctionDefinition() 9486 ? TPC_FriendFunctionTemplateDefinition 9487 : TPC_FriendFunctionTemplate) 9488 : (D.getCXXScopeSpec().isSet() && 9489 DC && DC->isRecord() && 9490 DC->isDependentContext()) 9491 ? TPC_ClassTemplateMember 9492 : TPC_FunctionTemplate); 9493 } 9494 9495 if (NewFD->isInvalidDecl()) { 9496 // Ignore all the rest of this. 9497 } else if (!D.isRedeclaration()) { 9498 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9499 AddToScope }; 9500 // Fake up an access specifier if it's supposed to be a class member. 9501 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9502 NewFD->setAccess(AS_public); 9503 9504 // Qualified decls generally require a previous declaration. 9505 if (D.getCXXScopeSpec().isSet()) { 9506 // ...with the major exception of templated-scope or 9507 // dependent-scope friend declarations. 9508 9509 // TODO: we currently also suppress this check in dependent 9510 // contexts because (1) the parameter depth will be off when 9511 // matching friend templates and (2) we might actually be 9512 // selecting a friend based on a dependent factor. But there 9513 // are situations where these conditions don't apply and we 9514 // can actually do this check immediately. 9515 // 9516 // Unless the scope is dependent, it's always an error if qualified 9517 // redeclaration lookup found nothing at all. Diagnose that now; 9518 // nothing will diagnose that error later. 9519 if (isFriend && 9520 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9521 (!Previous.empty() && CurContext->isDependentContext()))) { 9522 // ignore these 9523 } else { 9524 // The user tried to provide an out-of-line definition for a 9525 // function that is a member of a class or namespace, but there 9526 // was no such member function declared (C++ [class.mfct]p2, 9527 // C++ [namespace.memdef]p2). For example: 9528 // 9529 // class X { 9530 // void f() const; 9531 // }; 9532 // 9533 // void X::f() { } // ill-formed 9534 // 9535 // Complain about this problem, and attempt to suggest close 9536 // matches (e.g., those that differ only in cv-qualifiers and 9537 // whether the parameter types are references). 9538 9539 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9540 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9541 AddToScope = ExtraArgs.AddToScope; 9542 return Result; 9543 } 9544 } 9545 9546 // Unqualified local friend declarations are required to resolve 9547 // to something. 9548 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9549 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9550 *this, Previous, NewFD, ExtraArgs, true, S)) { 9551 AddToScope = ExtraArgs.AddToScope; 9552 return Result; 9553 } 9554 } 9555 } else if (!D.isFunctionDefinition() && 9556 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9557 !isFriend && !isFunctionTemplateSpecialization && 9558 !isMemberSpecialization) { 9559 // An out-of-line member function declaration must also be a 9560 // definition (C++ [class.mfct]p2). 9561 // Note that this is not the case for explicit specializations of 9562 // function templates or member functions of class templates, per 9563 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9564 // extension for compatibility with old SWIG code which likes to 9565 // generate them. 9566 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9567 << D.getCXXScopeSpec().getRange(); 9568 } 9569 } 9570 9571 ProcessPragmaWeak(S, NewFD); 9572 checkAttributesAfterMerging(*this, *NewFD); 9573 9574 AddKnownFunctionAttributes(NewFD); 9575 9576 if (NewFD->hasAttr<OverloadableAttr>() && 9577 !NewFD->getType()->getAs<FunctionProtoType>()) { 9578 Diag(NewFD->getLocation(), 9579 diag::err_attribute_overloadable_no_prototype) 9580 << NewFD; 9581 9582 // Turn this into a variadic function with no parameters. 9583 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9584 FunctionProtoType::ExtProtoInfo EPI( 9585 Context.getDefaultCallingConvention(true, false)); 9586 EPI.Variadic = true; 9587 EPI.ExtInfo = FT->getExtInfo(); 9588 9589 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9590 NewFD->setType(R); 9591 } 9592 9593 // If there's a #pragma GCC visibility in scope, and this isn't a class 9594 // member, set the visibility of this function. 9595 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9596 AddPushedVisibilityAttribute(NewFD); 9597 9598 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9599 // marking the function. 9600 AddCFAuditedAttribute(NewFD); 9601 9602 // If this is a function definition, check if we have to apply optnone due to 9603 // a pragma. 9604 if(D.isFunctionDefinition()) 9605 AddRangeBasedOptnone(NewFD); 9606 9607 // If this is the first declaration of an extern C variable, update 9608 // the map of such variables. 9609 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9610 isIncompleteDeclExternC(*this, NewFD)) 9611 RegisterLocallyScopedExternCDecl(NewFD, S); 9612 9613 // Set this FunctionDecl's range up to the right paren. 9614 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9615 9616 if (D.isRedeclaration() && !Previous.empty()) { 9617 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9618 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9619 isMemberSpecialization || 9620 isFunctionTemplateSpecialization, 9621 D.isFunctionDefinition()); 9622 } 9623 9624 if (getLangOpts().CUDA) { 9625 IdentifierInfo *II = NewFD->getIdentifier(); 9626 if (II && II->isStr(getCudaConfigureFuncName()) && 9627 !NewFD->isInvalidDecl() && 9628 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9629 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9630 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9631 << getCudaConfigureFuncName(); 9632 Context.setcudaConfigureCallDecl(NewFD); 9633 } 9634 9635 // Variadic functions, other than a *declaration* of printf, are not allowed 9636 // in device-side CUDA code, unless someone passed 9637 // -fcuda-allow-variadic-functions. 9638 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9639 (NewFD->hasAttr<CUDADeviceAttr>() || 9640 NewFD->hasAttr<CUDAGlobalAttr>()) && 9641 !(II && II->isStr("printf") && NewFD->isExternC() && 9642 !D.isFunctionDefinition())) { 9643 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9644 } 9645 } 9646 9647 MarkUnusedFileScopedDecl(NewFD); 9648 9649 9650 9651 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9652 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9653 if ((getLangOpts().OpenCLVersion >= 120) 9654 && (SC == SC_Static)) { 9655 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9656 D.setInvalidType(); 9657 } 9658 9659 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9660 if (!NewFD->getReturnType()->isVoidType()) { 9661 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9662 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9663 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9664 : FixItHint()); 9665 D.setInvalidType(); 9666 } 9667 9668 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9669 for (auto Param : NewFD->parameters()) 9670 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9671 9672 if (getLangOpts().OpenCLCPlusPlus) { 9673 if (DC->isRecord()) { 9674 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9675 D.setInvalidType(); 9676 } 9677 if (FunctionTemplate) { 9678 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9679 D.setInvalidType(); 9680 } 9681 } 9682 } 9683 9684 if (getLangOpts().CPlusPlus) { 9685 if (FunctionTemplate) { 9686 if (NewFD->isInvalidDecl()) 9687 FunctionTemplate->setInvalidDecl(); 9688 return FunctionTemplate; 9689 } 9690 9691 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9692 CompleteMemberSpecialization(NewFD, Previous); 9693 } 9694 9695 for (const ParmVarDecl *Param : NewFD->parameters()) { 9696 QualType PT = Param->getType(); 9697 9698 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9699 // types. 9700 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9701 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9702 QualType ElemTy = PipeTy->getElementType(); 9703 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9704 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9705 D.setInvalidType(); 9706 } 9707 } 9708 } 9709 } 9710 9711 // Here we have an function template explicit specialization at class scope. 9712 // The actual specialization will be postponed to template instatiation 9713 // time via the ClassScopeFunctionSpecializationDecl node. 9714 if (isDependentClassScopeExplicitSpecialization) { 9715 ClassScopeFunctionSpecializationDecl *NewSpec = 9716 ClassScopeFunctionSpecializationDecl::Create( 9717 Context, CurContext, NewFD->getLocation(), 9718 cast<CXXMethodDecl>(NewFD), 9719 HasExplicitTemplateArgs, TemplateArgs); 9720 CurContext->addDecl(NewSpec); 9721 AddToScope = false; 9722 } 9723 9724 // Diagnose availability attributes. Availability cannot be used on functions 9725 // that are run during load/unload. 9726 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9727 if (NewFD->hasAttr<ConstructorAttr>()) { 9728 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9729 << 1; 9730 NewFD->dropAttr<AvailabilityAttr>(); 9731 } 9732 if (NewFD->hasAttr<DestructorAttr>()) { 9733 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9734 << 2; 9735 NewFD->dropAttr<AvailabilityAttr>(); 9736 } 9737 } 9738 9739 // Diagnose no_builtin attribute on function declaration that are not a 9740 // definition. 9741 // FIXME: We should really be doing this in 9742 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9743 // the FunctionDecl and at this point of the code 9744 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9745 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9746 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9747 switch (D.getFunctionDefinitionKind()) { 9748 case FDK_Defaulted: 9749 case FDK_Deleted: 9750 Diag(NBA->getLocation(), 9751 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9752 << NBA->getSpelling(); 9753 break; 9754 case FDK_Declaration: 9755 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9756 << NBA->getSpelling(); 9757 break; 9758 case FDK_Definition: 9759 break; 9760 } 9761 9762 return NewFD; 9763 } 9764 9765 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9766 /// when __declspec(code_seg) "is applied to a class, all member functions of 9767 /// the class and nested classes -- this includes compiler-generated special 9768 /// member functions -- are put in the specified segment." 9769 /// The actual behavior is a little more complicated. The Microsoft compiler 9770 /// won't check outer classes if there is an active value from #pragma code_seg. 9771 /// The CodeSeg is always applied from the direct parent but only from outer 9772 /// classes when the #pragma code_seg stack is empty. See: 9773 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9774 /// available since MS has removed the page. 9775 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9776 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9777 if (!Method) 9778 return nullptr; 9779 const CXXRecordDecl *Parent = Method->getParent(); 9780 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9781 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9782 NewAttr->setImplicit(true); 9783 return NewAttr; 9784 } 9785 9786 // The Microsoft compiler won't check outer classes for the CodeSeg 9787 // when the #pragma code_seg stack is active. 9788 if (S.CodeSegStack.CurrentValue) 9789 return nullptr; 9790 9791 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9792 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9793 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9794 NewAttr->setImplicit(true); 9795 return NewAttr; 9796 } 9797 } 9798 return nullptr; 9799 } 9800 9801 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9802 /// containing class. Otherwise it will return implicit SectionAttr if the 9803 /// function is a definition and there is an active value on CodeSegStack 9804 /// (from the current #pragma code-seg value). 9805 /// 9806 /// \param FD Function being declared. 9807 /// \param IsDefinition Whether it is a definition or just a declarartion. 9808 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9809 /// nullptr if no attribute should be added. 9810 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9811 bool IsDefinition) { 9812 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9813 return A; 9814 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9815 CodeSegStack.CurrentValue) 9816 return SectionAttr::CreateImplicit( 9817 getASTContext(), CodeSegStack.CurrentValue->getString(), 9818 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9819 SectionAttr::Declspec_allocate); 9820 return nullptr; 9821 } 9822 9823 /// Determines if we can perform a correct type check for \p D as a 9824 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9825 /// best-effort check. 9826 /// 9827 /// \param NewD The new declaration. 9828 /// \param OldD The old declaration. 9829 /// \param NewT The portion of the type of the new declaration to check. 9830 /// \param OldT The portion of the type of the old declaration to check. 9831 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9832 QualType NewT, QualType OldT) { 9833 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9834 return true; 9835 9836 // For dependently-typed local extern declarations and friends, we can't 9837 // perform a correct type check in general until instantiation: 9838 // 9839 // int f(); 9840 // template<typename T> void g() { T f(); } 9841 // 9842 // (valid if g() is only instantiated with T = int). 9843 if (NewT->isDependentType() && 9844 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9845 return false; 9846 9847 // Similarly, if the previous declaration was a dependent local extern 9848 // declaration, we don't really know its type yet. 9849 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9850 return false; 9851 9852 return true; 9853 } 9854 9855 /// Checks if the new declaration declared in dependent context must be 9856 /// put in the same redeclaration chain as the specified declaration. 9857 /// 9858 /// \param D Declaration that is checked. 9859 /// \param PrevDecl Previous declaration found with proper lookup method for the 9860 /// same declaration name. 9861 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9862 /// belongs to. 9863 /// 9864 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9865 if (!D->getLexicalDeclContext()->isDependentContext()) 9866 return true; 9867 9868 // Don't chain dependent friend function definitions until instantiation, to 9869 // permit cases like 9870 // 9871 // void func(); 9872 // template<typename T> class C1 { friend void func() {} }; 9873 // template<typename T> class C2 { friend void func() {} }; 9874 // 9875 // ... which is valid if only one of C1 and C2 is ever instantiated. 9876 // 9877 // FIXME: This need only apply to function definitions. For now, we proxy 9878 // this by checking for a file-scope function. We do not want this to apply 9879 // to friend declarations nominating member functions, because that gets in 9880 // the way of access checks. 9881 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9882 return false; 9883 9884 auto *VD = dyn_cast<ValueDecl>(D); 9885 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9886 return !VD || !PrevVD || 9887 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9888 PrevVD->getType()); 9889 } 9890 9891 /// Check the target attribute of the function for MultiVersion 9892 /// validity. 9893 /// 9894 /// Returns true if there was an error, false otherwise. 9895 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9896 const auto *TA = FD->getAttr<TargetAttr>(); 9897 assert(TA && "MultiVersion Candidate requires a target attribute"); 9898 ParsedTargetAttr ParseInfo = TA->parse(); 9899 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9900 enum ErrType { Feature = 0, Architecture = 1 }; 9901 9902 if (!ParseInfo.Architecture.empty() && 9903 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9904 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9905 << Architecture << ParseInfo.Architecture; 9906 return true; 9907 } 9908 9909 for (const auto &Feat : ParseInfo.Features) { 9910 auto BareFeat = StringRef{Feat}.substr(1); 9911 if (Feat[0] == '-') { 9912 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9913 << Feature << ("no-" + BareFeat).str(); 9914 return true; 9915 } 9916 9917 if (!TargetInfo.validateCpuSupports(BareFeat) || 9918 !TargetInfo.isValidFeatureName(BareFeat)) { 9919 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9920 << Feature << BareFeat; 9921 return true; 9922 } 9923 } 9924 return false; 9925 } 9926 9927 // Provide a white-list of attributes that are allowed to be combined with 9928 // multiversion functions. 9929 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9930 MultiVersionKind MVType) { 9931 switch (Kind) { 9932 default: 9933 return false; 9934 case attr::Used: 9935 return MVType == MultiVersionKind::Target; 9936 } 9937 } 9938 9939 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9940 MultiVersionKind MVType) { 9941 for (const Attr *A : FD->attrs()) { 9942 switch (A->getKind()) { 9943 case attr::CPUDispatch: 9944 case attr::CPUSpecific: 9945 if (MVType != MultiVersionKind::CPUDispatch && 9946 MVType != MultiVersionKind::CPUSpecific) 9947 return true; 9948 break; 9949 case attr::Target: 9950 if (MVType != MultiVersionKind::Target) 9951 return true; 9952 break; 9953 default: 9954 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 9955 return true; 9956 break; 9957 } 9958 } 9959 return false; 9960 } 9961 9962 bool Sema::areMultiversionVariantFunctionsCompatible( 9963 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9964 const PartialDiagnostic &NoProtoDiagID, 9965 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9966 const PartialDiagnosticAt &NoSupportDiagIDAt, 9967 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9968 bool ConstexprSupported, bool CLinkageMayDiffer) { 9969 enum DoesntSupport { 9970 FuncTemplates = 0, 9971 VirtFuncs = 1, 9972 DeducedReturn = 2, 9973 Constructors = 3, 9974 Destructors = 4, 9975 DeletedFuncs = 5, 9976 DefaultedFuncs = 6, 9977 ConstexprFuncs = 7, 9978 ConstevalFuncs = 8, 9979 }; 9980 enum Different { 9981 CallingConv = 0, 9982 ReturnType = 1, 9983 ConstexprSpec = 2, 9984 InlineSpec = 3, 9985 StorageClass = 4, 9986 Linkage = 5, 9987 }; 9988 9989 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 9990 !OldFD->getType()->getAs<FunctionProtoType>()) { 9991 Diag(OldFD->getLocation(), NoProtoDiagID); 9992 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 9993 return true; 9994 } 9995 9996 if (NoProtoDiagID.getDiagID() != 0 && 9997 !NewFD->getType()->getAs<FunctionProtoType>()) 9998 return Diag(NewFD->getLocation(), NoProtoDiagID); 9999 10000 if (!TemplatesSupported && 10001 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10002 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10003 << FuncTemplates; 10004 10005 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10006 if (NewCXXFD->isVirtual()) 10007 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10008 << VirtFuncs; 10009 10010 if (isa<CXXConstructorDecl>(NewCXXFD)) 10011 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10012 << Constructors; 10013 10014 if (isa<CXXDestructorDecl>(NewCXXFD)) 10015 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10016 << Destructors; 10017 } 10018 10019 if (NewFD->isDeleted()) 10020 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10021 << DeletedFuncs; 10022 10023 if (NewFD->isDefaulted()) 10024 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10025 << DefaultedFuncs; 10026 10027 if (!ConstexprSupported && NewFD->isConstexpr()) 10028 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10029 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10030 10031 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10032 const auto *NewType = cast<FunctionType>(NewQType); 10033 QualType NewReturnType = NewType->getReturnType(); 10034 10035 if (NewReturnType->isUndeducedType()) 10036 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10037 << DeducedReturn; 10038 10039 // Ensure the return type is identical. 10040 if (OldFD) { 10041 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10042 const auto *OldType = cast<FunctionType>(OldQType); 10043 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10044 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10045 10046 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10047 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10048 10049 QualType OldReturnType = OldType->getReturnType(); 10050 10051 if (OldReturnType != NewReturnType) 10052 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10053 10054 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10055 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10056 10057 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10058 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10059 10060 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10061 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10062 10063 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10064 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10065 10066 if (CheckEquivalentExceptionSpec( 10067 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10068 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10069 return true; 10070 } 10071 return false; 10072 } 10073 10074 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10075 const FunctionDecl *NewFD, 10076 bool CausesMV, 10077 MultiVersionKind MVType) { 10078 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10079 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10080 if (OldFD) 10081 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10082 return true; 10083 } 10084 10085 bool IsCPUSpecificCPUDispatchMVType = 10086 MVType == MultiVersionKind::CPUDispatch || 10087 MVType == MultiVersionKind::CPUSpecific; 10088 10089 // For now, disallow all other attributes. These should be opt-in, but 10090 // an analysis of all of them is a future FIXME. 10091 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10092 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10093 << IsCPUSpecificCPUDispatchMVType; 10094 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10095 return true; 10096 } 10097 10098 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10099 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10100 << IsCPUSpecificCPUDispatchMVType; 10101 10102 // Only allow transition to MultiVersion if it hasn't been used. 10103 if (OldFD && CausesMV && OldFD->isUsed(false)) 10104 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10105 10106 return S.areMultiversionVariantFunctionsCompatible( 10107 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10108 PartialDiagnosticAt(NewFD->getLocation(), 10109 S.PDiag(diag::note_multiversioning_caused_here)), 10110 PartialDiagnosticAt(NewFD->getLocation(), 10111 S.PDiag(diag::err_multiversion_doesnt_support) 10112 << IsCPUSpecificCPUDispatchMVType), 10113 PartialDiagnosticAt(NewFD->getLocation(), 10114 S.PDiag(diag::err_multiversion_diff)), 10115 /*TemplatesSupported=*/false, 10116 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10117 /*CLinkageMayDiffer=*/false); 10118 } 10119 10120 /// Check the validity of a multiversion function declaration that is the 10121 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10122 /// 10123 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10124 /// 10125 /// Returns true if there was an error, false otherwise. 10126 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10127 MultiVersionKind MVType, 10128 const TargetAttr *TA) { 10129 assert(MVType != MultiVersionKind::None && 10130 "Function lacks multiversion attribute"); 10131 10132 // Target only causes MV if it is default, otherwise this is a normal 10133 // function. 10134 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10135 return false; 10136 10137 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10138 FD->setInvalidDecl(); 10139 return true; 10140 } 10141 10142 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10143 FD->setInvalidDecl(); 10144 return true; 10145 } 10146 10147 FD->setIsMultiVersion(); 10148 return false; 10149 } 10150 10151 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10152 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10153 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10154 return true; 10155 } 10156 10157 return false; 10158 } 10159 10160 static bool CheckTargetCausesMultiVersioning( 10161 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10162 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10163 LookupResult &Previous) { 10164 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10165 ParsedTargetAttr NewParsed = NewTA->parse(); 10166 // Sort order doesn't matter, it just needs to be consistent. 10167 llvm::sort(NewParsed.Features); 10168 10169 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10170 // to change, this is a simple redeclaration. 10171 if (!NewTA->isDefaultVersion() && 10172 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10173 return false; 10174 10175 // Otherwise, this decl causes MultiVersioning. 10176 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10177 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10178 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10179 NewFD->setInvalidDecl(); 10180 return true; 10181 } 10182 10183 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10184 MultiVersionKind::Target)) { 10185 NewFD->setInvalidDecl(); 10186 return true; 10187 } 10188 10189 if (CheckMultiVersionValue(S, NewFD)) { 10190 NewFD->setInvalidDecl(); 10191 return true; 10192 } 10193 10194 // If this is 'default', permit the forward declaration. 10195 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10196 Redeclaration = true; 10197 OldDecl = OldFD; 10198 OldFD->setIsMultiVersion(); 10199 NewFD->setIsMultiVersion(); 10200 return false; 10201 } 10202 10203 if (CheckMultiVersionValue(S, OldFD)) { 10204 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10205 NewFD->setInvalidDecl(); 10206 return true; 10207 } 10208 10209 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10210 10211 if (OldParsed == NewParsed) { 10212 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10213 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10214 NewFD->setInvalidDecl(); 10215 return true; 10216 } 10217 10218 for (const auto *FD : OldFD->redecls()) { 10219 const auto *CurTA = FD->getAttr<TargetAttr>(); 10220 // We allow forward declarations before ANY multiversioning attributes, but 10221 // nothing after the fact. 10222 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10223 (!CurTA || CurTA->isInherited())) { 10224 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10225 << 0; 10226 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10227 NewFD->setInvalidDecl(); 10228 return true; 10229 } 10230 } 10231 10232 OldFD->setIsMultiVersion(); 10233 NewFD->setIsMultiVersion(); 10234 Redeclaration = false; 10235 MergeTypeWithPrevious = false; 10236 OldDecl = nullptr; 10237 Previous.clear(); 10238 return false; 10239 } 10240 10241 /// Check the validity of a new function declaration being added to an existing 10242 /// multiversioned declaration collection. 10243 static bool CheckMultiVersionAdditionalDecl( 10244 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10245 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10246 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10247 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10248 LookupResult &Previous) { 10249 10250 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10251 // Disallow mixing of multiversioning types. 10252 if ((OldMVType == MultiVersionKind::Target && 10253 NewMVType != MultiVersionKind::Target) || 10254 (NewMVType == MultiVersionKind::Target && 10255 OldMVType != MultiVersionKind::Target)) { 10256 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10257 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10258 NewFD->setInvalidDecl(); 10259 return true; 10260 } 10261 10262 ParsedTargetAttr NewParsed; 10263 if (NewTA) { 10264 NewParsed = NewTA->parse(); 10265 llvm::sort(NewParsed.Features); 10266 } 10267 10268 bool UseMemberUsingDeclRules = 10269 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10270 10271 // Next, check ALL non-overloads to see if this is a redeclaration of a 10272 // previous member of the MultiVersion set. 10273 for (NamedDecl *ND : Previous) { 10274 FunctionDecl *CurFD = ND->getAsFunction(); 10275 if (!CurFD) 10276 continue; 10277 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10278 continue; 10279 10280 if (NewMVType == MultiVersionKind::Target) { 10281 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10282 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10283 NewFD->setIsMultiVersion(); 10284 Redeclaration = true; 10285 OldDecl = ND; 10286 return false; 10287 } 10288 10289 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10290 if (CurParsed == NewParsed) { 10291 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10292 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10293 NewFD->setInvalidDecl(); 10294 return true; 10295 } 10296 } else { 10297 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10298 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10299 // Handle CPUDispatch/CPUSpecific versions. 10300 // Only 1 CPUDispatch function is allowed, this will make it go through 10301 // the redeclaration errors. 10302 if (NewMVType == MultiVersionKind::CPUDispatch && 10303 CurFD->hasAttr<CPUDispatchAttr>()) { 10304 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10305 std::equal( 10306 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10307 NewCPUDisp->cpus_begin(), 10308 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10309 return Cur->getName() == New->getName(); 10310 })) { 10311 NewFD->setIsMultiVersion(); 10312 Redeclaration = true; 10313 OldDecl = ND; 10314 return false; 10315 } 10316 10317 // If the declarations don't match, this is an error condition. 10318 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10319 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10320 NewFD->setInvalidDecl(); 10321 return true; 10322 } 10323 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10324 10325 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10326 std::equal( 10327 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10328 NewCPUSpec->cpus_begin(), 10329 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10330 return Cur->getName() == New->getName(); 10331 })) { 10332 NewFD->setIsMultiVersion(); 10333 Redeclaration = true; 10334 OldDecl = ND; 10335 return false; 10336 } 10337 10338 // Only 1 version of CPUSpecific is allowed for each CPU. 10339 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10340 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10341 if (CurII == NewII) { 10342 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10343 << NewII; 10344 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10345 NewFD->setInvalidDecl(); 10346 return true; 10347 } 10348 } 10349 } 10350 } 10351 // If the two decls aren't the same MVType, there is no possible error 10352 // condition. 10353 } 10354 } 10355 10356 // Else, this is simply a non-redecl case. Checking the 'value' is only 10357 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10358 // handled in the attribute adding step. 10359 if (NewMVType == MultiVersionKind::Target && 10360 CheckMultiVersionValue(S, NewFD)) { 10361 NewFD->setInvalidDecl(); 10362 return true; 10363 } 10364 10365 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10366 !OldFD->isMultiVersion(), NewMVType)) { 10367 NewFD->setInvalidDecl(); 10368 return true; 10369 } 10370 10371 // Permit forward declarations in the case where these two are compatible. 10372 if (!OldFD->isMultiVersion()) { 10373 OldFD->setIsMultiVersion(); 10374 NewFD->setIsMultiVersion(); 10375 Redeclaration = true; 10376 OldDecl = OldFD; 10377 return false; 10378 } 10379 10380 NewFD->setIsMultiVersion(); 10381 Redeclaration = false; 10382 MergeTypeWithPrevious = false; 10383 OldDecl = nullptr; 10384 Previous.clear(); 10385 return false; 10386 } 10387 10388 10389 /// Check the validity of a mulitversion function declaration. 10390 /// Also sets the multiversion'ness' of the function itself. 10391 /// 10392 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10393 /// 10394 /// Returns true if there was an error, false otherwise. 10395 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10396 bool &Redeclaration, NamedDecl *&OldDecl, 10397 bool &MergeTypeWithPrevious, 10398 LookupResult &Previous) { 10399 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10400 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10401 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10402 10403 // Mixing Multiversioning types is prohibited. 10404 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10405 (NewCPUDisp && NewCPUSpec)) { 10406 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10407 NewFD->setInvalidDecl(); 10408 return true; 10409 } 10410 10411 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10412 10413 // Main isn't allowed to become a multiversion function, however it IS 10414 // permitted to have 'main' be marked with the 'target' optimization hint. 10415 if (NewFD->isMain()) { 10416 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10417 MVType == MultiVersionKind::CPUDispatch || 10418 MVType == MultiVersionKind::CPUSpecific) { 10419 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10420 NewFD->setInvalidDecl(); 10421 return true; 10422 } 10423 return false; 10424 } 10425 10426 if (!OldDecl || !OldDecl->getAsFunction() || 10427 OldDecl->getDeclContext()->getRedeclContext() != 10428 NewFD->getDeclContext()->getRedeclContext()) { 10429 // If there's no previous declaration, AND this isn't attempting to cause 10430 // multiversioning, this isn't an error condition. 10431 if (MVType == MultiVersionKind::None) 10432 return false; 10433 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10434 } 10435 10436 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10437 10438 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10439 return false; 10440 10441 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10442 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10443 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10444 NewFD->setInvalidDecl(); 10445 return true; 10446 } 10447 10448 // Handle the target potentially causes multiversioning case. 10449 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10450 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10451 Redeclaration, OldDecl, 10452 MergeTypeWithPrevious, Previous); 10453 10454 // At this point, we have a multiversion function decl (in OldFD) AND an 10455 // appropriate attribute in the current function decl. Resolve that these are 10456 // still compatible with previous declarations. 10457 return CheckMultiVersionAdditionalDecl( 10458 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10459 OldDecl, MergeTypeWithPrevious, Previous); 10460 } 10461 10462 /// Perform semantic checking of a new function declaration. 10463 /// 10464 /// Performs semantic analysis of the new function declaration 10465 /// NewFD. This routine performs all semantic checking that does not 10466 /// require the actual declarator involved in the declaration, and is 10467 /// used both for the declaration of functions as they are parsed 10468 /// (called via ActOnDeclarator) and for the declaration of functions 10469 /// that have been instantiated via C++ template instantiation (called 10470 /// via InstantiateDecl). 10471 /// 10472 /// \param IsMemberSpecialization whether this new function declaration is 10473 /// a member specialization (that replaces any definition provided by the 10474 /// previous declaration). 10475 /// 10476 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10477 /// 10478 /// \returns true if the function declaration is a redeclaration. 10479 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10480 LookupResult &Previous, 10481 bool IsMemberSpecialization) { 10482 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10483 "Variably modified return types are not handled here"); 10484 10485 // Determine whether the type of this function should be merged with 10486 // a previous visible declaration. This never happens for functions in C++, 10487 // and always happens in C if the previous declaration was visible. 10488 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10489 !Previous.isShadowed(); 10490 10491 bool Redeclaration = false; 10492 NamedDecl *OldDecl = nullptr; 10493 bool MayNeedOverloadableChecks = false; 10494 10495 // Merge or overload the declaration with an existing declaration of 10496 // the same name, if appropriate. 10497 if (!Previous.empty()) { 10498 // Determine whether NewFD is an overload of PrevDecl or 10499 // a declaration that requires merging. If it's an overload, 10500 // there's no more work to do here; we'll just add the new 10501 // function to the scope. 10502 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10503 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10504 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10505 Redeclaration = true; 10506 OldDecl = Candidate; 10507 } 10508 } else { 10509 MayNeedOverloadableChecks = true; 10510 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10511 /*NewIsUsingDecl*/ false)) { 10512 case Ovl_Match: 10513 Redeclaration = true; 10514 break; 10515 10516 case Ovl_NonFunction: 10517 Redeclaration = true; 10518 break; 10519 10520 case Ovl_Overload: 10521 Redeclaration = false; 10522 break; 10523 } 10524 } 10525 } 10526 10527 // Check for a previous extern "C" declaration with this name. 10528 if (!Redeclaration && 10529 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10530 if (!Previous.empty()) { 10531 // This is an extern "C" declaration with the same name as a previous 10532 // declaration, and thus redeclares that entity... 10533 Redeclaration = true; 10534 OldDecl = Previous.getFoundDecl(); 10535 MergeTypeWithPrevious = false; 10536 10537 // ... except in the presence of __attribute__((overloadable)). 10538 if (OldDecl->hasAttr<OverloadableAttr>() || 10539 NewFD->hasAttr<OverloadableAttr>()) { 10540 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10541 MayNeedOverloadableChecks = true; 10542 Redeclaration = false; 10543 OldDecl = nullptr; 10544 } 10545 } 10546 } 10547 } 10548 10549 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10550 MergeTypeWithPrevious, Previous)) 10551 return Redeclaration; 10552 10553 // C++11 [dcl.constexpr]p8: 10554 // A constexpr specifier for a non-static member function that is not 10555 // a constructor declares that member function to be const. 10556 // 10557 // This needs to be delayed until we know whether this is an out-of-line 10558 // definition of a static member function. 10559 // 10560 // This rule is not present in C++1y, so we produce a backwards 10561 // compatibility warning whenever it happens in C++11. 10562 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10563 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10564 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10565 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10566 CXXMethodDecl *OldMD = nullptr; 10567 if (OldDecl) 10568 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10569 if (!OldMD || !OldMD->isStatic()) { 10570 const FunctionProtoType *FPT = 10571 MD->getType()->castAs<FunctionProtoType>(); 10572 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10573 EPI.TypeQuals.addConst(); 10574 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10575 FPT->getParamTypes(), EPI)); 10576 10577 // Warn that we did this, if we're not performing template instantiation. 10578 // In that case, we'll have warned already when the template was defined. 10579 if (!inTemplateInstantiation()) { 10580 SourceLocation AddConstLoc; 10581 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10582 .IgnoreParens().getAs<FunctionTypeLoc>()) 10583 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10584 10585 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10586 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10587 } 10588 } 10589 } 10590 10591 if (Redeclaration) { 10592 // NewFD and OldDecl represent declarations that need to be 10593 // merged. 10594 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10595 NewFD->setInvalidDecl(); 10596 return Redeclaration; 10597 } 10598 10599 Previous.clear(); 10600 Previous.addDecl(OldDecl); 10601 10602 if (FunctionTemplateDecl *OldTemplateDecl = 10603 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10604 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10605 FunctionTemplateDecl *NewTemplateDecl 10606 = NewFD->getDescribedFunctionTemplate(); 10607 assert(NewTemplateDecl && "Template/non-template mismatch"); 10608 10609 // The call to MergeFunctionDecl above may have created some state in 10610 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10611 // can add it as a redeclaration. 10612 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10613 10614 NewFD->setPreviousDeclaration(OldFD); 10615 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10616 if (NewFD->isCXXClassMember()) { 10617 NewFD->setAccess(OldTemplateDecl->getAccess()); 10618 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10619 } 10620 10621 // If this is an explicit specialization of a member that is a function 10622 // template, mark it as a member specialization. 10623 if (IsMemberSpecialization && 10624 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10625 NewTemplateDecl->setMemberSpecialization(); 10626 assert(OldTemplateDecl->isMemberSpecialization()); 10627 // Explicit specializations of a member template do not inherit deleted 10628 // status from the parent member template that they are specializing. 10629 if (OldFD->isDeleted()) { 10630 // FIXME: This assert will not hold in the presence of modules. 10631 assert(OldFD->getCanonicalDecl() == OldFD); 10632 // FIXME: We need an update record for this AST mutation. 10633 OldFD->setDeletedAsWritten(false); 10634 } 10635 } 10636 10637 } else { 10638 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10639 auto *OldFD = cast<FunctionDecl>(OldDecl); 10640 // This needs to happen first so that 'inline' propagates. 10641 NewFD->setPreviousDeclaration(OldFD); 10642 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10643 if (NewFD->isCXXClassMember()) 10644 NewFD->setAccess(OldFD->getAccess()); 10645 } 10646 } 10647 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10648 !NewFD->getAttr<OverloadableAttr>()) { 10649 assert((Previous.empty() || 10650 llvm::any_of(Previous, 10651 [](const NamedDecl *ND) { 10652 return ND->hasAttr<OverloadableAttr>(); 10653 })) && 10654 "Non-redecls shouldn't happen without overloadable present"); 10655 10656 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10657 const auto *FD = dyn_cast<FunctionDecl>(ND); 10658 return FD && !FD->hasAttr<OverloadableAttr>(); 10659 }); 10660 10661 if (OtherUnmarkedIter != Previous.end()) { 10662 Diag(NewFD->getLocation(), 10663 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10664 Diag((*OtherUnmarkedIter)->getLocation(), 10665 diag::note_attribute_overloadable_prev_overload) 10666 << false; 10667 10668 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10669 } 10670 } 10671 10672 // Semantic checking for this function declaration (in isolation). 10673 10674 if (getLangOpts().CPlusPlus) { 10675 // C++-specific checks. 10676 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10677 CheckConstructor(Constructor); 10678 } else if (CXXDestructorDecl *Destructor = 10679 dyn_cast<CXXDestructorDecl>(NewFD)) { 10680 CXXRecordDecl *Record = Destructor->getParent(); 10681 QualType ClassType = Context.getTypeDeclType(Record); 10682 10683 // FIXME: Shouldn't we be able to perform this check even when the class 10684 // type is dependent? Both gcc and edg can handle that. 10685 if (!ClassType->isDependentType()) { 10686 DeclarationName Name 10687 = Context.DeclarationNames.getCXXDestructorName( 10688 Context.getCanonicalType(ClassType)); 10689 if (NewFD->getDeclName() != Name) { 10690 Diag(NewFD->getLocation(), diag::err_destructor_name); 10691 NewFD->setInvalidDecl(); 10692 return Redeclaration; 10693 } 10694 } 10695 } else if (CXXConversionDecl *Conversion 10696 = dyn_cast<CXXConversionDecl>(NewFD)) { 10697 ActOnConversionDeclarator(Conversion); 10698 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10699 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10700 CheckDeductionGuideTemplate(TD); 10701 10702 // A deduction guide is not on the list of entities that can be 10703 // explicitly specialized. 10704 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10705 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10706 << /*explicit specialization*/ 1; 10707 } 10708 10709 // Find any virtual functions that this function overrides. 10710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10711 if (!Method->isFunctionTemplateSpecialization() && 10712 !Method->getDescribedFunctionTemplate() && 10713 Method->isCanonicalDecl()) { 10714 AddOverriddenMethods(Method->getParent(), Method); 10715 } 10716 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10717 // C++2a [class.virtual]p6 10718 // A virtual method shall not have a requires-clause. 10719 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10720 diag::err_constrained_virtual_method); 10721 10722 if (Method->isStatic()) 10723 checkThisInStaticMemberFunctionType(Method); 10724 } 10725 10726 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10727 if (NewFD->isOverloadedOperator() && 10728 CheckOverloadedOperatorDeclaration(NewFD)) { 10729 NewFD->setInvalidDecl(); 10730 return Redeclaration; 10731 } 10732 10733 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10734 if (NewFD->getLiteralIdentifier() && 10735 CheckLiteralOperatorDeclaration(NewFD)) { 10736 NewFD->setInvalidDecl(); 10737 return Redeclaration; 10738 } 10739 10740 // In C++, check default arguments now that we have merged decls. Unless 10741 // the lexical context is the class, because in this case this is done 10742 // during delayed parsing anyway. 10743 if (!CurContext->isRecord()) 10744 CheckCXXDefaultArguments(NewFD); 10745 10746 // If this function declares a builtin function, check the type of this 10747 // declaration against the expected type for the builtin. 10748 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10749 ASTContext::GetBuiltinTypeError Error; 10750 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10751 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10752 // If the type of the builtin differs only in its exception 10753 // specification, that's OK. 10754 // FIXME: If the types do differ in this way, it would be better to 10755 // retain the 'noexcept' form of the type. 10756 if (!T.isNull() && 10757 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10758 NewFD->getType())) 10759 // The type of this function differs from the type of the builtin, 10760 // so forget about the builtin entirely. 10761 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10762 } 10763 10764 // If this function is declared as being extern "C", then check to see if 10765 // the function returns a UDT (class, struct, or union type) that is not C 10766 // compatible, and if it does, warn the user. 10767 // But, issue any diagnostic on the first declaration only. 10768 if (Previous.empty() && NewFD->isExternC()) { 10769 QualType R = NewFD->getReturnType(); 10770 if (R->isIncompleteType() && !R->isVoidType()) 10771 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10772 << NewFD << R; 10773 else if (!R.isPODType(Context) && !R->isVoidType() && 10774 !R->isObjCObjectPointerType()) 10775 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10776 } 10777 10778 // C++1z [dcl.fct]p6: 10779 // [...] whether the function has a non-throwing exception-specification 10780 // [is] part of the function type 10781 // 10782 // This results in an ABI break between C++14 and C++17 for functions whose 10783 // declared type includes an exception-specification in a parameter or 10784 // return type. (Exception specifications on the function itself are OK in 10785 // most cases, and exception specifications are not permitted in most other 10786 // contexts where they could make it into a mangling.) 10787 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10788 auto HasNoexcept = [&](QualType T) -> bool { 10789 // Strip off declarator chunks that could be between us and a function 10790 // type. We don't need to look far, exception specifications are very 10791 // restricted prior to C++17. 10792 if (auto *RT = T->getAs<ReferenceType>()) 10793 T = RT->getPointeeType(); 10794 else if (T->isAnyPointerType()) 10795 T = T->getPointeeType(); 10796 else if (auto *MPT = T->getAs<MemberPointerType>()) 10797 T = MPT->getPointeeType(); 10798 if (auto *FPT = T->getAs<FunctionProtoType>()) 10799 if (FPT->isNothrow()) 10800 return true; 10801 return false; 10802 }; 10803 10804 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10805 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10806 for (QualType T : FPT->param_types()) 10807 AnyNoexcept |= HasNoexcept(T); 10808 if (AnyNoexcept) 10809 Diag(NewFD->getLocation(), 10810 diag::warn_cxx17_compat_exception_spec_in_signature) 10811 << NewFD; 10812 } 10813 10814 if (!Redeclaration && LangOpts.CUDA) 10815 checkCUDATargetOverload(NewFD, Previous); 10816 } 10817 return Redeclaration; 10818 } 10819 10820 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10821 // C++11 [basic.start.main]p3: 10822 // A program that [...] declares main to be inline, static or 10823 // constexpr is ill-formed. 10824 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10825 // appear in a declaration of main. 10826 // static main is not an error under C99, but we should warn about it. 10827 // We accept _Noreturn main as an extension. 10828 if (FD->getStorageClass() == SC_Static) 10829 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10830 ? diag::err_static_main : diag::warn_static_main) 10831 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10832 if (FD->isInlineSpecified()) 10833 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10834 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10835 if (DS.isNoreturnSpecified()) { 10836 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10837 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10838 Diag(NoreturnLoc, diag::ext_noreturn_main); 10839 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10840 << FixItHint::CreateRemoval(NoreturnRange); 10841 } 10842 if (FD->isConstexpr()) { 10843 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10844 << FD->isConsteval() 10845 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10846 FD->setConstexprKind(CSK_unspecified); 10847 } 10848 10849 if (getLangOpts().OpenCL) { 10850 Diag(FD->getLocation(), diag::err_opencl_no_main) 10851 << FD->hasAttr<OpenCLKernelAttr>(); 10852 FD->setInvalidDecl(); 10853 return; 10854 } 10855 10856 QualType T = FD->getType(); 10857 assert(T->isFunctionType() && "function decl is not of function type"); 10858 const FunctionType* FT = T->castAs<FunctionType>(); 10859 10860 // Set default calling convention for main() 10861 if (FT->getCallConv() != CC_C) { 10862 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10863 FD->setType(QualType(FT, 0)); 10864 T = Context.getCanonicalType(FD->getType()); 10865 } 10866 10867 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10868 // In C with GNU extensions we allow main() to have non-integer return 10869 // type, but we should warn about the extension, and we disable the 10870 // implicit-return-zero rule. 10871 10872 // GCC in C mode accepts qualified 'int'. 10873 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10874 FD->setHasImplicitReturnZero(true); 10875 else { 10876 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10877 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10878 if (RTRange.isValid()) 10879 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10880 << FixItHint::CreateReplacement(RTRange, "int"); 10881 } 10882 } else { 10883 // In C and C++, main magically returns 0 if you fall off the end; 10884 // set the flag which tells us that. 10885 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10886 10887 // All the standards say that main() should return 'int'. 10888 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10889 FD->setHasImplicitReturnZero(true); 10890 else { 10891 // Otherwise, this is just a flat-out error. 10892 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10893 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10894 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10895 : FixItHint()); 10896 FD->setInvalidDecl(true); 10897 } 10898 } 10899 10900 // Treat protoless main() as nullary. 10901 if (isa<FunctionNoProtoType>(FT)) return; 10902 10903 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10904 unsigned nparams = FTP->getNumParams(); 10905 assert(FD->getNumParams() == nparams); 10906 10907 bool HasExtraParameters = (nparams > 3); 10908 10909 if (FTP->isVariadic()) { 10910 Diag(FD->getLocation(), diag::ext_variadic_main); 10911 // FIXME: if we had information about the location of the ellipsis, we 10912 // could add a FixIt hint to remove it as a parameter. 10913 } 10914 10915 // Darwin passes an undocumented fourth argument of type char**. If 10916 // other platforms start sprouting these, the logic below will start 10917 // getting shifty. 10918 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10919 HasExtraParameters = false; 10920 10921 if (HasExtraParameters) { 10922 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10923 FD->setInvalidDecl(true); 10924 nparams = 3; 10925 } 10926 10927 // FIXME: a lot of the following diagnostics would be improved 10928 // if we had some location information about types. 10929 10930 QualType CharPP = 10931 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10932 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10933 10934 for (unsigned i = 0; i < nparams; ++i) { 10935 QualType AT = FTP->getParamType(i); 10936 10937 bool mismatch = true; 10938 10939 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10940 mismatch = false; 10941 else if (Expected[i] == CharPP) { 10942 // As an extension, the following forms are okay: 10943 // char const ** 10944 // char const * const * 10945 // char * const * 10946 10947 QualifierCollector qs; 10948 const PointerType* PT; 10949 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10950 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10951 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10952 Context.CharTy)) { 10953 qs.removeConst(); 10954 mismatch = !qs.empty(); 10955 } 10956 } 10957 10958 if (mismatch) { 10959 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10960 // TODO: suggest replacing given type with expected type 10961 FD->setInvalidDecl(true); 10962 } 10963 } 10964 10965 if (nparams == 1 && !FD->isInvalidDecl()) { 10966 Diag(FD->getLocation(), diag::warn_main_one_arg); 10967 } 10968 10969 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10970 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10971 FD->setInvalidDecl(); 10972 } 10973 } 10974 10975 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10976 QualType T = FD->getType(); 10977 assert(T->isFunctionType() && "function decl is not of function type"); 10978 const FunctionType *FT = T->castAs<FunctionType>(); 10979 10980 // Set an implicit return of 'zero' if the function can return some integral, 10981 // enumeration, pointer or nullptr type. 10982 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10983 FT->getReturnType()->isAnyPointerType() || 10984 FT->getReturnType()->isNullPtrType()) 10985 // DllMain is exempt because a return value of zero means it failed. 10986 if (FD->getName() != "DllMain") 10987 FD->setHasImplicitReturnZero(true); 10988 10989 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10990 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10991 FD->setInvalidDecl(); 10992 } 10993 } 10994 10995 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10996 // FIXME: Need strict checking. In C89, we need to check for 10997 // any assignment, increment, decrement, function-calls, or 10998 // commas outside of a sizeof. In C99, it's the same list, 10999 // except that the aforementioned are allowed in unevaluated 11000 // expressions. Everything else falls under the 11001 // "may accept other forms of constant expressions" exception. 11002 // (We never end up here for C++, so the constant expression 11003 // rules there don't matter.) 11004 const Expr *Culprit; 11005 if (Init->isConstantInitializer(Context, false, &Culprit)) 11006 return false; 11007 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11008 << Culprit->getSourceRange(); 11009 return true; 11010 } 11011 11012 namespace { 11013 // Visits an initialization expression to see if OrigDecl is evaluated in 11014 // its own initialization and throws a warning if it does. 11015 class SelfReferenceChecker 11016 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11017 Sema &S; 11018 Decl *OrigDecl; 11019 bool isRecordType; 11020 bool isPODType; 11021 bool isReferenceType; 11022 11023 bool isInitList; 11024 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11025 11026 public: 11027 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11028 11029 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11030 S(S), OrigDecl(OrigDecl) { 11031 isPODType = false; 11032 isRecordType = false; 11033 isReferenceType = false; 11034 isInitList = false; 11035 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11036 isPODType = VD->getType().isPODType(S.Context); 11037 isRecordType = VD->getType()->isRecordType(); 11038 isReferenceType = VD->getType()->isReferenceType(); 11039 } 11040 } 11041 11042 // For most expressions, just call the visitor. For initializer lists, 11043 // track the index of the field being initialized since fields are 11044 // initialized in order allowing use of previously initialized fields. 11045 void CheckExpr(Expr *E) { 11046 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11047 if (!InitList) { 11048 Visit(E); 11049 return; 11050 } 11051 11052 // Track and increment the index here. 11053 isInitList = true; 11054 InitFieldIndex.push_back(0); 11055 for (auto Child : InitList->children()) { 11056 CheckExpr(cast<Expr>(Child)); 11057 ++InitFieldIndex.back(); 11058 } 11059 InitFieldIndex.pop_back(); 11060 } 11061 11062 // Returns true if MemberExpr is checked and no further checking is needed. 11063 // Returns false if additional checking is required. 11064 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11065 llvm::SmallVector<FieldDecl*, 4> Fields; 11066 Expr *Base = E; 11067 bool ReferenceField = false; 11068 11069 // Get the field members used. 11070 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11071 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11072 if (!FD) 11073 return false; 11074 Fields.push_back(FD); 11075 if (FD->getType()->isReferenceType()) 11076 ReferenceField = true; 11077 Base = ME->getBase()->IgnoreParenImpCasts(); 11078 } 11079 11080 // Keep checking only if the base Decl is the same. 11081 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11082 if (!DRE || DRE->getDecl() != OrigDecl) 11083 return false; 11084 11085 // A reference field can be bound to an unininitialized field. 11086 if (CheckReference && !ReferenceField) 11087 return true; 11088 11089 // Convert FieldDecls to their index number. 11090 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11091 for (const FieldDecl *I : llvm::reverse(Fields)) 11092 UsedFieldIndex.push_back(I->getFieldIndex()); 11093 11094 // See if a warning is needed by checking the first difference in index 11095 // numbers. If field being used has index less than the field being 11096 // initialized, then the use is safe. 11097 for (auto UsedIter = UsedFieldIndex.begin(), 11098 UsedEnd = UsedFieldIndex.end(), 11099 OrigIter = InitFieldIndex.begin(), 11100 OrigEnd = InitFieldIndex.end(); 11101 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11102 if (*UsedIter < *OrigIter) 11103 return true; 11104 if (*UsedIter > *OrigIter) 11105 break; 11106 } 11107 11108 // TODO: Add a different warning which will print the field names. 11109 HandleDeclRefExpr(DRE); 11110 return true; 11111 } 11112 11113 // For most expressions, the cast is directly above the DeclRefExpr. 11114 // For conditional operators, the cast can be outside the conditional 11115 // operator if both expressions are DeclRefExpr's. 11116 void HandleValue(Expr *E) { 11117 E = E->IgnoreParens(); 11118 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11119 HandleDeclRefExpr(DRE); 11120 return; 11121 } 11122 11123 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11124 Visit(CO->getCond()); 11125 HandleValue(CO->getTrueExpr()); 11126 HandleValue(CO->getFalseExpr()); 11127 return; 11128 } 11129 11130 if (BinaryConditionalOperator *BCO = 11131 dyn_cast<BinaryConditionalOperator>(E)) { 11132 Visit(BCO->getCond()); 11133 HandleValue(BCO->getFalseExpr()); 11134 return; 11135 } 11136 11137 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11138 HandleValue(OVE->getSourceExpr()); 11139 return; 11140 } 11141 11142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11143 if (BO->getOpcode() == BO_Comma) { 11144 Visit(BO->getLHS()); 11145 HandleValue(BO->getRHS()); 11146 return; 11147 } 11148 } 11149 11150 if (isa<MemberExpr>(E)) { 11151 if (isInitList) { 11152 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11153 false /*CheckReference*/)) 11154 return; 11155 } 11156 11157 Expr *Base = E->IgnoreParenImpCasts(); 11158 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11159 // Check for static member variables and don't warn on them. 11160 if (!isa<FieldDecl>(ME->getMemberDecl())) 11161 return; 11162 Base = ME->getBase()->IgnoreParenImpCasts(); 11163 } 11164 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11165 HandleDeclRefExpr(DRE); 11166 return; 11167 } 11168 11169 Visit(E); 11170 } 11171 11172 // Reference types not handled in HandleValue are handled here since all 11173 // uses of references are bad, not just r-value uses. 11174 void VisitDeclRefExpr(DeclRefExpr *E) { 11175 if (isReferenceType) 11176 HandleDeclRefExpr(E); 11177 } 11178 11179 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11180 if (E->getCastKind() == CK_LValueToRValue) { 11181 HandleValue(E->getSubExpr()); 11182 return; 11183 } 11184 11185 Inherited::VisitImplicitCastExpr(E); 11186 } 11187 11188 void VisitMemberExpr(MemberExpr *E) { 11189 if (isInitList) { 11190 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11191 return; 11192 } 11193 11194 // Don't warn on arrays since they can be treated as pointers. 11195 if (E->getType()->canDecayToPointerType()) return; 11196 11197 // Warn when a non-static method call is followed by non-static member 11198 // field accesses, which is followed by a DeclRefExpr. 11199 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11200 bool Warn = (MD && !MD->isStatic()); 11201 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11202 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11203 if (!isa<FieldDecl>(ME->getMemberDecl())) 11204 Warn = false; 11205 Base = ME->getBase()->IgnoreParenImpCasts(); 11206 } 11207 11208 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11209 if (Warn) 11210 HandleDeclRefExpr(DRE); 11211 return; 11212 } 11213 11214 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11215 // Visit that expression. 11216 Visit(Base); 11217 } 11218 11219 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11220 Expr *Callee = E->getCallee(); 11221 11222 if (isa<UnresolvedLookupExpr>(Callee)) 11223 return Inherited::VisitCXXOperatorCallExpr(E); 11224 11225 Visit(Callee); 11226 for (auto Arg: E->arguments()) 11227 HandleValue(Arg->IgnoreParenImpCasts()); 11228 } 11229 11230 void VisitUnaryOperator(UnaryOperator *E) { 11231 // For POD record types, addresses of its own members are well-defined. 11232 if (E->getOpcode() == UO_AddrOf && isRecordType && 11233 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11234 if (!isPODType) 11235 HandleValue(E->getSubExpr()); 11236 return; 11237 } 11238 11239 if (E->isIncrementDecrementOp()) { 11240 HandleValue(E->getSubExpr()); 11241 return; 11242 } 11243 11244 Inherited::VisitUnaryOperator(E); 11245 } 11246 11247 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11248 11249 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11250 if (E->getConstructor()->isCopyConstructor()) { 11251 Expr *ArgExpr = E->getArg(0); 11252 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11253 if (ILE->getNumInits() == 1) 11254 ArgExpr = ILE->getInit(0); 11255 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11256 if (ICE->getCastKind() == CK_NoOp) 11257 ArgExpr = ICE->getSubExpr(); 11258 HandleValue(ArgExpr); 11259 return; 11260 } 11261 Inherited::VisitCXXConstructExpr(E); 11262 } 11263 11264 void VisitCallExpr(CallExpr *E) { 11265 // Treat std::move as a use. 11266 if (E->isCallToStdMove()) { 11267 HandleValue(E->getArg(0)); 11268 return; 11269 } 11270 11271 Inherited::VisitCallExpr(E); 11272 } 11273 11274 void VisitBinaryOperator(BinaryOperator *E) { 11275 if (E->isCompoundAssignmentOp()) { 11276 HandleValue(E->getLHS()); 11277 Visit(E->getRHS()); 11278 return; 11279 } 11280 11281 Inherited::VisitBinaryOperator(E); 11282 } 11283 11284 // A custom visitor for BinaryConditionalOperator is needed because the 11285 // regular visitor would check the condition and true expression separately 11286 // but both point to the same place giving duplicate diagnostics. 11287 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11288 Visit(E->getCond()); 11289 Visit(E->getFalseExpr()); 11290 } 11291 11292 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11293 Decl* ReferenceDecl = DRE->getDecl(); 11294 if (OrigDecl != ReferenceDecl) return; 11295 unsigned diag; 11296 if (isReferenceType) { 11297 diag = diag::warn_uninit_self_reference_in_reference_init; 11298 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11299 diag = diag::warn_static_self_reference_in_init; 11300 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11301 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11302 DRE->getDecl()->getType()->isRecordType()) { 11303 diag = diag::warn_uninit_self_reference_in_init; 11304 } else { 11305 // Local variables will be handled by the CFG analysis. 11306 return; 11307 } 11308 11309 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11310 S.PDiag(diag) 11311 << DRE->getDecl() << OrigDecl->getLocation() 11312 << DRE->getSourceRange()); 11313 } 11314 }; 11315 11316 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11317 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11318 bool DirectInit) { 11319 // Parameters arguments are occassionially constructed with itself, 11320 // for instance, in recursive functions. Skip them. 11321 if (isa<ParmVarDecl>(OrigDecl)) 11322 return; 11323 11324 E = E->IgnoreParens(); 11325 11326 // Skip checking T a = a where T is not a record or reference type. 11327 // Doing so is a way to silence uninitialized warnings. 11328 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11329 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11330 if (ICE->getCastKind() == CK_LValueToRValue) 11331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11332 if (DRE->getDecl() == OrigDecl) 11333 return; 11334 11335 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11336 } 11337 } // end anonymous namespace 11338 11339 namespace { 11340 // Simple wrapper to add the name of a variable or (if no variable is 11341 // available) a DeclarationName into a diagnostic. 11342 struct VarDeclOrName { 11343 VarDecl *VDecl; 11344 DeclarationName Name; 11345 11346 friend const Sema::SemaDiagnosticBuilder & 11347 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11348 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11349 } 11350 }; 11351 } // end anonymous namespace 11352 11353 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11354 DeclarationName Name, QualType Type, 11355 TypeSourceInfo *TSI, 11356 SourceRange Range, bool DirectInit, 11357 Expr *Init) { 11358 bool IsInitCapture = !VDecl; 11359 assert((!VDecl || !VDecl->isInitCapture()) && 11360 "init captures are expected to be deduced prior to initialization"); 11361 11362 VarDeclOrName VN{VDecl, Name}; 11363 11364 DeducedType *Deduced = Type->getContainedDeducedType(); 11365 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11366 11367 // C++11 [dcl.spec.auto]p3 11368 if (!Init) { 11369 assert(VDecl && "no init for init capture deduction?"); 11370 11371 // Except for class argument deduction, and then for an initializing 11372 // declaration only, i.e. no static at class scope or extern. 11373 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11374 VDecl->hasExternalStorage() || 11375 VDecl->isStaticDataMember()) { 11376 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11377 << VDecl->getDeclName() << Type; 11378 return QualType(); 11379 } 11380 } 11381 11382 ArrayRef<Expr*> DeduceInits; 11383 if (Init) 11384 DeduceInits = Init; 11385 11386 if (DirectInit) { 11387 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11388 DeduceInits = PL->exprs(); 11389 } 11390 11391 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11392 assert(VDecl && "non-auto type for init capture deduction?"); 11393 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11394 InitializationKind Kind = InitializationKind::CreateForInit( 11395 VDecl->getLocation(), DirectInit, Init); 11396 // FIXME: Initialization should not be taking a mutable list of inits. 11397 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11398 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11399 InitsCopy); 11400 } 11401 11402 if (DirectInit) { 11403 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11404 DeduceInits = IL->inits(); 11405 } 11406 11407 // Deduction only works if we have exactly one source expression. 11408 if (DeduceInits.empty()) { 11409 // It isn't possible to write this directly, but it is possible to 11410 // end up in this situation with "auto x(some_pack...);" 11411 Diag(Init->getBeginLoc(), IsInitCapture 11412 ? diag::err_init_capture_no_expression 11413 : diag::err_auto_var_init_no_expression) 11414 << VN << Type << Range; 11415 return QualType(); 11416 } 11417 11418 if (DeduceInits.size() > 1) { 11419 Diag(DeduceInits[1]->getBeginLoc(), 11420 IsInitCapture ? diag::err_init_capture_multiple_expressions 11421 : diag::err_auto_var_init_multiple_expressions) 11422 << VN << Type << Range; 11423 return QualType(); 11424 } 11425 11426 Expr *DeduceInit = DeduceInits[0]; 11427 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11428 Diag(Init->getBeginLoc(), IsInitCapture 11429 ? diag::err_init_capture_paren_braces 11430 : diag::err_auto_var_init_paren_braces) 11431 << isa<InitListExpr>(Init) << VN << Type << Range; 11432 return QualType(); 11433 } 11434 11435 // Expressions default to 'id' when we're in a debugger. 11436 bool DefaultedAnyToId = false; 11437 if (getLangOpts().DebuggerCastResultToId && 11438 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11439 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11440 if (Result.isInvalid()) { 11441 return QualType(); 11442 } 11443 Init = Result.get(); 11444 DefaultedAnyToId = true; 11445 } 11446 11447 // C++ [dcl.decomp]p1: 11448 // If the assignment-expression [...] has array type A and no ref-qualifier 11449 // is present, e has type cv A 11450 if (VDecl && isa<DecompositionDecl>(VDecl) && 11451 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11452 DeduceInit->getType()->isConstantArrayType()) 11453 return Context.getQualifiedType(DeduceInit->getType(), 11454 Type.getQualifiers()); 11455 11456 QualType DeducedType; 11457 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11458 if (!IsInitCapture) 11459 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11460 else if (isa<InitListExpr>(Init)) 11461 Diag(Range.getBegin(), 11462 diag::err_init_capture_deduction_failure_from_init_list) 11463 << VN 11464 << (DeduceInit->getType().isNull() ? TSI->getType() 11465 : DeduceInit->getType()) 11466 << DeduceInit->getSourceRange(); 11467 else 11468 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11469 << VN << TSI->getType() 11470 << (DeduceInit->getType().isNull() ? TSI->getType() 11471 : DeduceInit->getType()) 11472 << DeduceInit->getSourceRange(); 11473 } 11474 11475 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11476 // 'id' instead of a specific object type prevents most of our usual 11477 // checks. 11478 // We only want to warn outside of template instantiations, though: 11479 // inside a template, the 'id' could have come from a parameter. 11480 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11481 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11482 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11483 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11484 } 11485 11486 return DeducedType; 11487 } 11488 11489 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11490 Expr *Init) { 11491 QualType DeducedType = deduceVarTypeFromInitializer( 11492 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11493 VDecl->getSourceRange(), DirectInit, Init); 11494 if (DeducedType.isNull()) { 11495 VDecl->setInvalidDecl(); 11496 return true; 11497 } 11498 11499 VDecl->setType(DeducedType); 11500 assert(VDecl->isLinkageValid()); 11501 11502 // In ARC, infer lifetime. 11503 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11504 VDecl->setInvalidDecl(); 11505 11506 if (getLangOpts().OpenCL) 11507 deduceOpenCLAddressSpace(VDecl); 11508 11509 // If this is a redeclaration, check that the type we just deduced matches 11510 // the previously declared type. 11511 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11512 // We never need to merge the type, because we cannot form an incomplete 11513 // array of auto, nor deduce such a type. 11514 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11515 } 11516 11517 // Check the deduced type is valid for a variable declaration. 11518 CheckVariableDeclarationType(VDecl); 11519 return VDecl->isInvalidDecl(); 11520 } 11521 11522 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11523 SourceLocation Loc) { 11524 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11525 Init = CE->getSubExpr(); 11526 11527 QualType InitType = Init->getType(); 11528 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11529 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11530 "shouldn't be called if type doesn't have a non-trivial C struct"); 11531 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11532 for (auto I : ILE->inits()) { 11533 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11534 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11535 continue; 11536 SourceLocation SL = I->getExprLoc(); 11537 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11538 } 11539 return; 11540 } 11541 11542 if (isa<ImplicitValueInitExpr>(Init)) { 11543 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11544 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11545 NTCUK_Init); 11546 } else { 11547 // Assume all other explicit initializers involving copying some existing 11548 // object. 11549 // TODO: ignore any explicit initializers where we can guarantee 11550 // copy-elision. 11551 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11552 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11553 } 11554 } 11555 11556 namespace { 11557 11558 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11559 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11560 // in the source code or implicitly by the compiler if it is in a union 11561 // defined in a system header and has non-trivial ObjC ownership 11562 // qualifications. We don't want those fields to participate in determining 11563 // whether the containing union is non-trivial. 11564 return FD->hasAttr<UnavailableAttr>(); 11565 } 11566 11567 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11568 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11569 void> { 11570 using Super = 11571 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11572 void>; 11573 11574 DiagNonTrivalCUnionDefaultInitializeVisitor( 11575 QualType OrigTy, SourceLocation OrigLoc, 11576 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11577 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11578 11579 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11580 const FieldDecl *FD, bool InNonTrivialUnion) { 11581 if (const auto *AT = S.Context.getAsArrayType(QT)) 11582 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11583 InNonTrivialUnion); 11584 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11585 } 11586 11587 void visitARCStrong(QualType QT, const FieldDecl *FD, 11588 bool InNonTrivialUnion) { 11589 if (InNonTrivialUnion) 11590 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11591 << 1 << 0 << QT << FD->getName(); 11592 } 11593 11594 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11595 if (InNonTrivialUnion) 11596 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11597 << 1 << 0 << QT << FD->getName(); 11598 } 11599 11600 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11601 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11602 if (RD->isUnion()) { 11603 if (OrigLoc.isValid()) { 11604 bool IsUnion = false; 11605 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11606 IsUnion = OrigRD->isUnion(); 11607 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11608 << 0 << OrigTy << IsUnion << UseContext; 11609 // Reset OrigLoc so that this diagnostic is emitted only once. 11610 OrigLoc = SourceLocation(); 11611 } 11612 InNonTrivialUnion = true; 11613 } 11614 11615 if (InNonTrivialUnion) 11616 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11617 << 0 << 0 << QT.getUnqualifiedType() << ""; 11618 11619 for (const FieldDecl *FD : RD->fields()) 11620 if (!shouldIgnoreForRecordTriviality(FD)) 11621 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11622 } 11623 11624 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11625 11626 // The non-trivial C union type or the struct/union type that contains a 11627 // non-trivial C union. 11628 QualType OrigTy; 11629 SourceLocation OrigLoc; 11630 Sema::NonTrivialCUnionContext UseContext; 11631 Sema &S; 11632 }; 11633 11634 struct DiagNonTrivalCUnionDestructedTypeVisitor 11635 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11636 using Super = 11637 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11638 11639 DiagNonTrivalCUnionDestructedTypeVisitor( 11640 QualType OrigTy, SourceLocation OrigLoc, 11641 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11642 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11643 11644 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11645 const FieldDecl *FD, bool InNonTrivialUnion) { 11646 if (const auto *AT = S.Context.getAsArrayType(QT)) 11647 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11648 InNonTrivialUnion); 11649 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11650 } 11651 11652 void visitARCStrong(QualType QT, const FieldDecl *FD, 11653 bool InNonTrivialUnion) { 11654 if (InNonTrivialUnion) 11655 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11656 << 1 << 1 << QT << FD->getName(); 11657 } 11658 11659 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11660 if (InNonTrivialUnion) 11661 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11662 << 1 << 1 << QT << FD->getName(); 11663 } 11664 11665 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11666 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11667 if (RD->isUnion()) { 11668 if (OrigLoc.isValid()) { 11669 bool IsUnion = false; 11670 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11671 IsUnion = OrigRD->isUnion(); 11672 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11673 << 1 << OrigTy << IsUnion << UseContext; 11674 // Reset OrigLoc so that this diagnostic is emitted only once. 11675 OrigLoc = SourceLocation(); 11676 } 11677 InNonTrivialUnion = true; 11678 } 11679 11680 if (InNonTrivialUnion) 11681 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11682 << 0 << 1 << QT.getUnqualifiedType() << ""; 11683 11684 for (const FieldDecl *FD : RD->fields()) 11685 if (!shouldIgnoreForRecordTriviality(FD)) 11686 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11687 } 11688 11689 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11690 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11691 bool InNonTrivialUnion) {} 11692 11693 // The non-trivial C union type or the struct/union type that contains a 11694 // non-trivial C union. 11695 QualType OrigTy; 11696 SourceLocation OrigLoc; 11697 Sema::NonTrivialCUnionContext UseContext; 11698 Sema &S; 11699 }; 11700 11701 struct DiagNonTrivalCUnionCopyVisitor 11702 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11703 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11704 11705 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11706 Sema::NonTrivialCUnionContext UseContext, 11707 Sema &S) 11708 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11709 11710 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11711 const FieldDecl *FD, bool InNonTrivialUnion) { 11712 if (const auto *AT = S.Context.getAsArrayType(QT)) 11713 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11714 InNonTrivialUnion); 11715 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11716 } 11717 11718 void visitARCStrong(QualType QT, const FieldDecl *FD, 11719 bool InNonTrivialUnion) { 11720 if (InNonTrivialUnion) 11721 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11722 << 1 << 2 << QT << FD->getName(); 11723 } 11724 11725 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11726 if (InNonTrivialUnion) 11727 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11728 << 1 << 2 << QT << FD->getName(); 11729 } 11730 11731 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11732 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11733 if (RD->isUnion()) { 11734 if (OrigLoc.isValid()) { 11735 bool IsUnion = false; 11736 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11737 IsUnion = OrigRD->isUnion(); 11738 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11739 << 2 << OrigTy << IsUnion << UseContext; 11740 // Reset OrigLoc so that this diagnostic is emitted only once. 11741 OrigLoc = SourceLocation(); 11742 } 11743 InNonTrivialUnion = true; 11744 } 11745 11746 if (InNonTrivialUnion) 11747 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11748 << 0 << 2 << QT.getUnqualifiedType() << ""; 11749 11750 for (const FieldDecl *FD : RD->fields()) 11751 if (!shouldIgnoreForRecordTriviality(FD)) 11752 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11753 } 11754 11755 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11756 const FieldDecl *FD, bool InNonTrivialUnion) {} 11757 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11758 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11759 bool InNonTrivialUnion) {} 11760 11761 // The non-trivial C union type or the struct/union type that contains a 11762 // non-trivial C union. 11763 QualType OrigTy; 11764 SourceLocation OrigLoc; 11765 Sema::NonTrivialCUnionContext UseContext; 11766 Sema &S; 11767 }; 11768 11769 } // namespace 11770 11771 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11772 NonTrivialCUnionContext UseContext, 11773 unsigned NonTrivialKind) { 11774 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11775 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11776 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11777 "shouldn't be called if type doesn't have a non-trivial C union"); 11778 11779 if ((NonTrivialKind & NTCUK_Init) && 11780 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11781 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11782 .visit(QT, nullptr, false); 11783 if ((NonTrivialKind & NTCUK_Destruct) && 11784 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11785 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11786 .visit(QT, nullptr, false); 11787 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11788 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11789 .visit(QT, nullptr, false); 11790 } 11791 11792 /// AddInitializerToDecl - Adds the initializer Init to the 11793 /// declaration dcl. If DirectInit is true, this is C++ direct 11794 /// initialization rather than copy initialization. 11795 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11796 // If there is no declaration, there was an error parsing it. Just ignore 11797 // the initializer. 11798 if (!RealDecl || RealDecl->isInvalidDecl()) { 11799 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11800 return; 11801 } 11802 11803 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11804 // Pure-specifiers are handled in ActOnPureSpecifier. 11805 Diag(Method->getLocation(), diag::err_member_function_initialization) 11806 << Method->getDeclName() << Init->getSourceRange(); 11807 Method->setInvalidDecl(); 11808 return; 11809 } 11810 11811 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11812 if (!VDecl) { 11813 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11814 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11815 RealDecl->setInvalidDecl(); 11816 return; 11817 } 11818 11819 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11820 if (VDecl->getType()->isUndeducedType()) { 11821 // Attempt typo correction early so that the type of the init expression can 11822 // be deduced based on the chosen correction if the original init contains a 11823 // TypoExpr. 11824 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11825 if (!Res.isUsable()) { 11826 RealDecl->setInvalidDecl(); 11827 return; 11828 } 11829 Init = Res.get(); 11830 11831 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11832 return; 11833 } 11834 11835 // dllimport cannot be used on variable definitions. 11836 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11837 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11838 VDecl->setInvalidDecl(); 11839 return; 11840 } 11841 11842 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11843 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11844 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11845 VDecl->setInvalidDecl(); 11846 return; 11847 } 11848 11849 if (!VDecl->getType()->isDependentType()) { 11850 // A definition must end up with a complete type, which means it must be 11851 // complete with the restriction that an array type might be completed by 11852 // the initializer; note that later code assumes this restriction. 11853 QualType BaseDeclType = VDecl->getType(); 11854 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11855 BaseDeclType = Array->getElementType(); 11856 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11857 diag::err_typecheck_decl_incomplete_type)) { 11858 RealDecl->setInvalidDecl(); 11859 return; 11860 } 11861 11862 // The variable can not have an abstract class type. 11863 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11864 diag::err_abstract_type_in_decl, 11865 AbstractVariableType)) 11866 VDecl->setInvalidDecl(); 11867 } 11868 11869 // If adding the initializer will turn this declaration into a definition, 11870 // and we already have a definition for this variable, diagnose or otherwise 11871 // handle the situation. 11872 VarDecl *Def; 11873 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11874 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11875 !VDecl->isThisDeclarationADemotedDefinition() && 11876 checkVarDeclRedefinition(Def, VDecl)) 11877 return; 11878 11879 if (getLangOpts().CPlusPlus) { 11880 // C++ [class.static.data]p4 11881 // If a static data member is of const integral or const 11882 // enumeration type, its declaration in the class definition can 11883 // specify a constant-initializer which shall be an integral 11884 // constant expression (5.19). In that case, the member can appear 11885 // in integral constant expressions. The member shall still be 11886 // defined in a namespace scope if it is used in the program and the 11887 // namespace scope definition shall not contain an initializer. 11888 // 11889 // We already performed a redefinition check above, but for static 11890 // data members we also need to check whether there was an in-class 11891 // declaration with an initializer. 11892 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11893 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11894 << VDecl->getDeclName(); 11895 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11896 diag::note_previous_initializer) 11897 << 0; 11898 return; 11899 } 11900 11901 if (VDecl->hasLocalStorage()) 11902 setFunctionHasBranchProtectedScope(); 11903 11904 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11905 VDecl->setInvalidDecl(); 11906 return; 11907 } 11908 } 11909 11910 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11911 // a kernel function cannot be initialized." 11912 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11913 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11914 VDecl->setInvalidDecl(); 11915 return; 11916 } 11917 11918 // Get the decls type and save a reference for later, since 11919 // CheckInitializerTypes may change it. 11920 QualType DclT = VDecl->getType(), SavT = DclT; 11921 11922 // Expressions default to 'id' when we're in a debugger 11923 // and we are assigning it to a variable of Objective-C pointer type. 11924 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11925 Init->getType() == Context.UnknownAnyTy) { 11926 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11927 if (Result.isInvalid()) { 11928 VDecl->setInvalidDecl(); 11929 return; 11930 } 11931 Init = Result.get(); 11932 } 11933 11934 // Perform the initialization. 11935 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11936 if (!VDecl->isInvalidDecl()) { 11937 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11938 InitializationKind Kind = InitializationKind::CreateForInit( 11939 VDecl->getLocation(), DirectInit, Init); 11940 11941 MultiExprArg Args = Init; 11942 if (CXXDirectInit) 11943 Args = MultiExprArg(CXXDirectInit->getExprs(), 11944 CXXDirectInit->getNumExprs()); 11945 11946 // Try to correct any TypoExprs in the initialization arguments. 11947 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11948 ExprResult Res = CorrectDelayedTyposInExpr( 11949 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11950 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11951 return Init.Failed() ? ExprError() : E; 11952 }); 11953 if (Res.isInvalid()) { 11954 VDecl->setInvalidDecl(); 11955 } else if (Res.get() != Args[Idx]) { 11956 Args[Idx] = Res.get(); 11957 } 11958 } 11959 if (VDecl->isInvalidDecl()) 11960 return; 11961 11962 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11963 /*TopLevelOfInitList=*/false, 11964 /*TreatUnavailableAsInvalid=*/false); 11965 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11966 if (Result.isInvalid()) { 11967 VDecl->setInvalidDecl(); 11968 return; 11969 } 11970 11971 Init = Result.getAs<Expr>(); 11972 } 11973 11974 // Check for self-references within variable initializers. 11975 // Variables declared within a function/method body (except for references) 11976 // are handled by a dataflow analysis. 11977 // This is undefined behavior in C++, but valid in C. 11978 if (getLangOpts().CPlusPlus) { 11979 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11980 VDecl->getType()->isReferenceType()) { 11981 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11982 } 11983 } 11984 11985 // If the type changed, it means we had an incomplete type that was 11986 // completed by the initializer. For example: 11987 // int ary[] = { 1, 3, 5 }; 11988 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11989 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11990 VDecl->setType(DclT); 11991 11992 if (!VDecl->isInvalidDecl()) { 11993 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11994 11995 if (VDecl->hasAttr<BlocksAttr>()) 11996 checkRetainCycles(VDecl, Init); 11997 11998 // It is safe to assign a weak reference into a strong variable. 11999 // Although this code can still have problems: 12000 // id x = self.weakProp; 12001 // id y = self.weakProp; 12002 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12003 // paths through the function. This should be revisited if 12004 // -Wrepeated-use-of-weak is made flow-sensitive. 12005 if (FunctionScopeInfo *FSI = getCurFunction()) 12006 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12007 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12008 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12009 Init->getBeginLoc())) 12010 FSI->markSafeWeakUse(Init); 12011 } 12012 12013 // The initialization is usually a full-expression. 12014 // 12015 // FIXME: If this is a braced initialization of an aggregate, it is not 12016 // an expression, and each individual field initializer is a separate 12017 // full-expression. For instance, in: 12018 // 12019 // struct Temp { ~Temp(); }; 12020 // struct S { S(Temp); }; 12021 // struct T { S a, b; } t = { Temp(), Temp() } 12022 // 12023 // we should destroy the first Temp before constructing the second. 12024 ExprResult Result = 12025 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12026 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12027 if (Result.isInvalid()) { 12028 VDecl->setInvalidDecl(); 12029 return; 12030 } 12031 Init = Result.get(); 12032 12033 // Attach the initializer to the decl. 12034 VDecl->setInit(Init); 12035 12036 if (VDecl->isLocalVarDecl()) { 12037 // Don't check the initializer if the declaration is malformed. 12038 if (VDecl->isInvalidDecl()) { 12039 // do nothing 12040 12041 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12042 // This is true even in C++ for OpenCL. 12043 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12044 CheckForConstantInitializer(Init, DclT); 12045 12046 // Otherwise, C++ does not restrict the initializer. 12047 } else if (getLangOpts().CPlusPlus) { 12048 // do nothing 12049 12050 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12051 // static storage duration shall be constant expressions or string literals. 12052 } else if (VDecl->getStorageClass() == SC_Static) { 12053 CheckForConstantInitializer(Init, DclT); 12054 12055 // C89 is stricter than C99 for aggregate initializers. 12056 // C89 6.5.7p3: All the expressions [...] in an initializer list 12057 // for an object that has aggregate or union type shall be 12058 // constant expressions. 12059 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12060 isa<InitListExpr>(Init)) { 12061 const Expr *Culprit; 12062 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12063 Diag(Culprit->getExprLoc(), 12064 diag::ext_aggregate_init_not_constant) 12065 << Culprit->getSourceRange(); 12066 } 12067 } 12068 12069 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12070 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12071 if (VDecl->hasLocalStorage()) 12072 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12073 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12074 VDecl->getLexicalDeclContext()->isRecord()) { 12075 // This is an in-class initialization for a static data member, e.g., 12076 // 12077 // struct S { 12078 // static const int value = 17; 12079 // }; 12080 12081 // C++ [class.mem]p4: 12082 // A member-declarator can contain a constant-initializer only 12083 // if it declares a static member (9.4) of const integral or 12084 // const enumeration type, see 9.4.2. 12085 // 12086 // C++11 [class.static.data]p3: 12087 // If a non-volatile non-inline const static data member is of integral 12088 // or enumeration type, its declaration in the class definition can 12089 // specify a brace-or-equal-initializer in which every initializer-clause 12090 // that is an assignment-expression is a constant expression. A static 12091 // data member of literal type can be declared in the class definition 12092 // with the constexpr specifier; if so, its declaration shall specify a 12093 // brace-or-equal-initializer in which every initializer-clause that is 12094 // an assignment-expression is a constant expression. 12095 12096 // Do nothing on dependent types. 12097 if (DclT->isDependentType()) { 12098 12099 // Allow any 'static constexpr' members, whether or not they are of literal 12100 // type. We separately check that every constexpr variable is of literal 12101 // type. 12102 } else if (VDecl->isConstexpr()) { 12103 12104 // Require constness. 12105 } else if (!DclT.isConstQualified()) { 12106 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12107 << Init->getSourceRange(); 12108 VDecl->setInvalidDecl(); 12109 12110 // We allow integer constant expressions in all cases. 12111 } else if (DclT->isIntegralOrEnumerationType()) { 12112 // Check whether the expression is a constant expression. 12113 SourceLocation Loc; 12114 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12115 // In C++11, a non-constexpr const static data member with an 12116 // in-class initializer cannot be volatile. 12117 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12118 else if (Init->isValueDependent()) 12119 ; // Nothing to check. 12120 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12121 ; // Ok, it's an ICE! 12122 else if (Init->getType()->isScopedEnumeralType() && 12123 Init->isCXX11ConstantExpr(Context)) 12124 ; // Ok, it is a scoped-enum constant expression. 12125 else if (Init->isEvaluatable(Context)) { 12126 // If we can constant fold the initializer through heroics, accept it, 12127 // but report this as a use of an extension for -pedantic. 12128 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12129 << Init->getSourceRange(); 12130 } else { 12131 // Otherwise, this is some crazy unknown case. Report the issue at the 12132 // location provided by the isIntegerConstantExpr failed check. 12133 Diag(Loc, diag::err_in_class_initializer_non_constant) 12134 << Init->getSourceRange(); 12135 VDecl->setInvalidDecl(); 12136 } 12137 12138 // We allow foldable floating-point constants as an extension. 12139 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12140 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12141 // it anyway and provide a fixit to add the 'constexpr'. 12142 if (getLangOpts().CPlusPlus11) { 12143 Diag(VDecl->getLocation(), 12144 diag::ext_in_class_initializer_float_type_cxx11) 12145 << DclT << Init->getSourceRange(); 12146 Diag(VDecl->getBeginLoc(), 12147 diag::note_in_class_initializer_float_type_cxx11) 12148 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12149 } else { 12150 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12151 << DclT << Init->getSourceRange(); 12152 12153 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12154 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12155 << Init->getSourceRange(); 12156 VDecl->setInvalidDecl(); 12157 } 12158 } 12159 12160 // Suggest adding 'constexpr' in C++11 for literal types. 12161 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12162 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12163 << DclT << Init->getSourceRange() 12164 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12165 VDecl->setConstexpr(true); 12166 12167 } else { 12168 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12169 << DclT << Init->getSourceRange(); 12170 VDecl->setInvalidDecl(); 12171 } 12172 } else if (VDecl->isFileVarDecl()) { 12173 // In C, extern is typically used to avoid tentative definitions when 12174 // declaring variables in headers, but adding an intializer makes it a 12175 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12176 // In C++, extern is often used to give implictly static const variables 12177 // external linkage, so don't warn in that case. If selectany is present, 12178 // this might be header code intended for C and C++ inclusion, so apply the 12179 // C++ rules. 12180 if (VDecl->getStorageClass() == SC_Extern && 12181 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12182 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12183 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12184 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12185 Diag(VDecl->getLocation(), diag::warn_extern_init); 12186 12187 // In Microsoft C++ mode, a const variable defined in namespace scope has 12188 // external linkage by default if the variable is declared with 12189 // __declspec(dllexport). 12190 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12191 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12192 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12193 VDecl->setStorageClass(SC_Extern); 12194 12195 // C99 6.7.8p4. All file scoped initializers need to be constant. 12196 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12197 CheckForConstantInitializer(Init, DclT); 12198 } 12199 12200 QualType InitType = Init->getType(); 12201 if (!InitType.isNull() && 12202 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12203 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12204 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12205 12206 // We will represent direct-initialization similarly to copy-initialization: 12207 // int x(1); -as-> int x = 1; 12208 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12209 // 12210 // Clients that want to distinguish between the two forms, can check for 12211 // direct initializer using VarDecl::getInitStyle(). 12212 // A major benefit is that clients that don't particularly care about which 12213 // exactly form was it (like the CodeGen) can handle both cases without 12214 // special case code. 12215 12216 // C++ 8.5p11: 12217 // The form of initialization (using parentheses or '=') is generally 12218 // insignificant, but does matter when the entity being initialized has a 12219 // class type. 12220 if (CXXDirectInit) { 12221 assert(DirectInit && "Call-style initializer must be direct init."); 12222 VDecl->setInitStyle(VarDecl::CallInit); 12223 } else if (DirectInit) { 12224 // This must be list-initialization. No other way is direct-initialization. 12225 VDecl->setInitStyle(VarDecl::ListInit); 12226 } 12227 12228 CheckCompleteVariableDeclaration(VDecl); 12229 } 12230 12231 /// ActOnInitializerError - Given that there was an error parsing an 12232 /// initializer for the given declaration, try to return to some form 12233 /// of sanity. 12234 void Sema::ActOnInitializerError(Decl *D) { 12235 // Our main concern here is re-establishing invariants like "a 12236 // variable's type is either dependent or complete". 12237 if (!D || D->isInvalidDecl()) return; 12238 12239 VarDecl *VD = dyn_cast<VarDecl>(D); 12240 if (!VD) return; 12241 12242 // Bindings are not usable if we can't make sense of the initializer. 12243 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12244 for (auto *BD : DD->bindings()) 12245 BD->setInvalidDecl(); 12246 12247 // Auto types are meaningless if we can't make sense of the initializer. 12248 if (ParsingInitForAutoVars.count(D)) { 12249 D->setInvalidDecl(); 12250 return; 12251 } 12252 12253 QualType Ty = VD->getType(); 12254 if (Ty->isDependentType()) return; 12255 12256 // Require a complete type. 12257 if (RequireCompleteType(VD->getLocation(), 12258 Context.getBaseElementType(Ty), 12259 diag::err_typecheck_decl_incomplete_type)) { 12260 VD->setInvalidDecl(); 12261 return; 12262 } 12263 12264 // Require a non-abstract type. 12265 if (RequireNonAbstractType(VD->getLocation(), Ty, 12266 diag::err_abstract_type_in_decl, 12267 AbstractVariableType)) { 12268 VD->setInvalidDecl(); 12269 return; 12270 } 12271 12272 // Don't bother complaining about constructors or destructors, 12273 // though. 12274 } 12275 12276 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12277 // If there is no declaration, there was an error parsing it. Just ignore it. 12278 if (!RealDecl) 12279 return; 12280 12281 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12282 QualType Type = Var->getType(); 12283 12284 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12285 if (isa<DecompositionDecl>(RealDecl)) { 12286 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12287 Var->setInvalidDecl(); 12288 return; 12289 } 12290 12291 if (Type->isUndeducedType() && 12292 DeduceVariableDeclarationType(Var, false, nullptr)) 12293 return; 12294 12295 // C++11 [class.static.data]p3: A static data member can be declared with 12296 // the constexpr specifier; if so, its declaration shall specify 12297 // a brace-or-equal-initializer. 12298 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12299 // the definition of a variable [...] or the declaration of a static data 12300 // member. 12301 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12302 !Var->isThisDeclarationADemotedDefinition()) { 12303 if (Var->isStaticDataMember()) { 12304 // C++1z removes the relevant rule; the in-class declaration is always 12305 // a definition there. 12306 if (!getLangOpts().CPlusPlus17 && 12307 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12308 Diag(Var->getLocation(), 12309 diag::err_constexpr_static_mem_var_requires_init) 12310 << Var->getDeclName(); 12311 Var->setInvalidDecl(); 12312 return; 12313 } 12314 } else { 12315 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12316 Var->setInvalidDecl(); 12317 return; 12318 } 12319 } 12320 12321 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12322 // be initialized. 12323 if (!Var->isInvalidDecl() && 12324 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12325 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12326 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12327 Var->setInvalidDecl(); 12328 return; 12329 } 12330 12331 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12332 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12333 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12334 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12335 NTCUC_DefaultInitializedObject, NTCUK_Init); 12336 12337 12338 switch (DefKind) { 12339 case VarDecl::Definition: 12340 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12341 break; 12342 12343 // We have an out-of-line definition of a static data member 12344 // that has an in-class initializer, so we type-check this like 12345 // a declaration. 12346 // 12347 LLVM_FALLTHROUGH; 12348 12349 case VarDecl::DeclarationOnly: 12350 // It's only a declaration. 12351 12352 // Block scope. C99 6.7p7: If an identifier for an object is 12353 // declared with no linkage (C99 6.2.2p6), the type for the 12354 // object shall be complete. 12355 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12356 !Var->hasLinkage() && !Var->isInvalidDecl() && 12357 RequireCompleteType(Var->getLocation(), Type, 12358 diag::err_typecheck_decl_incomplete_type)) 12359 Var->setInvalidDecl(); 12360 12361 // Make sure that the type is not abstract. 12362 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12363 RequireNonAbstractType(Var->getLocation(), Type, 12364 diag::err_abstract_type_in_decl, 12365 AbstractVariableType)) 12366 Var->setInvalidDecl(); 12367 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12368 Var->getStorageClass() == SC_PrivateExtern) { 12369 Diag(Var->getLocation(), diag::warn_private_extern); 12370 Diag(Var->getLocation(), diag::note_private_extern); 12371 } 12372 12373 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12374 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12375 ExternalDeclarations.push_back(Var); 12376 12377 return; 12378 12379 case VarDecl::TentativeDefinition: 12380 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12381 // object that has file scope without an initializer, and without a 12382 // storage-class specifier or with the storage-class specifier "static", 12383 // constitutes a tentative definition. Note: A tentative definition with 12384 // external linkage is valid (C99 6.2.2p5). 12385 if (!Var->isInvalidDecl()) { 12386 if (const IncompleteArrayType *ArrayT 12387 = Context.getAsIncompleteArrayType(Type)) { 12388 if (RequireCompleteSizedType( 12389 Var->getLocation(), ArrayT->getElementType(), 12390 diag::err_array_incomplete_or_sizeless_type)) 12391 Var->setInvalidDecl(); 12392 } else if (Var->getStorageClass() == SC_Static) { 12393 // C99 6.9.2p3: If the declaration of an identifier for an object is 12394 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12395 // declared type shall not be an incomplete type. 12396 // NOTE: code such as the following 12397 // static struct s; 12398 // struct s { int a; }; 12399 // is accepted by gcc. Hence here we issue a warning instead of 12400 // an error and we do not invalidate the static declaration. 12401 // NOTE: to avoid multiple warnings, only check the first declaration. 12402 if (Var->isFirstDecl()) 12403 RequireCompleteType(Var->getLocation(), Type, 12404 diag::ext_typecheck_decl_incomplete_type); 12405 } 12406 } 12407 12408 // Record the tentative definition; we're done. 12409 if (!Var->isInvalidDecl()) 12410 TentativeDefinitions.push_back(Var); 12411 return; 12412 } 12413 12414 // Provide a specific diagnostic for uninitialized variable 12415 // definitions with incomplete array type. 12416 if (Type->isIncompleteArrayType()) { 12417 Diag(Var->getLocation(), 12418 diag::err_typecheck_incomplete_array_needs_initializer); 12419 Var->setInvalidDecl(); 12420 return; 12421 } 12422 12423 // Provide a specific diagnostic for uninitialized variable 12424 // definitions with reference type. 12425 if (Type->isReferenceType()) { 12426 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12427 << Var->getDeclName() 12428 << SourceRange(Var->getLocation(), Var->getLocation()); 12429 Var->setInvalidDecl(); 12430 return; 12431 } 12432 12433 // Do not attempt to type-check the default initializer for a 12434 // variable with dependent type. 12435 if (Type->isDependentType()) 12436 return; 12437 12438 if (Var->isInvalidDecl()) 12439 return; 12440 12441 if (!Var->hasAttr<AliasAttr>()) { 12442 if (RequireCompleteType(Var->getLocation(), 12443 Context.getBaseElementType(Type), 12444 diag::err_typecheck_decl_incomplete_type)) { 12445 Var->setInvalidDecl(); 12446 return; 12447 } 12448 } else { 12449 return; 12450 } 12451 12452 // The variable can not have an abstract class type. 12453 if (RequireNonAbstractType(Var->getLocation(), Type, 12454 diag::err_abstract_type_in_decl, 12455 AbstractVariableType)) { 12456 Var->setInvalidDecl(); 12457 return; 12458 } 12459 12460 // Check for jumps past the implicit initializer. C++0x 12461 // clarifies that this applies to a "variable with automatic 12462 // storage duration", not a "local variable". 12463 // C++11 [stmt.dcl]p3 12464 // A program that jumps from a point where a variable with automatic 12465 // storage duration is not in scope to a point where it is in scope is 12466 // ill-formed unless the variable has scalar type, class type with a 12467 // trivial default constructor and a trivial destructor, a cv-qualified 12468 // version of one of these types, or an array of one of the preceding 12469 // types and is declared without an initializer. 12470 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12471 if (const RecordType *Record 12472 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12473 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12474 // Mark the function (if we're in one) for further checking even if the 12475 // looser rules of C++11 do not require such checks, so that we can 12476 // diagnose incompatibilities with C++98. 12477 if (!CXXRecord->isPOD()) 12478 setFunctionHasBranchProtectedScope(); 12479 } 12480 } 12481 // In OpenCL, we can't initialize objects in the __local address space, 12482 // even implicitly, so don't synthesize an implicit initializer. 12483 if (getLangOpts().OpenCL && 12484 Var->getType().getAddressSpace() == LangAS::opencl_local) 12485 return; 12486 // C++03 [dcl.init]p9: 12487 // If no initializer is specified for an object, and the 12488 // object is of (possibly cv-qualified) non-POD class type (or 12489 // array thereof), the object shall be default-initialized; if 12490 // the object is of const-qualified type, the underlying class 12491 // type shall have a user-declared default 12492 // constructor. Otherwise, if no initializer is specified for 12493 // a non- static object, the object and its subobjects, if 12494 // any, have an indeterminate initial value); if the object 12495 // or any of its subobjects are of const-qualified type, the 12496 // program is ill-formed. 12497 // C++0x [dcl.init]p11: 12498 // If no initializer is specified for an object, the object is 12499 // default-initialized; [...]. 12500 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12501 InitializationKind Kind 12502 = InitializationKind::CreateDefault(Var->getLocation()); 12503 12504 InitializationSequence InitSeq(*this, Entity, Kind, None); 12505 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12506 if (Init.isInvalid()) 12507 Var->setInvalidDecl(); 12508 else if (Init.get()) { 12509 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12510 // This is important for template substitution. 12511 Var->setInitStyle(VarDecl::CallInit); 12512 } 12513 12514 CheckCompleteVariableDeclaration(Var); 12515 } 12516 } 12517 12518 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12519 // If there is no declaration, there was an error parsing it. Ignore it. 12520 if (!D) 12521 return; 12522 12523 VarDecl *VD = dyn_cast<VarDecl>(D); 12524 if (!VD) { 12525 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12526 D->setInvalidDecl(); 12527 return; 12528 } 12529 12530 VD->setCXXForRangeDecl(true); 12531 12532 // for-range-declaration cannot be given a storage class specifier. 12533 int Error = -1; 12534 switch (VD->getStorageClass()) { 12535 case SC_None: 12536 break; 12537 case SC_Extern: 12538 Error = 0; 12539 break; 12540 case SC_Static: 12541 Error = 1; 12542 break; 12543 case SC_PrivateExtern: 12544 Error = 2; 12545 break; 12546 case SC_Auto: 12547 Error = 3; 12548 break; 12549 case SC_Register: 12550 Error = 4; 12551 break; 12552 } 12553 if (Error != -1) { 12554 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12555 << VD->getDeclName() << Error; 12556 D->setInvalidDecl(); 12557 } 12558 } 12559 12560 StmtResult 12561 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12562 IdentifierInfo *Ident, 12563 ParsedAttributes &Attrs, 12564 SourceLocation AttrEnd) { 12565 // C++1y [stmt.iter]p1: 12566 // A range-based for statement of the form 12567 // for ( for-range-identifier : for-range-initializer ) statement 12568 // is equivalent to 12569 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12570 DeclSpec DS(Attrs.getPool().getFactory()); 12571 12572 const char *PrevSpec; 12573 unsigned DiagID; 12574 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12575 getPrintingPolicy()); 12576 12577 Declarator D(DS, DeclaratorContext::ForContext); 12578 D.SetIdentifier(Ident, IdentLoc); 12579 D.takeAttributes(Attrs, AttrEnd); 12580 12581 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12582 IdentLoc); 12583 Decl *Var = ActOnDeclarator(S, D); 12584 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12585 FinalizeDeclaration(Var); 12586 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12587 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12588 } 12589 12590 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12591 if (var->isInvalidDecl()) return; 12592 12593 if (getLangOpts().OpenCL) { 12594 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12595 // initialiser 12596 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12597 !var->hasInit()) { 12598 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12599 << 1 /*Init*/; 12600 var->setInvalidDecl(); 12601 return; 12602 } 12603 } 12604 12605 // In Objective-C, don't allow jumps past the implicit initialization of a 12606 // local retaining variable. 12607 if (getLangOpts().ObjC && 12608 var->hasLocalStorage()) { 12609 switch (var->getType().getObjCLifetime()) { 12610 case Qualifiers::OCL_None: 12611 case Qualifiers::OCL_ExplicitNone: 12612 case Qualifiers::OCL_Autoreleasing: 12613 break; 12614 12615 case Qualifiers::OCL_Weak: 12616 case Qualifiers::OCL_Strong: 12617 setFunctionHasBranchProtectedScope(); 12618 break; 12619 } 12620 } 12621 12622 if (var->hasLocalStorage() && 12623 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12624 setFunctionHasBranchProtectedScope(); 12625 12626 // Warn about externally-visible variables being defined without a 12627 // prior declaration. We only want to do this for global 12628 // declarations, but we also specifically need to avoid doing it for 12629 // class members because the linkage of an anonymous class can 12630 // change if it's later given a typedef name. 12631 if (var->isThisDeclarationADefinition() && 12632 var->getDeclContext()->getRedeclContext()->isFileContext() && 12633 var->isExternallyVisible() && var->hasLinkage() && 12634 !var->isInline() && !var->getDescribedVarTemplate() && 12635 !isa<VarTemplatePartialSpecializationDecl>(var) && 12636 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12637 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12638 var->getLocation())) { 12639 // Find a previous declaration that's not a definition. 12640 VarDecl *prev = var->getPreviousDecl(); 12641 while (prev && prev->isThisDeclarationADefinition()) 12642 prev = prev->getPreviousDecl(); 12643 12644 if (!prev) { 12645 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12646 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12647 << /* variable */ 0; 12648 } 12649 } 12650 12651 // Cache the result of checking for constant initialization. 12652 Optional<bool> CacheHasConstInit; 12653 const Expr *CacheCulprit = nullptr; 12654 auto checkConstInit = [&]() mutable { 12655 if (!CacheHasConstInit) 12656 CacheHasConstInit = var->getInit()->isConstantInitializer( 12657 Context, var->getType()->isReferenceType(), &CacheCulprit); 12658 return *CacheHasConstInit; 12659 }; 12660 12661 if (var->getTLSKind() == VarDecl::TLS_Static) { 12662 if (var->getType().isDestructedType()) { 12663 // GNU C++98 edits for __thread, [basic.start.term]p3: 12664 // The type of an object with thread storage duration shall not 12665 // have a non-trivial destructor. 12666 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12667 if (getLangOpts().CPlusPlus11) 12668 Diag(var->getLocation(), diag::note_use_thread_local); 12669 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12670 if (!checkConstInit()) { 12671 // GNU C++98 edits for __thread, [basic.start.init]p4: 12672 // An object of thread storage duration shall not require dynamic 12673 // initialization. 12674 // FIXME: Need strict checking here. 12675 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12676 << CacheCulprit->getSourceRange(); 12677 if (getLangOpts().CPlusPlus11) 12678 Diag(var->getLocation(), diag::note_use_thread_local); 12679 } 12680 } 12681 } 12682 12683 // Apply section attributes and pragmas to global variables. 12684 bool GlobalStorage = var->hasGlobalStorage(); 12685 if (GlobalStorage && var->isThisDeclarationADefinition() && 12686 !inTemplateInstantiation()) { 12687 PragmaStack<StringLiteral *> *Stack = nullptr; 12688 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12689 if (var->getType().isConstQualified()) 12690 Stack = &ConstSegStack; 12691 else if (!var->getInit()) { 12692 Stack = &BSSSegStack; 12693 SectionFlags |= ASTContext::PSF_Write; 12694 } else { 12695 Stack = &DataSegStack; 12696 SectionFlags |= ASTContext::PSF_Write; 12697 } 12698 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12699 var->addAttr(SectionAttr::CreateImplicit( 12700 Context, Stack->CurrentValue->getString(), 12701 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12702 SectionAttr::Declspec_allocate)); 12703 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12704 if (UnifySection(SA->getName(), SectionFlags, var)) 12705 var->dropAttr<SectionAttr>(); 12706 12707 // Apply the init_seg attribute if this has an initializer. If the 12708 // initializer turns out to not be dynamic, we'll end up ignoring this 12709 // attribute. 12710 if (CurInitSeg && var->getInit()) 12711 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12712 CurInitSegLoc, 12713 AttributeCommonInfo::AS_Pragma)); 12714 } 12715 12716 // All the following checks are C++ only. 12717 if (!getLangOpts().CPlusPlus) { 12718 // If this variable must be emitted, add it as an initializer for the 12719 // current module. 12720 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12721 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12722 return; 12723 } 12724 12725 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12726 CheckCompleteDecompositionDeclaration(DD); 12727 12728 QualType type = var->getType(); 12729 if (type->isDependentType()) return; 12730 12731 if (var->hasAttr<BlocksAttr>()) 12732 getCurFunction()->addByrefBlockVar(var); 12733 12734 Expr *Init = var->getInit(); 12735 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12736 QualType baseType = Context.getBaseElementType(type); 12737 12738 if (Init && !Init->isValueDependent()) { 12739 if (var->isConstexpr()) { 12740 SmallVector<PartialDiagnosticAt, 8> Notes; 12741 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12742 SourceLocation DiagLoc = var->getLocation(); 12743 // If the note doesn't add any useful information other than a source 12744 // location, fold it into the primary diagnostic. 12745 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12746 diag::note_invalid_subexpr_in_const_expr) { 12747 DiagLoc = Notes[0].first; 12748 Notes.clear(); 12749 } 12750 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12751 << var << Init->getSourceRange(); 12752 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12753 Diag(Notes[I].first, Notes[I].second); 12754 } 12755 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12756 // Check whether the initializer of a const variable of integral or 12757 // enumeration type is an ICE now, since we can't tell whether it was 12758 // initialized by a constant expression if we check later. 12759 var->checkInitIsICE(); 12760 } 12761 12762 // Don't emit further diagnostics about constexpr globals since they 12763 // were just diagnosed. 12764 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12765 // FIXME: Need strict checking in C++03 here. 12766 bool DiagErr = getLangOpts().CPlusPlus11 12767 ? !var->checkInitIsICE() : !checkConstInit(); 12768 if (DiagErr) { 12769 auto *Attr = var->getAttr<ConstInitAttr>(); 12770 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12771 << Init->getSourceRange(); 12772 Diag(Attr->getLocation(), 12773 diag::note_declared_required_constant_init_here) 12774 << Attr->getRange() << Attr->isConstinit(); 12775 if (getLangOpts().CPlusPlus11) { 12776 APValue Value; 12777 SmallVector<PartialDiagnosticAt, 8> Notes; 12778 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12779 for (auto &it : Notes) 12780 Diag(it.first, it.second); 12781 } else { 12782 Diag(CacheCulprit->getExprLoc(), 12783 diag::note_invalid_subexpr_in_const_expr) 12784 << CacheCulprit->getSourceRange(); 12785 } 12786 } 12787 } 12788 else if (!var->isConstexpr() && IsGlobal && 12789 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12790 var->getLocation())) { 12791 // Warn about globals which don't have a constant initializer. Don't 12792 // warn about globals with a non-trivial destructor because we already 12793 // warned about them. 12794 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12795 if (!(RD && !RD->hasTrivialDestructor())) { 12796 if (!checkConstInit()) 12797 Diag(var->getLocation(), diag::warn_global_constructor) 12798 << Init->getSourceRange(); 12799 } 12800 } 12801 } 12802 12803 // Require the destructor. 12804 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12805 FinalizeVarWithDestructor(var, recordType); 12806 12807 // If this variable must be emitted, add it as an initializer for the current 12808 // module. 12809 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12810 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12811 } 12812 12813 /// Determines if a variable's alignment is dependent. 12814 static bool hasDependentAlignment(VarDecl *VD) { 12815 if (VD->getType()->isDependentType()) 12816 return true; 12817 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12818 if (I->isAlignmentDependent()) 12819 return true; 12820 return false; 12821 } 12822 12823 /// Check if VD needs to be dllexport/dllimport due to being in a 12824 /// dllexport/import function. 12825 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12826 assert(VD->isStaticLocal()); 12827 12828 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12829 12830 // Find outermost function when VD is in lambda function. 12831 while (FD && !getDLLAttr(FD) && 12832 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12833 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12834 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12835 } 12836 12837 if (!FD) 12838 return; 12839 12840 // Static locals inherit dll attributes from their function. 12841 if (Attr *A = getDLLAttr(FD)) { 12842 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12843 NewAttr->setInherited(true); 12844 VD->addAttr(NewAttr); 12845 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12846 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12847 NewAttr->setInherited(true); 12848 VD->addAttr(NewAttr); 12849 12850 // Export this function to enforce exporting this static variable even 12851 // if it is not used in this compilation unit. 12852 if (!FD->hasAttr<DLLExportAttr>()) 12853 FD->addAttr(NewAttr); 12854 12855 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12856 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12857 NewAttr->setInherited(true); 12858 VD->addAttr(NewAttr); 12859 } 12860 } 12861 12862 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12863 /// any semantic actions necessary after any initializer has been attached. 12864 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12865 // Note that we are no longer parsing the initializer for this declaration. 12866 ParsingInitForAutoVars.erase(ThisDecl); 12867 12868 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12869 if (!VD) 12870 return; 12871 12872 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12873 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12874 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12875 if (PragmaClangBSSSection.Valid) 12876 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12877 Context, PragmaClangBSSSection.SectionName, 12878 PragmaClangBSSSection.PragmaLocation, 12879 AttributeCommonInfo::AS_Pragma)); 12880 if (PragmaClangDataSection.Valid) 12881 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12882 Context, PragmaClangDataSection.SectionName, 12883 PragmaClangDataSection.PragmaLocation, 12884 AttributeCommonInfo::AS_Pragma)); 12885 if (PragmaClangRodataSection.Valid) 12886 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12887 Context, PragmaClangRodataSection.SectionName, 12888 PragmaClangRodataSection.PragmaLocation, 12889 AttributeCommonInfo::AS_Pragma)); 12890 if (PragmaClangRelroSection.Valid) 12891 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12892 Context, PragmaClangRelroSection.SectionName, 12893 PragmaClangRelroSection.PragmaLocation, 12894 AttributeCommonInfo::AS_Pragma)); 12895 } 12896 12897 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12898 for (auto *BD : DD->bindings()) { 12899 FinalizeDeclaration(BD); 12900 } 12901 } 12902 12903 checkAttributesAfterMerging(*this, *VD); 12904 12905 // Perform TLS alignment check here after attributes attached to the variable 12906 // which may affect the alignment have been processed. Only perform the check 12907 // if the target has a maximum TLS alignment (zero means no constraints). 12908 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12909 // Protect the check so that it's not performed on dependent types and 12910 // dependent alignments (we can't determine the alignment in that case). 12911 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12912 !VD->isInvalidDecl()) { 12913 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12914 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12915 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12916 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12917 << (unsigned)MaxAlignChars.getQuantity(); 12918 } 12919 } 12920 } 12921 12922 if (VD->isStaticLocal()) { 12923 CheckStaticLocalForDllExport(VD); 12924 12925 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12926 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12927 // function, only __shared__ variables or variables without any device 12928 // memory qualifiers may be declared with static storage class. 12929 // Note: It is unclear how a function-scope non-const static variable 12930 // without device memory qualifier is implemented, therefore only static 12931 // const variable without device memory qualifier is allowed. 12932 [&]() { 12933 if (!getLangOpts().CUDA) 12934 return; 12935 if (VD->hasAttr<CUDASharedAttr>()) 12936 return; 12937 if (VD->getType().isConstQualified() && 12938 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12939 return; 12940 if (CUDADiagIfDeviceCode(VD->getLocation(), 12941 diag::err_device_static_local_var) 12942 << CurrentCUDATarget()) 12943 VD->setInvalidDecl(); 12944 }(); 12945 } 12946 } 12947 12948 // Perform check for initializers of device-side global variables. 12949 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12950 // 7.5). We must also apply the same checks to all __shared__ 12951 // variables whether they are local or not. CUDA also allows 12952 // constant initializers for __constant__ and __device__ variables. 12953 if (getLangOpts().CUDA) 12954 checkAllowedCUDAInitializer(VD); 12955 12956 // Grab the dllimport or dllexport attribute off of the VarDecl. 12957 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12958 12959 // Imported static data members cannot be defined out-of-line. 12960 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12961 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12962 VD->isThisDeclarationADefinition()) { 12963 // We allow definitions of dllimport class template static data members 12964 // with a warning. 12965 CXXRecordDecl *Context = 12966 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12967 bool IsClassTemplateMember = 12968 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12969 Context->getDescribedClassTemplate(); 12970 12971 Diag(VD->getLocation(), 12972 IsClassTemplateMember 12973 ? diag::warn_attribute_dllimport_static_field_definition 12974 : diag::err_attribute_dllimport_static_field_definition); 12975 Diag(IA->getLocation(), diag::note_attribute); 12976 if (!IsClassTemplateMember) 12977 VD->setInvalidDecl(); 12978 } 12979 } 12980 12981 // dllimport/dllexport variables cannot be thread local, their TLS index 12982 // isn't exported with the variable. 12983 if (DLLAttr && VD->getTLSKind()) { 12984 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12985 if (F && getDLLAttr(F)) { 12986 assert(VD->isStaticLocal()); 12987 // But if this is a static local in a dlimport/dllexport function, the 12988 // function will never be inlined, which means the var would never be 12989 // imported, so having it marked import/export is safe. 12990 } else { 12991 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12992 << DLLAttr; 12993 VD->setInvalidDecl(); 12994 } 12995 } 12996 12997 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12998 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12999 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13000 VD->dropAttr<UsedAttr>(); 13001 } 13002 } 13003 13004 const DeclContext *DC = VD->getDeclContext(); 13005 // If there's a #pragma GCC visibility in scope, and this isn't a class 13006 // member, set the visibility of this variable. 13007 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13008 AddPushedVisibilityAttribute(VD); 13009 13010 // FIXME: Warn on unused var template partial specializations. 13011 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13012 MarkUnusedFileScopedDecl(VD); 13013 13014 // Now we have parsed the initializer and can update the table of magic 13015 // tag values. 13016 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13017 !VD->getType()->isIntegralOrEnumerationType()) 13018 return; 13019 13020 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13021 const Expr *MagicValueExpr = VD->getInit(); 13022 if (!MagicValueExpr) { 13023 continue; 13024 } 13025 llvm::APSInt MagicValueInt; 13026 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13027 Diag(I->getRange().getBegin(), 13028 diag::err_type_tag_for_datatype_not_ice) 13029 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13030 continue; 13031 } 13032 if (MagicValueInt.getActiveBits() > 64) { 13033 Diag(I->getRange().getBegin(), 13034 diag::err_type_tag_for_datatype_too_large) 13035 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13036 continue; 13037 } 13038 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13039 RegisterTypeTagForDatatype(I->getArgumentKind(), 13040 MagicValue, 13041 I->getMatchingCType(), 13042 I->getLayoutCompatible(), 13043 I->getMustBeNull()); 13044 } 13045 } 13046 13047 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13048 auto *VD = dyn_cast<VarDecl>(DD); 13049 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13050 } 13051 13052 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13053 ArrayRef<Decl *> Group) { 13054 SmallVector<Decl*, 8> Decls; 13055 13056 if (DS.isTypeSpecOwned()) 13057 Decls.push_back(DS.getRepAsDecl()); 13058 13059 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13060 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13061 bool DiagnosedMultipleDecomps = false; 13062 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13063 bool DiagnosedNonDeducedAuto = false; 13064 13065 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13066 if (Decl *D = Group[i]) { 13067 // For declarators, there are some additional syntactic-ish checks we need 13068 // to perform. 13069 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13070 if (!FirstDeclaratorInGroup) 13071 FirstDeclaratorInGroup = DD; 13072 if (!FirstDecompDeclaratorInGroup) 13073 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13074 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13075 !hasDeducedAuto(DD)) 13076 FirstNonDeducedAutoInGroup = DD; 13077 13078 if (FirstDeclaratorInGroup != DD) { 13079 // A decomposition declaration cannot be combined with any other 13080 // declaration in the same group. 13081 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13082 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13083 diag::err_decomp_decl_not_alone) 13084 << FirstDeclaratorInGroup->getSourceRange() 13085 << DD->getSourceRange(); 13086 DiagnosedMultipleDecomps = true; 13087 } 13088 13089 // A declarator that uses 'auto' in any way other than to declare a 13090 // variable with a deduced type cannot be combined with any other 13091 // declarator in the same group. 13092 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13093 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13094 diag::err_auto_non_deduced_not_alone) 13095 << FirstNonDeducedAutoInGroup->getType() 13096 ->hasAutoForTrailingReturnType() 13097 << FirstDeclaratorInGroup->getSourceRange() 13098 << DD->getSourceRange(); 13099 DiagnosedNonDeducedAuto = true; 13100 } 13101 } 13102 } 13103 13104 Decls.push_back(D); 13105 } 13106 } 13107 13108 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13109 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13110 handleTagNumbering(Tag, S); 13111 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13112 getLangOpts().CPlusPlus) 13113 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13114 } 13115 } 13116 13117 return BuildDeclaratorGroup(Decls); 13118 } 13119 13120 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13121 /// group, performing any necessary semantic checking. 13122 Sema::DeclGroupPtrTy 13123 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13124 // C++14 [dcl.spec.auto]p7: (DR1347) 13125 // If the type that replaces the placeholder type is not the same in each 13126 // deduction, the program is ill-formed. 13127 if (Group.size() > 1) { 13128 QualType Deduced; 13129 VarDecl *DeducedDecl = nullptr; 13130 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13131 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13132 if (!D || D->isInvalidDecl()) 13133 break; 13134 DeducedType *DT = D->getType()->getContainedDeducedType(); 13135 if (!DT || DT->getDeducedType().isNull()) 13136 continue; 13137 if (Deduced.isNull()) { 13138 Deduced = DT->getDeducedType(); 13139 DeducedDecl = D; 13140 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13141 auto *AT = dyn_cast<AutoType>(DT); 13142 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13143 diag::err_auto_different_deductions) 13144 << (AT ? (unsigned)AT->getKeyword() : 3) 13145 << Deduced << DeducedDecl->getDeclName() 13146 << DT->getDeducedType() << D->getDeclName() 13147 << DeducedDecl->getInit()->getSourceRange() 13148 << D->getInit()->getSourceRange(); 13149 D->setInvalidDecl(); 13150 break; 13151 } 13152 } 13153 } 13154 13155 ActOnDocumentableDecls(Group); 13156 13157 return DeclGroupPtrTy::make( 13158 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13159 } 13160 13161 void Sema::ActOnDocumentableDecl(Decl *D) { 13162 ActOnDocumentableDecls(D); 13163 } 13164 13165 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13166 // Don't parse the comment if Doxygen diagnostics are ignored. 13167 if (Group.empty() || !Group[0]) 13168 return; 13169 13170 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13171 Group[0]->getLocation()) && 13172 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13173 Group[0]->getLocation())) 13174 return; 13175 13176 if (Group.size() >= 2) { 13177 // This is a decl group. Normally it will contain only declarations 13178 // produced from declarator list. But in case we have any definitions or 13179 // additional declaration references: 13180 // 'typedef struct S {} S;' 13181 // 'typedef struct S *S;' 13182 // 'struct S *pS;' 13183 // FinalizeDeclaratorGroup adds these as separate declarations. 13184 Decl *MaybeTagDecl = Group[0]; 13185 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13186 Group = Group.slice(1); 13187 } 13188 } 13189 13190 // FIMXE: We assume every Decl in the group is in the same file. 13191 // This is false when preprocessor constructs the group from decls in 13192 // different files (e. g. macros or #include). 13193 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13194 } 13195 13196 /// Common checks for a parameter-declaration that should apply to both function 13197 /// parameters and non-type template parameters. 13198 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13199 // Check that there are no default arguments inside the type of this 13200 // parameter. 13201 if (getLangOpts().CPlusPlus) 13202 CheckExtraCXXDefaultArguments(D); 13203 13204 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13205 if (D.getCXXScopeSpec().isSet()) { 13206 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13207 << D.getCXXScopeSpec().getRange(); 13208 } 13209 13210 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13211 // simple identifier except [...irrelevant cases...]. 13212 switch (D.getName().getKind()) { 13213 case UnqualifiedIdKind::IK_Identifier: 13214 break; 13215 13216 case UnqualifiedIdKind::IK_OperatorFunctionId: 13217 case UnqualifiedIdKind::IK_ConversionFunctionId: 13218 case UnqualifiedIdKind::IK_LiteralOperatorId: 13219 case UnqualifiedIdKind::IK_ConstructorName: 13220 case UnqualifiedIdKind::IK_DestructorName: 13221 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13222 case UnqualifiedIdKind::IK_DeductionGuideName: 13223 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13224 << GetNameForDeclarator(D).getName(); 13225 break; 13226 13227 case UnqualifiedIdKind::IK_TemplateId: 13228 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13229 // GetNameForDeclarator would not produce a useful name in this case. 13230 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13231 break; 13232 } 13233 } 13234 13235 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13236 /// to introduce parameters into function prototype scope. 13237 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13238 const DeclSpec &DS = D.getDeclSpec(); 13239 13240 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13241 13242 // C++03 [dcl.stc]p2 also permits 'auto'. 13243 StorageClass SC = SC_None; 13244 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13245 SC = SC_Register; 13246 // In C++11, the 'register' storage class specifier is deprecated. 13247 // In C++17, it is not allowed, but we tolerate it as an extension. 13248 if (getLangOpts().CPlusPlus11) { 13249 Diag(DS.getStorageClassSpecLoc(), 13250 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13251 : diag::warn_deprecated_register) 13252 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13253 } 13254 } else if (getLangOpts().CPlusPlus && 13255 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13256 SC = SC_Auto; 13257 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13258 Diag(DS.getStorageClassSpecLoc(), 13259 diag::err_invalid_storage_class_in_func_decl); 13260 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13261 } 13262 13263 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13264 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13265 << DeclSpec::getSpecifierName(TSCS); 13266 if (DS.isInlineSpecified()) 13267 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13268 << getLangOpts().CPlusPlus17; 13269 if (DS.hasConstexprSpecifier()) 13270 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13271 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13272 13273 DiagnoseFunctionSpecifiers(DS); 13274 13275 CheckFunctionOrTemplateParamDeclarator(S, D); 13276 13277 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13278 QualType parmDeclType = TInfo->getType(); 13279 13280 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13281 IdentifierInfo *II = D.getIdentifier(); 13282 if (II) { 13283 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13284 ForVisibleRedeclaration); 13285 LookupName(R, S); 13286 if (R.isSingleResult()) { 13287 NamedDecl *PrevDecl = R.getFoundDecl(); 13288 if (PrevDecl->isTemplateParameter()) { 13289 // Maybe we will complain about the shadowed template parameter. 13290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13291 // Just pretend that we didn't see the previous declaration. 13292 PrevDecl = nullptr; 13293 } else if (S->isDeclScope(PrevDecl)) { 13294 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13295 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13296 13297 // Recover by removing the name 13298 II = nullptr; 13299 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13300 D.setInvalidType(true); 13301 } 13302 } 13303 } 13304 13305 // Temporarily put parameter variables in the translation unit, not 13306 // the enclosing context. This prevents them from accidentally 13307 // looking like class members in C++. 13308 ParmVarDecl *New = 13309 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13310 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13311 13312 if (D.isInvalidType()) 13313 New->setInvalidDecl(); 13314 13315 assert(S->isFunctionPrototypeScope()); 13316 assert(S->getFunctionPrototypeDepth() >= 1); 13317 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13318 S->getNextFunctionPrototypeIndex()); 13319 13320 // Add the parameter declaration into this scope. 13321 S->AddDecl(New); 13322 if (II) 13323 IdResolver.AddDecl(New); 13324 13325 ProcessDeclAttributes(S, New, D); 13326 13327 if (D.getDeclSpec().isModulePrivateSpecified()) 13328 Diag(New->getLocation(), diag::err_module_private_local) 13329 << 1 << New->getDeclName() 13330 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13331 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13332 13333 if (New->hasAttr<BlocksAttr>()) { 13334 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13335 } 13336 13337 if (getLangOpts().OpenCL) 13338 deduceOpenCLAddressSpace(New); 13339 13340 return New; 13341 } 13342 13343 /// Synthesizes a variable for a parameter arising from a 13344 /// typedef. 13345 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13346 SourceLocation Loc, 13347 QualType T) { 13348 /* FIXME: setting StartLoc == Loc. 13349 Would it be worth to modify callers so as to provide proper source 13350 location for the unnamed parameters, embedding the parameter's type? */ 13351 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13352 T, Context.getTrivialTypeSourceInfo(T, Loc), 13353 SC_None, nullptr); 13354 Param->setImplicit(); 13355 return Param; 13356 } 13357 13358 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13359 // Don't diagnose unused-parameter errors in template instantiations; we 13360 // will already have done so in the template itself. 13361 if (inTemplateInstantiation()) 13362 return; 13363 13364 for (const ParmVarDecl *Parameter : Parameters) { 13365 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13366 !Parameter->hasAttr<UnusedAttr>()) { 13367 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13368 << Parameter->getDeclName(); 13369 } 13370 } 13371 } 13372 13373 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13374 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13375 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13376 return; 13377 13378 // Warn if the return value is pass-by-value and larger than the specified 13379 // threshold. 13380 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13381 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13382 if (Size > LangOpts.NumLargeByValueCopy) 13383 Diag(D->getLocation(), diag::warn_return_value_size) 13384 << D->getDeclName() << Size; 13385 } 13386 13387 // Warn if any parameter is pass-by-value and larger than the specified 13388 // threshold. 13389 for (const ParmVarDecl *Parameter : Parameters) { 13390 QualType T = Parameter->getType(); 13391 if (T->isDependentType() || !T.isPODType(Context)) 13392 continue; 13393 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13394 if (Size > LangOpts.NumLargeByValueCopy) 13395 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13396 << Parameter->getDeclName() << Size; 13397 } 13398 } 13399 13400 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13401 SourceLocation NameLoc, IdentifierInfo *Name, 13402 QualType T, TypeSourceInfo *TSInfo, 13403 StorageClass SC) { 13404 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13405 if (getLangOpts().ObjCAutoRefCount && 13406 T.getObjCLifetime() == Qualifiers::OCL_None && 13407 T->isObjCLifetimeType()) { 13408 13409 Qualifiers::ObjCLifetime lifetime; 13410 13411 // Special cases for arrays: 13412 // - if it's const, use __unsafe_unretained 13413 // - otherwise, it's an error 13414 if (T->isArrayType()) { 13415 if (!T.isConstQualified()) { 13416 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13417 DelayedDiagnostics.add( 13418 sema::DelayedDiagnostic::makeForbiddenType( 13419 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13420 else 13421 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13422 << TSInfo->getTypeLoc().getSourceRange(); 13423 } 13424 lifetime = Qualifiers::OCL_ExplicitNone; 13425 } else { 13426 lifetime = T->getObjCARCImplicitLifetime(); 13427 } 13428 T = Context.getLifetimeQualifiedType(T, lifetime); 13429 } 13430 13431 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13432 Context.getAdjustedParameterType(T), 13433 TSInfo, SC, nullptr); 13434 13435 // Make a note if we created a new pack in the scope of a lambda, so that 13436 // we know that references to that pack must also be expanded within the 13437 // lambda scope. 13438 if (New->isParameterPack()) 13439 if (auto *LSI = getEnclosingLambda()) 13440 LSI->LocalPacks.push_back(New); 13441 13442 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13443 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13444 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13445 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13446 13447 // Parameters can not be abstract class types. 13448 // For record types, this is done by the AbstractClassUsageDiagnoser once 13449 // the class has been completely parsed. 13450 if (!CurContext->isRecord() && 13451 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13452 AbstractParamType)) 13453 New->setInvalidDecl(); 13454 13455 // Parameter declarators cannot be interface types. All ObjC objects are 13456 // passed by reference. 13457 if (T->isObjCObjectType()) { 13458 SourceLocation TypeEndLoc = 13459 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13460 Diag(NameLoc, 13461 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13462 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13463 T = Context.getObjCObjectPointerType(T); 13464 New->setType(T); 13465 } 13466 13467 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13468 // duration shall not be qualified by an address-space qualifier." 13469 // Since all parameters have automatic store duration, they can not have 13470 // an address space. 13471 if (T.getAddressSpace() != LangAS::Default && 13472 // OpenCL allows function arguments declared to be an array of a type 13473 // to be qualified with an address space. 13474 !(getLangOpts().OpenCL && 13475 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13476 Diag(NameLoc, diag::err_arg_with_address_space); 13477 New->setInvalidDecl(); 13478 } 13479 13480 return New; 13481 } 13482 13483 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13484 SourceLocation LocAfterDecls) { 13485 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13486 13487 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13488 // for a K&R function. 13489 if (!FTI.hasPrototype) { 13490 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13491 --i; 13492 if (FTI.Params[i].Param == nullptr) { 13493 SmallString<256> Code; 13494 llvm::raw_svector_ostream(Code) 13495 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13496 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13497 << FTI.Params[i].Ident 13498 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13499 13500 // Implicitly declare the argument as type 'int' for lack of a better 13501 // type. 13502 AttributeFactory attrs; 13503 DeclSpec DS(attrs); 13504 const char* PrevSpec; // unused 13505 unsigned DiagID; // unused 13506 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13507 DiagID, Context.getPrintingPolicy()); 13508 // Use the identifier location for the type source range. 13509 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13510 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13511 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13512 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13513 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13514 } 13515 } 13516 } 13517 } 13518 13519 Decl * 13520 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13521 MultiTemplateParamsArg TemplateParameterLists, 13522 SkipBodyInfo *SkipBody) { 13523 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13524 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13525 Scope *ParentScope = FnBodyScope->getParent(); 13526 13527 D.setFunctionDefinitionKind(FDK_Definition); 13528 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13529 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13530 } 13531 13532 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13533 Consumer.HandleInlineFunctionDefinition(D); 13534 } 13535 13536 static bool 13537 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13538 const FunctionDecl *&PossiblePrototype) { 13539 // Don't warn about invalid declarations. 13540 if (FD->isInvalidDecl()) 13541 return false; 13542 13543 // Or declarations that aren't global. 13544 if (!FD->isGlobal()) 13545 return false; 13546 13547 // Don't warn about C++ member functions. 13548 if (isa<CXXMethodDecl>(FD)) 13549 return false; 13550 13551 // Don't warn about 'main'. 13552 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13553 if (IdentifierInfo *II = FD->getIdentifier()) 13554 if (II->isStr("main")) 13555 return false; 13556 13557 // Don't warn about inline functions. 13558 if (FD->isInlined()) 13559 return false; 13560 13561 // Don't warn about function templates. 13562 if (FD->getDescribedFunctionTemplate()) 13563 return false; 13564 13565 // Don't warn about function template specializations. 13566 if (FD->isFunctionTemplateSpecialization()) 13567 return false; 13568 13569 // Don't warn for OpenCL kernels. 13570 if (FD->hasAttr<OpenCLKernelAttr>()) 13571 return false; 13572 13573 // Don't warn on explicitly deleted functions. 13574 if (FD->isDeleted()) 13575 return false; 13576 13577 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13578 Prev; Prev = Prev->getPreviousDecl()) { 13579 // Ignore any declarations that occur in function or method 13580 // scope, because they aren't visible from the header. 13581 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13582 continue; 13583 13584 PossiblePrototype = Prev; 13585 return Prev->getType()->isFunctionNoProtoType(); 13586 } 13587 13588 return true; 13589 } 13590 13591 void 13592 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13593 const FunctionDecl *EffectiveDefinition, 13594 SkipBodyInfo *SkipBody) { 13595 const FunctionDecl *Definition = EffectiveDefinition; 13596 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13597 // If this is a friend function defined in a class template, it does not 13598 // have a body until it is used, nevertheless it is a definition, see 13599 // [temp.inst]p2: 13600 // 13601 // ... for the purpose of determining whether an instantiated redeclaration 13602 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13603 // corresponds to a definition in the template is considered to be a 13604 // definition. 13605 // 13606 // The following code must produce redefinition error: 13607 // 13608 // template<typename T> struct C20 { friend void func_20() {} }; 13609 // C20<int> c20i; 13610 // void func_20() {} 13611 // 13612 for (auto I : FD->redecls()) { 13613 if (I != FD && !I->isInvalidDecl() && 13614 I->getFriendObjectKind() != Decl::FOK_None) { 13615 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13616 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13617 // A merged copy of the same function, instantiated as a member of 13618 // the same class, is OK. 13619 if (declaresSameEntity(OrigFD, Original) && 13620 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13621 cast<Decl>(FD->getLexicalDeclContext()))) 13622 continue; 13623 } 13624 13625 if (Original->isThisDeclarationADefinition()) { 13626 Definition = I; 13627 break; 13628 } 13629 } 13630 } 13631 } 13632 } 13633 13634 if (!Definition) 13635 // Similar to friend functions a friend function template may be a 13636 // definition and do not have a body if it is instantiated in a class 13637 // template. 13638 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13639 for (auto I : FTD->redecls()) { 13640 auto D = cast<FunctionTemplateDecl>(I); 13641 if (D != FTD) { 13642 assert(!D->isThisDeclarationADefinition() && 13643 "More than one definition in redeclaration chain"); 13644 if (D->getFriendObjectKind() != Decl::FOK_None) 13645 if (FunctionTemplateDecl *FT = 13646 D->getInstantiatedFromMemberTemplate()) { 13647 if (FT->isThisDeclarationADefinition()) { 13648 Definition = D->getTemplatedDecl(); 13649 break; 13650 } 13651 } 13652 } 13653 } 13654 } 13655 13656 if (!Definition) 13657 return; 13658 13659 if (canRedefineFunction(Definition, getLangOpts())) 13660 return; 13661 13662 // Don't emit an error when this is redefinition of a typo-corrected 13663 // definition. 13664 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13665 return; 13666 13667 // If we don't have a visible definition of the function, and it's inline or 13668 // a template, skip the new definition. 13669 if (SkipBody && !hasVisibleDefinition(Definition) && 13670 (Definition->getFormalLinkage() == InternalLinkage || 13671 Definition->isInlined() || 13672 Definition->getDescribedFunctionTemplate() || 13673 Definition->getNumTemplateParameterLists())) { 13674 SkipBody->ShouldSkip = true; 13675 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13676 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13677 makeMergedDefinitionVisible(TD); 13678 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13679 return; 13680 } 13681 13682 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13683 Definition->getStorageClass() == SC_Extern) 13684 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13685 << FD->getDeclName() << getLangOpts().CPlusPlus; 13686 else 13687 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13688 13689 Diag(Definition->getLocation(), diag::note_previous_definition); 13690 FD->setInvalidDecl(); 13691 } 13692 13693 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13694 Sema &S) { 13695 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13696 13697 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13698 LSI->CallOperator = CallOperator; 13699 LSI->Lambda = LambdaClass; 13700 LSI->ReturnType = CallOperator->getReturnType(); 13701 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13702 13703 if (LCD == LCD_None) 13704 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13705 else if (LCD == LCD_ByCopy) 13706 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13707 else if (LCD == LCD_ByRef) 13708 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13709 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13710 13711 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13712 LSI->Mutable = !CallOperator->isConst(); 13713 13714 // Add the captures to the LSI so they can be noted as already 13715 // captured within tryCaptureVar. 13716 auto I = LambdaClass->field_begin(); 13717 for (const auto &C : LambdaClass->captures()) { 13718 if (C.capturesVariable()) { 13719 VarDecl *VD = C.getCapturedVar(); 13720 if (VD->isInitCapture()) 13721 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13722 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13723 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13724 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13725 /*EllipsisLoc*/C.isPackExpansion() 13726 ? C.getEllipsisLoc() : SourceLocation(), 13727 I->getType(), /*Invalid*/false); 13728 13729 } else if (C.capturesThis()) { 13730 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13731 C.getCaptureKind() == LCK_StarThis); 13732 } else { 13733 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13734 I->getType()); 13735 } 13736 ++I; 13737 } 13738 } 13739 13740 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13741 SkipBodyInfo *SkipBody) { 13742 if (!D) { 13743 // Parsing the function declaration failed in some way. Push on a fake scope 13744 // anyway so we can try to parse the function body. 13745 PushFunctionScope(); 13746 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13747 return D; 13748 } 13749 13750 FunctionDecl *FD = nullptr; 13751 13752 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13753 FD = FunTmpl->getTemplatedDecl(); 13754 else 13755 FD = cast<FunctionDecl>(D); 13756 13757 // Do not push if it is a lambda because one is already pushed when building 13758 // the lambda in ActOnStartOfLambdaDefinition(). 13759 if (!isLambdaCallOperator(FD)) 13760 PushExpressionEvaluationContext( 13761 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13762 : ExprEvalContexts.back().Context); 13763 13764 // Check for defining attributes before the check for redefinition. 13765 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13766 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13767 FD->dropAttr<AliasAttr>(); 13768 FD->setInvalidDecl(); 13769 } 13770 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13771 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13772 FD->dropAttr<IFuncAttr>(); 13773 FD->setInvalidDecl(); 13774 } 13775 13776 // See if this is a redefinition. If 'will have body' is already set, then 13777 // these checks were already performed when it was set. 13778 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13779 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13780 13781 // If we're skipping the body, we're done. Don't enter the scope. 13782 if (SkipBody && SkipBody->ShouldSkip) 13783 return D; 13784 } 13785 13786 // Mark this function as "will have a body eventually". This lets users to 13787 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13788 // this function. 13789 FD->setWillHaveBody(); 13790 13791 // If we are instantiating a generic lambda call operator, push 13792 // a LambdaScopeInfo onto the function stack. But use the information 13793 // that's already been calculated (ActOnLambdaExpr) to prime the current 13794 // LambdaScopeInfo. 13795 // When the template operator is being specialized, the LambdaScopeInfo, 13796 // has to be properly restored so that tryCaptureVariable doesn't try 13797 // and capture any new variables. In addition when calculating potential 13798 // captures during transformation of nested lambdas, it is necessary to 13799 // have the LSI properly restored. 13800 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13801 assert(inTemplateInstantiation() && 13802 "There should be an active template instantiation on the stack " 13803 "when instantiating a generic lambda!"); 13804 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13805 } else { 13806 // Enter a new function scope 13807 PushFunctionScope(); 13808 } 13809 13810 // Builtin functions cannot be defined. 13811 if (unsigned BuiltinID = FD->getBuiltinID()) { 13812 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13813 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13814 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13815 FD->setInvalidDecl(); 13816 } 13817 } 13818 13819 // The return type of a function definition must be complete 13820 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13821 QualType ResultType = FD->getReturnType(); 13822 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13823 !FD->isInvalidDecl() && 13824 RequireCompleteType(FD->getLocation(), ResultType, 13825 diag::err_func_def_incomplete_result)) 13826 FD->setInvalidDecl(); 13827 13828 if (FnBodyScope) 13829 PushDeclContext(FnBodyScope, FD); 13830 13831 // Check the validity of our function parameters 13832 CheckParmsForFunctionDef(FD->parameters(), 13833 /*CheckParameterNames=*/true); 13834 13835 // Add non-parameter declarations already in the function to the current 13836 // scope. 13837 if (FnBodyScope) { 13838 for (Decl *NPD : FD->decls()) { 13839 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13840 if (!NonParmDecl) 13841 continue; 13842 assert(!isa<ParmVarDecl>(NonParmDecl) && 13843 "parameters should not be in newly created FD yet"); 13844 13845 // If the decl has a name, make it accessible in the current scope. 13846 if (NonParmDecl->getDeclName()) 13847 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13848 13849 // Similarly, dive into enums and fish their constants out, making them 13850 // accessible in this scope. 13851 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13852 for (auto *EI : ED->enumerators()) 13853 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13854 } 13855 } 13856 } 13857 13858 // Introduce our parameters into the function scope 13859 for (auto Param : FD->parameters()) { 13860 Param->setOwningFunction(FD); 13861 13862 // If this has an identifier, add it to the scope stack. 13863 if (Param->getIdentifier() && FnBodyScope) { 13864 CheckShadow(FnBodyScope, Param); 13865 13866 PushOnScopeChains(Param, FnBodyScope); 13867 } 13868 } 13869 13870 // Ensure that the function's exception specification is instantiated. 13871 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13872 ResolveExceptionSpec(D->getLocation(), FPT); 13873 13874 // dllimport cannot be applied to non-inline function definitions. 13875 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13876 !FD->isTemplateInstantiation()) { 13877 assert(!FD->hasAttr<DLLExportAttr>()); 13878 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13879 FD->setInvalidDecl(); 13880 return D; 13881 } 13882 // We want to attach documentation to original Decl (which might be 13883 // a function template). 13884 ActOnDocumentableDecl(D); 13885 if (getCurLexicalContext()->isObjCContainer() && 13886 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13887 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13888 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13889 13890 return D; 13891 } 13892 13893 /// Given the set of return statements within a function body, 13894 /// compute the variables that are subject to the named return value 13895 /// optimization. 13896 /// 13897 /// Each of the variables that is subject to the named return value 13898 /// optimization will be marked as NRVO variables in the AST, and any 13899 /// return statement that has a marked NRVO variable as its NRVO candidate can 13900 /// use the named return value optimization. 13901 /// 13902 /// This function applies a very simplistic algorithm for NRVO: if every return 13903 /// statement in the scope of a variable has the same NRVO candidate, that 13904 /// candidate is an NRVO variable. 13905 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13906 ReturnStmt **Returns = Scope->Returns.data(); 13907 13908 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13909 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13910 if (!NRVOCandidate->isNRVOVariable()) 13911 Returns[I]->setNRVOCandidate(nullptr); 13912 } 13913 } 13914 } 13915 13916 bool Sema::canDelayFunctionBody(const Declarator &D) { 13917 // We can't delay parsing the body of a constexpr function template (yet). 13918 if (D.getDeclSpec().hasConstexprSpecifier()) 13919 return false; 13920 13921 // We can't delay parsing the body of a function template with a deduced 13922 // return type (yet). 13923 if (D.getDeclSpec().hasAutoTypeSpec()) { 13924 // If the placeholder introduces a non-deduced trailing return type, 13925 // we can still delay parsing it. 13926 if (D.getNumTypeObjects()) { 13927 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13928 if (Outer.Kind == DeclaratorChunk::Function && 13929 Outer.Fun.hasTrailingReturnType()) { 13930 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13931 return Ty.isNull() || !Ty->isUndeducedType(); 13932 } 13933 } 13934 return false; 13935 } 13936 13937 return true; 13938 } 13939 13940 bool Sema::canSkipFunctionBody(Decl *D) { 13941 // We cannot skip the body of a function (or function template) which is 13942 // constexpr, since we may need to evaluate its body in order to parse the 13943 // rest of the file. 13944 // We cannot skip the body of a function with an undeduced return type, 13945 // because any callers of that function need to know the type. 13946 if (const FunctionDecl *FD = D->getAsFunction()) { 13947 if (FD->isConstexpr()) 13948 return false; 13949 // We can't simply call Type::isUndeducedType here, because inside template 13950 // auto can be deduced to a dependent type, which is not considered 13951 // "undeduced". 13952 if (FD->getReturnType()->getContainedDeducedType()) 13953 return false; 13954 } 13955 return Consumer.shouldSkipFunctionBody(D); 13956 } 13957 13958 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13959 if (!Decl) 13960 return nullptr; 13961 if (FunctionDecl *FD = Decl->getAsFunction()) 13962 FD->setHasSkippedBody(); 13963 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13964 MD->setHasSkippedBody(); 13965 return Decl; 13966 } 13967 13968 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13969 return ActOnFinishFunctionBody(D, BodyArg, false); 13970 } 13971 13972 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13973 /// body. 13974 class ExitFunctionBodyRAII { 13975 public: 13976 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13977 ~ExitFunctionBodyRAII() { 13978 if (!IsLambda) 13979 S.PopExpressionEvaluationContext(); 13980 } 13981 13982 private: 13983 Sema &S; 13984 bool IsLambda = false; 13985 }; 13986 13987 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13988 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13989 13990 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13991 if (EscapeInfo.count(BD)) 13992 return EscapeInfo[BD]; 13993 13994 bool R = false; 13995 const BlockDecl *CurBD = BD; 13996 13997 do { 13998 R = !CurBD->doesNotEscape(); 13999 if (R) 14000 break; 14001 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14002 } while (CurBD); 14003 14004 return EscapeInfo[BD] = R; 14005 }; 14006 14007 // If the location where 'self' is implicitly retained is inside a escaping 14008 // block, emit a diagnostic. 14009 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14010 S.ImplicitlyRetainedSelfLocs) 14011 if (IsOrNestedInEscapingBlock(P.second)) 14012 S.Diag(P.first, diag::warn_implicitly_retains_self) 14013 << FixItHint::CreateInsertion(P.first, "self->"); 14014 } 14015 14016 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14017 bool IsInstantiation) { 14018 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14019 14020 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14021 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14022 14023 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14024 CheckCompletedCoroutineBody(FD, Body); 14025 14026 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14027 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14028 // meant to pop the context added in ActOnStartOfFunctionDef(). 14029 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14030 14031 if (FD) { 14032 FD->setBody(Body); 14033 FD->setWillHaveBody(false); 14034 14035 if (getLangOpts().CPlusPlus14) { 14036 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14037 FD->getReturnType()->isUndeducedType()) { 14038 // If the function has a deduced result type but contains no 'return' 14039 // statements, the result type as written must be exactly 'auto', and 14040 // the deduced result type is 'void'. 14041 if (!FD->getReturnType()->getAs<AutoType>()) { 14042 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14043 << FD->getReturnType(); 14044 FD->setInvalidDecl(); 14045 } else { 14046 // Substitute 'void' for the 'auto' in the type. 14047 TypeLoc ResultType = getReturnTypeLoc(FD); 14048 Context.adjustDeducedFunctionResultType( 14049 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14050 } 14051 } 14052 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14053 // In C++11, we don't use 'auto' deduction rules for lambda call 14054 // operators because we don't support return type deduction. 14055 auto *LSI = getCurLambda(); 14056 if (LSI->HasImplicitReturnType) { 14057 deduceClosureReturnType(*LSI); 14058 14059 // C++11 [expr.prim.lambda]p4: 14060 // [...] if there are no return statements in the compound-statement 14061 // [the deduced type is] the type void 14062 QualType RetType = 14063 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14064 14065 // Update the return type to the deduced type. 14066 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14067 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14068 Proto->getExtProtoInfo())); 14069 } 14070 } 14071 14072 // If the function implicitly returns zero (like 'main') or is naked, 14073 // don't complain about missing return statements. 14074 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14075 WP.disableCheckFallThrough(); 14076 14077 // MSVC permits the use of pure specifier (=0) on function definition, 14078 // defined at class scope, warn about this non-standard construct. 14079 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14080 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14081 14082 if (!FD->isInvalidDecl()) { 14083 // Don't diagnose unused parameters of defaulted or deleted functions. 14084 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14085 DiagnoseUnusedParameters(FD->parameters()); 14086 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14087 FD->getReturnType(), FD); 14088 14089 // If this is a structor, we need a vtable. 14090 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14091 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14092 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14093 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14094 14095 // Try to apply the named return value optimization. We have to check 14096 // if we can do this here because lambdas keep return statements around 14097 // to deduce an implicit return type. 14098 if (FD->getReturnType()->isRecordType() && 14099 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14100 computeNRVO(Body, getCurFunction()); 14101 } 14102 14103 // GNU warning -Wmissing-prototypes: 14104 // Warn if a global function is defined without a previous 14105 // prototype declaration. This warning is issued even if the 14106 // definition itself provides a prototype. The aim is to detect 14107 // global functions that fail to be declared in header files. 14108 const FunctionDecl *PossiblePrototype = nullptr; 14109 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14110 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14111 14112 if (PossiblePrototype) { 14113 // We found a declaration that is not a prototype, 14114 // but that could be a zero-parameter prototype 14115 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14116 TypeLoc TL = TI->getTypeLoc(); 14117 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14118 Diag(PossiblePrototype->getLocation(), 14119 diag::note_declaration_not_a_prototype) 14120 << (FD->getNumParams() != 0) 14121 << (FD->getNumParams() == 0 14122 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14123 : FixItHint{}); 14124 } 14125 } else { 14126 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14127 << /* function */ 1 14128 << (FD->getStorageClass() == SC_None 14129 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14130 "static ") 14131 : FixItHint{}); 14132 } 14133 14134 // GNU warning -Wstrict-prototypes 14135 // Warn if K&R function is defined without a previous declaration. 14136 // This warning is issued only if the definition itself does not provide 14137 // a prototype. Only K&R definitions do not provide a prototype. 14138 if (!FD->hasWrittenPrototype()) { 14139 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14140 TypeLoc TL = TI->getTypeLoc(); 14141 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14142 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14143 } 14144 } 14145 14146 // Warn on CPUDispatch with an actual body. 14147 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14148 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14149 if (!CmpndBody->body_empty()) 14150 Diag(CmpndBody->body_front()->getBeginLoc(), 14151 diag::warn_dispatch_body_ignored); 14152 14153 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14154 const CXXMethodDecl *KeyFunction; 14155 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14156 MD->isVirtual() && 14157 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14158 MD == KeyFunction->getCanonicalDecl()) { 14159 // Update the key-function state if necessary for this ABI. 14160 if (FD->isInlined() && 14161 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14162 Context.setNonKeyFunction(MD); 14163 14164 // If the newly-chosen key function is already defined, then we 14165 // need to mark the vtable as used retroactively. 14166 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14167 const FunctionDecl *Definition; 14168 if (KeyFunction && KeyFunction->isDefined(Definition)) 14169 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14170 } else { 14171 // We just defined they key function; mark the vtable as used. 14172 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14173 } 14174 } 14175 } 14176 14177 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14178 "Function parsing confused"); 14179 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14180 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14181 MD->setBody(Body); 14182 if (!MD->isInvalidDecl()) { 14183 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14184 MD->getReturnType(), MD); 14185 14186 if (Body) 14187 computeNRVO(Body, getCurFunction()); 14188 } 14189 if (getCurFunction()->ObjCShouldCallSuper) { 14190 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14191 << MD->getSelector().getAsString(); 14192 getCurFunction()->ObjCShouldCallSuper = false; 14193 } 14194 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14195 const ObjCMethodDecl *InitMethod = nullptr; 14196 bool isDesignated = 14197 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14198 assert(isDesignated && InitMethod); 14199 (void)isDesignated; 14200 14201 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14202 auto IFace = MD->getClassInterface(); 14203 if (!IFace) 14204 return false; 14205 auto SuperD = IFace->getSuperClass(); 14206 if (!SuperD) 14207 return false; 14208 return SuperD->getIdentifier() == 14209 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14210 }; 14211 // Don't issue this warning for unavailable inits or direct subclasses 14212 // of NSObject. 14213 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14214 Diag(MD->getLocation(), 14215 diag::warn_objc_designated_init_missing_super_call); 14216 Diag(InitMethod->getLocation(), 14217 diag::note_objc_designated_init_marked_here); 14218 } 14219 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14220 } 14221 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14222 // Don't issue this warning for unavaialable inits. 14223 if (!MD->isUnavailable()) 14224 Diag(MD->getLocation(), 14225 diag::warn_objc_secondary_init_missing_init_call); 14226 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14227 } 14228 14229 diagnoseImplicitlyRetainedSelf(*this); 14230 } else { 14231 // Parsing the function declaration failed in some way. Pop the fake scope 14232 // we pushed on. 14233 PopFunctionScopeInfo(ActivePolicy, dcl); 14234 return nullptr; 14235 } 14236 14237 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14238 DiagnoseUnguardedAvailabilityViolations(dcl); 14239 14240 assert(!getCurFunction()->ObjCShouldCallSuper && 14241 "This should only be set for ObjC methods, which should have been " 14242 "handled in the block above."); 14243 14244 // Verify and clean out per-function state. 14245 if (Body && (!FD || !FD->isDefaulted())) { 14246 // C++ constructors that have function-try-blocks can't have return 14247 // statements in the handlers of that block. (C++ [except.handle]p14) 14248 // Verify this. 14249 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14250 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14251 14252 // Verify that gotos and switch cases don't jump into scopes illegally. 14253 if (getCurFunction()->NeedsScopeChecking() && 14254 !PP.isCodeCompletionEnabled()) 14255 DiagnoseInvalidJumps(Body); 14256 14257 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14258 if (!Destructor->getParent()->isDependentType()) 14259 CheckDestructor(Destructor); 14260 14261 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14262 Destructor->getParent()); 14263 } 14264 14265 // If any errors have occurred, clear out any temporaries that may have 14266 // been leftover. This ensures that these temporaries won't be picked up for 14267 // deletion in some later function. 14268 if (getDiagnostics().hasErrorOccurred() || 14269 getDiagnostics().getSuppressAllDiagnostics()) { 14270 DiscardCleanupsInEvaluationContext(); 14271 } 14272 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14273 !isa<FunctionTemplateDecl>(dcl)) { 14274 // Since the body is valid, issue any analysis-based warnings that are 14275 // enabled. 14276 ActivePolicy = &WP; 14277 } 14278 14279 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14280 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14281 FD->setInvalidDecl(); 14282 14283 if (FD && FD->hasAttr<NakedAttr>()) { 14284 for (const Stmt *S : Body->children()) { 14285 // Allow local register variables without initializer as they don't 14286 // require prologue. 14287 bool RegisterVariables = false; 14288 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14289 for (const auto *Decl : DS->decls()) { 14290 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14291 RegisterVariables = 14292 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14293 if (!RegisterVariables) 14294 break; 14295 } 14296 } 14297 } 14298 if (RegisterVariables) 14299 continue; 14300 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14301 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14302 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14303 FD->setInvalidDecl(); 14304 break; 14305 } 14306 } 14307 } 14308 14309 assert(ExprCleanupObjects.size() == 14310 ExprEvalContexts.back().NumCleanupObjects && 14311 "Leftover temporaries in function"); 14312 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14313 assert(MaybeODRUseExprs.empty() && 14314 "Leftover expressions for odr-use checking"); 14315 } 14316 14317 if (!IsInstantiation) 14318 PopDeclContext(); 14319 14320 PopFunctionScopeInfo(ActivePolicy, dcl); 14321 // If any errors have occurred, clear out any temporaries that may have 14322 // been leftover. This ensures that these temporaries won't be picked up for 14323 // deletion in some later function. 14324 if (getDiagnostics().hasErrorOccurred()) { 14325 DiscardCleanupsInEvaluationContext(); 14326 } 14327 14328 return dcl; 14329 } 14330 14331 /// When we finish delayed parsing of an attribute, we must attach it to the 14332 /// relevant Decl. 14333 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14334 ParsedAttributes &Attrs) { 14335 // Always attach attributes to the underlying decl. 14336 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14337 D = TD->getTemplatedDecl(); 14338 ProcessDeclAttributeList(S, D, Attrs); 14339 14340 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14341 if (Method->isStatic()) 14342 checkThisInStaticMemberFunctionAttributes(Method); 14343 } 14344 14345 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14346 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14347 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14348 IdentifierInfo &II, Scope *S) { 14349 // Find the scope in which the identifier is injected and the corresponding 14350 // DeclContext. 14351 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14352 // In that case, we inject the declaration into the translation unit scope 14353 // instead. 14354 Scope *BlockScope = S; 14355 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14356 BlockScope = BlockScope->getParent(); 14357 14358 Scope *ContextScope = BlockScope; 14359 while (!ContextScope->getEntity()) 14360 ContextScope = ContextScope->getParent(); 14361 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14362 14363 // Before we produce a declaration for an implicitly defined 14364 // function, see whether there was a locally-scoped declaration of 14365 // this name as a function or variable. If so, use that 14366 // (non-visible) declaration, and complain about it. 14367 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14368 if (ExternCPrev) { 14369 // We still need to inject the function into the enclosing block scope so 14370 // that later (non-call) uses can see it. 14371 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14372 14373 // C89 footnote 38: 14374 // If in fact it is not defined as having type "function returning int", 14375 // the behavior is undefined. 14376 if (!isa<FunctionDecl>(ExternCPrev) || 14377 !Context.typesAreCompatible( 14378 cast<FunctionDecl>(ExternCPrev)->getType(), 14379 Context.getFunctionNoProtoType(Context.IntTy))) { 14380 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14381 << ExternCPrev << !getLangOpts().C99; 14382 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14383 return ExternCPrev; 14384 } 14385 } 14386 14387 // Extension in C99. Legal in C90, but warn about it. 14388 unsigned diag_id; 14389 if (II.getName().startswith("__builtin_")) 14390 diag_id = diag::warn_builtin_unknown; 14391 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14392 else if (getLangOpts().OpenCL) 14393 diag_id = diag::err_opencl_implicit_function_decl; 14394 else if (getLangOpts().C99) 14395 diag_id = diag::ext_implicit_function_decl; 14396 else 14397 diag_id = diag::warn_implicit_function_decl; 14398 Diag(Loc, diag_id) << &II; 14399 14400 // If we found a prior declaration of this function, don't bother building 14401 // another one. We've already pushed that one into scope, so there's nothing 14402 // more to do. 14403 if (ExternCPrev) 14404 return ExternCPrev; 14405 14406 // Because typo correction is expensive, only do it if the implicit 14407 // function declaration is going to be treated as an error. 14408 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14409 TypoCorrection Corrected; 14410 DeclFilterCCC<FunctionDecl> CCC{}; 14411 if (S && (Corrected = 14412 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14413 S, nullptr, CCC, CTK_NonError))) 14414 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14415 /*ErrorRecovery*/false); 14416 } 14417 14418 // Set a Declarator for the implicit definition: int foo(); 14419 const char *Dummy; 14420 AttributeFactory attrFactory; 14421 DeclSpec DS(attrFactory); 14422 unsigned DiagID; 14423 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14424 Context.getPrintingPolicy()); 14425 (void)Error; // Silence warning. 14426 assert(!Error && "Error setting up implicit decl!"); 14427 SourceLocation NoLoc; 14428 Declarator D(DS, DeclaratorContext::BlockContext); 14429 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14430 /*IsAmbiguous=*/false, 14431 /*LParenLoc=*/NoLoc, 14432 /*Params=*/nullptr, 14433 /*NumParams=*/0, 14434 /*EllipsisLoc=*/NoLoc, 14435 /*RParenLoc=*/NoLoc, 14436 /*RefQualifierIsLvalueRef=*/true, 14437 /*RefQualifierLoc=*/NoLoc, 14438 /*MutableLoc=*/NoLoc, EST_None, 14439 /*ESpecRange=*/SourceRange(), 14440 /*Exceptions=*/nullptr, 14441 /*ExceptionRanges=*/nullptr, 14442 /*NumExceptions=*/0, 14443 /*NoexceptExpr=*/nullptr, 14444 /*ExceptionSpecTokens=*/nullptr, 14445 /*DeclsInPrototype=*/None, Loc, 14446 Loc, D), 14447 std::move(DS.getAttributes()), SourceLocation()); 14448 D.SetIdentifier(&II, Loc); 14449 14450 // Insert this function into the enclosing block scope. 14451 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14452 FD->setImplicit(); 14453 14454 AddKnownFunctionAttributes(FD); 14455 14456 return FD; 14457 } 14458 14459 /// If this function is a C++ replaceable global allocation function 14460 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14461 /// adds any function attributes that we know a priori based on the standard. 14462 /// 14463 /// We need to check for duplicate attributes both here and where user-written 14464 /// attributes are applied to declarations. 14465 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14466 FunctionDecl *FD) { 14467 if (FD->isInvalidDecl()) 14468 return; 14469 14470 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14471 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14472 return; 14473 14474 Optional<unsigned> AlignmentParam; 14475 bool IsNothrow = false; 14476 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14477 return; 14478 14479 // C++2a [basic.stc.dynamic.allocation]p4: 14480 // An allocation function that has a non-throwing exception specification 14481 // indicates failure by returning a null pointer value. Any other allocation 14482 // function never returns a null pointer value and indicates failure only by 14483 // throwing an exception [...] 14484 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14485 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14486 14487 // C++2a [basic.stc.dynamic.allocation]p2: 14488 // An allocation function attempts to allocate the requested amount of 14489 // storage. [...] If the request succeeds, the value returned by a 14490 // replaceable allocation function is a [...] pointer value p0 different 14491 // from any previously returned value p1 [...] 14492 // 14493 // However, this particular information is being added in codegen, 14494 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14495 14496 // C++2a [basic.stc.dynamic.allocation]p2: 14497 // An allocation function attempts to allocate the requested amount of 14498 // storage. If it is successful, it returns the address of the start of a 14499 // block of storage whose length in bytes is at least as large as the 14500 // requested size. 14501 if (!FD->hasAttr<AllocSizeAttr>()) { 14502 FD->addAttr(AllocSizeAttr::CreateImplicit( 14503 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14504 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14505 } 14506 14507 // C++2a [basic.stc.dynamic.allocation]p3: 14508 // For an allocation function [...], the pointer returned on a successful 14509 // call shall represent the address of storage that is aligned as follows: 14510 // (3.1) If the allocation function takes an argument of type 14511 // std::align_val_t, the storage will have the alignment 14512 // specified by the value of this argument. 14513 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14514 FD->addAttr(AllocAlignAttr::CreateImplicit( 14515 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14516 } 14517 14518 // FIXME: 14519 // C++2a [basic.stc.dynamic.allocation]p3: 14520 // For an allocation function [...], the pointer returned on a successful 14521 // call shall represent the address of storage that is aligned as follows: 14522 // (3.2) Otherwise, if the allocation function is named operator new[], 14523 // the storage is aligned for any object that does not have 14524 // new-extended alignment ([basic.align]) and is no larger than the 14525 // requested size. 14526 // (3.3) Otherwise, the storage is aligned for any object that does not 14527 // have new-extended alignment and is of the requested size. 14528 } 14529 14530 /// Adds any function attributes that we know a priori based on 14531 /// the declaration of this function. 14532 /// 14533 /// These attributes can apply both to implicitly-declared builtins 14534 /// (like __builtin___printf_chk) or to library-declared functions 14535 /// like NSLog or printf. 14536 /// 14537 /// We need to check for duplicate attributes both here and where user-written 14538 /// attributes are applied to declarations. 14539 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14540 if (FD->isInvalidDecl()) 14541 return; 14542 14543 // If this is a built-in function, map its builtin attributes to 14544 // actual attributes. 14545 if (unsigned BuiltinID = FD->getBuiltinID()) { 14546 // Handle printf-formatting attributes. 14547 unsigned FormatIdx; 14548 bool HasVAListArg; 14549 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14550 if (!FD->hasAttr<FormatAttr>()) { 14551 const char *fmt = "printf"; 14552 unsigned int NumParams = FD->getNumParams(); 14553 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14554 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14555 fmt = "NSString"; 14556 FD->addAttr(FormatAttr::CreateImplicit(Context, 14557 &Context.Idents.get(fmt), 14558 FormatIdx+1, 14559 HasVAListArg ? 0 : FormatIdx+2, 14560 FD->getLocation())); 14561 } 14562 } 14563 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14564 HasVAListArg)) { 14565 if (!FD->hasAttr<FormatAttr>()) 14566 FD->addAttr(FormatAttr::CreateImplicit(Context, 14567 &Context.Idents.get("scanf"), 14568 FormatIdx+1, 14569 HasVAListArg ? 0 : FormatIdx+2, 14570 FD->getLocation())); 14571 } 14572 14573 // Handle automatically recognized callbacks. 14574 SmallVector<int, 4> Encoding; 14575 if (!FD->hasAttr<CallbackAttr>() && 14576 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14577 FD->addAttr(CallbackAttr::CreateImplicit( 14578 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14579 14580 // Mark const if we don't care about errno and that is the only thing 14581 // preventing the function from being const. This allows IRgen to use LLVM 14582 // intrinsics for such functions. 14583 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14584 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14585 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14586 14587 // We make "fma" on some platforms const because we know it does not set 14588 // errno in those environments even though it could set errno based on the 14589 // C standard. 14590 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14591 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14592 !FD->hasAttr<ConstAttr>()) { 14593 switch (BuiltinID) { 14594 case Builtin::BI__builtin_fma: 14595 case Builtin::BI__builtin_fmaf: 14596 case Builtin::BI__builtin_fmal: 14597 case Builtin::BIfma: 14598 case Builtin::BIfmaf: 14599 case Builtin::BIfmal: 14600 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14601 break; 14602 default: 14603 break; 14604 } 14605 } 14606 14607 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14608 !FD->hasAttr<ReturnsTwiceAttr>()) 14609 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14610 FD->getLocation())); 14611 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14612 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14613 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14614 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14615 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14616 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14617 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14618 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14619 // Add the appropriate attribute, depending on the CUDA compilation mode 14620 // and which target the builtin belongs to. For example, during host 14621 // compilation, aux builtins are __device__, while the rest are __host__. 14622 if (getLangOpts().CUDAIsDevice != 14623 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14624 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14625 else 14626 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14627 } 14628 } 14629 14630 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14631 14632 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14633 // throw, add an implicit nothrow attribute to any extern "C" function we come 14634 // across. 14635 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14636 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14637 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14638 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14639 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14640 } 14641 14642 IdentifierInfo *Name = FD->getIdentifier(); 14643 if (!Name) 14644 return; 14645 if ((!getLangOpts().CPlusPlus && 14646 FD->getDeclContext()->isTranslationUnit()) || 14647 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14648 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14649 LinkageSpecDecl::lang_c)) { 14650 // Okay: this could be a libc/libm/Objective-C function we know 14651 // about. 14652 } else 14653 return; 14654 14655 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14656 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14657 // target-specific builtins, perhaps? 14658 if (!FD->hasAttr<FormatAttr>()) 14659 FD->addAttr(FormatAttr::CreateImplicit(Context, 14660 &Context.Idents.get("printf"), 2, 14661 Name->isStr("vasprintf") ? 0 : 3, 14662 FD->getLocation())); 14663 } 14664 14665 if (Name->isStr("__CFStringMakeConstantString")) { 14666 // We already have a __builtin___CFStringMakeConstantString, 14667 // but builds that use -fno-constant-cfstrings don't go through that. 14668 if (!FD->hasAttr<FormatArgAttr>()) 14669 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14670 FD->getLocation())); 14671 } 14672 } 14673 14674 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14675 TypeSourceInfo *TInfo) { 14676 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14677 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14678 14679 if (!TInfo) { 14680 assert(D.isInvalidType() && "no declarator info for valid type"); 14681 TInfo = Context.getTrivialTypeSourceInfo(T); 14682 } 14683 14684 // Scope manipulation handled by caller. 14685 TypedefDecl *NewTD = 14686 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14687 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14688 14689 // Bail out immediately if we have an invalid declaration. 14690 if (D.isInvalidType()) { 14691 NewTD->setInvalidDecl(); 14692 return NewTD; 14693 } 14694 14695 if (D.getDeclSpec().isModulePrivateSpecified()) { 14696 if (CurContext->isFunctionOrMethod()) 14697 Diag(NewTD->getLocation(), diag::err_module_private_local) 14698 << 2 << NewTD->getDeclName() 14699 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14700 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14701 else 14702 NewTD->setModulePrivate(); 14703 } 14704 14705 // C++ [dcl.typedef]p8: 14706 // If the typedef declaration defines an unnamed class (or 14707 // enum), the first typedef-name declared by the declaration 14708 // to be that class type (or enum type) is used to denote the 14709 // class type (or enum type) for linkage purposes only. 14710 // We need to check whether the type was declared in the declaration. 14711 switch (D.getDeclSpec().getTypeSpecType()) { 14712 case TST_enum: 14713 case TST_struct: 14714 case TST_interface: 14715 case TST_union: 14716 case TST_class: { 14717 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14718 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14719 break; 14720 } 14721 14722 default: 14723 break; 14724 } 14725 14726 return NewTD; 14727 } 14728 14729 /// Check that this is a valid underlying type for an enum declaration. 14730 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14731 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14732 QualType T = TI->getType(); 14733 14734 if (T->isDependentType()) 14735 return false; 14736 14737 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14738 if (BT->isInteger()) 14739 return false; 14740 14741 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14742 return true; 14743 } 14744 14745 /// Check whether this is a valid redeclaration of a previous enumeration. 14746 /// \return true if the redeclaration was invalid. 14747 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14748 QualType EnumUnderlyingTy, bool IsFixed, 14749 const EnumDecl *Prev) { 14750 if (IsScoped != Prev->isScoped()) { 14751 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14752 << Prev->isScoped(); 14753 Diag(Prev->getLocation(), diag::note_previous_declaration); 14754 return true; 14755 } 14756 14757 if (IsFixed && Prev->isFixed()) { 14758 if (!EnumUnderlyingTy->isDependentType() && 14759 !Prev->getIntegerType()->isDependentType() && 14760 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14761 Prev->getIntegerType())) { 14762 // TODO: Highlight the underlying type of the redeclaration. 14763 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14764 << EnumUnderlyingTy << Prev->getIntegerType(); 14765 Diag(Prev->getLocation(), diag::note_previous_declaration) 14766 << Prev->getIntegerTypeRange(); 14767 return true; 14768 } 14769 } else if (IsFixed != Prev->isFixed()) { 14770 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14771 << Prev->isFixed(); 14772 Diag(Prev->getLocation(), diag::note_previous_declaration); 14773 return true; 14774 } 14775 14776 return false; 14777 } 14778 14779 /// Get diagnostic %select index for tag kind for 14780 /// redeclaration diagnostic message. 14781 /// WARNING: Indexes apply to particular diagnostics only! 14782 /// 14783 /// \returns diagnostic %select index. 14784 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14785 switch (Tag) { 14786 case TTK_Struct: return 0; 14787 case TTK_Interface: return 1; 14788 case TTK_Class: return 2; 14789 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14790 } 14791 } 14792 14793 /// Determine if tag kind is a class-key compatible with 14794 /// class for redeclaration (class, struct, or __interface). 14795 /// 14796 /// \returns true iff the tag kind is compatible. 14797 static bool isClassCompatTagKind(TagTypeKind Tag) 14798 { 14799 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14800 } 14801 14802 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14803 TagTypeKind TTK) { 14804 if (isa<TypedefDecl>(PrevDecl)) 14805 return NTK_Typedef; 14806 else if (isa<TypeAliasDecl>(PrevDecl)) 14807 return NTK_TypeAlias; 14808 else if (isa<ClassTemplateDecl>(PrevDecl)) 14809 return NTK_Template; 14810 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14811 return NTK_TypeAliasTemplate; 14812 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14813 return NTK_TemplateTemplateArgument; 14814 switch (TTK) { 14815 case TTK_Struct: 14816 case TTK_Interface: 14817 case TTK_Class: 14818 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14819 case TTK_Union: 14820 return NTK_NonUnion; 14821 case TTK_Enum: 14822 return NTK_NonEnum; 14823 } 14824 llvm_unreachable("invalid TTK"); 14825 } 14826 14827 /// Determine whether a tag with a given kind is acceptable 14828 /// as a redeclaration of the given tag declaration. 14829 /// 14830 /// \returns true if the new tag kind is acceptable, false otherwise. 14831 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14832 TagTypeKind NewTag, bool isDefinition, 14833 SourceLocation NewTagLoc, 14834 const IdentifierInfo *Name) { 14835 // C++ [dcl.type.elab]p3: 14836 // The class-key or enum keyword present in the 14837 // elaborated-type-specifier shall agree in kind with the 14838 // declaration to which the name in the elaborated-type-specifier 14839 // refers. This rule also applies to the form of 14840 // elaborated-type-specifier that declares a class-name or 14841 // friend class since it can be construed as referring to the 14842 // definition of the class. Thus, in any 14843 // elaborated-type-specifier, the enum keyword shall be used to 14844 // refer to an enumeration (7.2), the union class-key shall be 14845 // used to refer to a union (clause 9), and either the class or 14846 // struct class-key shall be used to refer to a class (clause 9) 14847 // declared using the class or struct class-key. 14848 TagTypeKind OldTag = Previous->getTagKind(); 14849 if (OldTag != NewTag && 14850 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14851 return false; 14852 14853 // Tags are compatible, but we might still want to warn on mismatched tags. 14854 // Non-class tags can't be mismatched at this point. 14855 if (!isClassCompatTagKind(NewTag)) 14856 return true; 14857 14858 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14859 // by our warning analysis. We don't want to warn about mismatches with (eg) 14860 // declarations in system headers that are designed to be specialized, but if 14861 // a user asks us to warn, we should warn if their code contains mismatched 14862 // declarations. 14863 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14864 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14865 Loc); 14866 }; 14867 if (IsIgnoredLoc(NewTagLoc)) 14868 return true; 14869 14870 auto IsIgnored = [&](const TagDecl *Tag) { 14871 return IsIgnoredLoc(Tag->getLocation()); 14872 }; 14873 while (IsIgnored(Previous)) { 14874 Previous = Previous->getPreviousDecl(); 14875 if (!Previous) 14876 return true; 14877 OldTag = Previous->getTagKind(); 14878 } 14879 14880 bool isTemplate = false; 14881 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14882 isTemplate = Record->getDescribedClassTemplate(); 14883 14884 if (inTemplateInstantiation()) { 14885 if (OldTag != NewTag) { 14886 // In a template instantiation, do not offer fix-its for tag mismatches 14887 // since they usually mess up the template instead of fixing the problem. 14888 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14889 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14890 << getRedeclDiagFromTagKind(OldTag); 14891 // FIXME: Note previous location? 14892 } 14893 return true; 14894 } 14895 14896 if (isDefinition) { 14897 // On definitions, check all previous tags and issue a fix-it for each 14898 // one that doesn't match the current tag. 14899 if (Previous->getDefinition()) { 14900 // Don't suggest fix-its for redefinitions. 14901 return true; 14902 } 14903 14904 bool previousMismatch = false; 14905 for (const TagDecl *I : Previous->redecls()) { 14906 if (I->getTagKind() != NewTag) { 14907 // Ignore previous declarations for which the warning was disabled. 14908 if (IsIgnored(I)) 14909 continue; 14910 14911 if (!previousMismatch) { 14912 previousMismatch = true; 14913 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14914 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14915 << getRedeclDiagFromTagKind(I->getTagKind()); 14916 } 14917 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14918 << getRedeclDiagFromTagKind(NewTag) 14919 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14920 TypeWithKeyword::getTagTypeKindName(NewTag)); 14921 } 14922 } 14923 return true; 14924 } 14925 14926 // Identify the prevailing tag kind: this is the kind of the definition (if 14927 // there is a non-ignored definition), or otherwise the kind of the prior 14928 // (non-ignored) declaration. 14929 const TagDecl *PrevDef = Previous->getDefinition(); 14930 if (PrevDef && IsIgnored(PrevDef)) 14931 PrevDef = nullptr; 14932 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14933 if (Redecl->getTagKind() != NewTag) { 14934 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14935 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14936 << getRedeclDiagFromTagKind(OldTag); 14937 Diag(Redecl->getLocation(), diag::note_previous_use); 14938 14939 // If there is a previous definition, suggest a fix-it. 14940 if (PrevDef) { 14941 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14942 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14943 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14944 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14945 } 14946 } 14947 14948 return true; 14949 } 14950 14951 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14952 /// from an outer enclosing namespace or file scope inside a friend declaration. 14953 /// This should provide the commented out code in the following snippet: 14954 /// namespace N { 14955 /// struct X; 14956 /// namespace M { 14957 /// struct Y { friend struct /*N::*/ X; }; 14958 /// } 14959 /// } 14960 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14961 SourceLocation NameLoc) { 14962 // While the decl is in a namespace, do repeated lookup of that name and see 14963 // if we get the same namespace back. If we do not, continue until 14964 // translation unit scope, at which point we have a fully qualified NNS. 14965 SmallVector<IdentifierInfo *, 4> Namespaces; 14966 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14967 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14968 // This tag should be declared in a namespace, which can only be enclosed by 14969 // other namespaces. Bail if there's an anonymous namespace in the chain. 14970 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14971 if (!Namespace || Namespace->isAnonymousNamespace()) 14972 return FixItHint(); 14973 IdentifierInfo *II = Namespace->getIdentifier(); 14974 Namespaces.push_back(II); 14975 NamedDecl *Lookup = SemaRef.LookupSingleName( 14976 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14977 if (Lookup == Namespace) 14978 break; 14979 } 14980 14981 // Once we have all the namespaces, reverse them to go outermost first, and 14982 // build an NNS. 14983 SmallString<64> Insertion; 14984 llvm::raw_svector_ostream OS(Insertion); 14985 if (DC->isTranslationUnit()) 14986 OS << "::"; 14987 std::reverse(Namespaces.begin(), Namespaces.end()); 14988 for (auto *II : Namespaces) 14989 OS << II->getName() << "::"; 14990 return FixItHint::CreateInsertion(NameLoc, Insertion); 14991 } 14992 14993 /// Determine whether a tag originally declared in context \p OldDC can 14994 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14995 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14996 /// using-declaration). 14997 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14998 DeclContext *NewDC) { 14999 OldDC = OldDC->getRedeclContext(); 15000 NewDC = NewDC->getRedeclContext(); 15001 15002 if (OldDC->Equals(NewDC)) 15003 return true; 15004 15005 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15006 // encloses the other). 15007 if (S.getLangOpts().MSVCCompat && 15008 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15009 return true; 15010 15011 return false; 15012 } 15013 15014 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15015 /// former case, Name will be non-null. In the later case, Name will be null. 15016 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15017 /// reference/declaration/definition of a tag. 15018 /// 15019 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15020 /// trailing-type-specifier) other than one in an alias-declaration. 15021 /// 15022 /// \param SkipBody If non-null, will be set to indicate if the caller should 15023 /// skip the definition of this tag and treat it as if it were a declaration. 15024 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15025 SourceLocation KWLoc, CXXScopeSpec &SS, 15026 IdentifierInfo *Name, SourceLocation NameLoc, 15027 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15028 SourceLocation ModulePrivateLoc, 15029 MultiTemplateParamsArg TemplateParameterLists, 15030 bool &OwnedDecl, bool &IsDependent, 15031 SourceLocation ScopedEnumKWLoc, 15032 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15033 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15034 SkipBodyInfo *SkipBody) { 15035 // If this is not a definition, it must have a name. 15036 IdentifierInfo *OrigName = Name; 15037 assert((Name != nullptr || TUK == TUK_Definition) && 15038 "Nameless record must be a definition!"); 15039 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15040 15041 OwnedDecl = false; 15042 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15043 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15044 15045 // FIXME: Check member specializations more carefully. 15046 bool isMemberSpecialization = false; 15047 bool Invalid = false; 15048 15049 // We only need to do this matching if we have template parameters 15050 // or a scope specifier, which also conveniently avoids this work 15051 // for non-C++ cases. 15052 if (TemplateParameterLists.size() > 0 || 15053 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15054 if (TemplateParameterList *TemplateParams = 15055 MatchTemplateParametersToScopeSpecifier( 15056 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15057 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15058 if (Kind == TTK_Enum) { 15059 Diag(KWLoc, diag::err_enum_template); 15060 return nullptr; 15061 } 15062 15063 if (TemplateParams->size() > 0) { 15064 // This is a declaration or definition of a class template (which may 15065 // be a member of another template). 15066 15067 if (Invalid) 15068 return nullptr; 15069 15070 OwnedDecl = false; 15071 DeclResult Result = CheckClassTemplate( 15072 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15073 AS, ModulePrivateLoc, 15074 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15075 TemplateParameterLists.data(), SkipBody); 15076 return Result.get(); 15077 } else { 15078 // The "template<>" header is extraneous. 15079 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15080 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15081 isMemberSpecialization = true; 15082 } 15083 } 15084 } 15085 15086 // Figure out the underlying type if this a enum declaration. We need to do 15087 // this early, because it's needed to detect if this is an incompatible 15088 // redeclaration. 15089 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15090 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15091 15092 if (Kind == TTK_Enum) { 15093 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15094 // No underlying type explicitly specified, or we failed to parse the 15095 // type, default to int. 15096 EnumUnderlying = Context.IntTy.getTypePtr(); 15097 } else if (UnderlyingType.get()) { 15098 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15099 // integral type; any cv-qualification is ignored. 15100 TypeSourceInfo *TI = nullptr; 15101 GetTypeFromParser(UnderlyingType.get(), &TI); 15102 EnumUnderlying = TI; 15103 15104 if (CheckEnumUnderlyingType(TI)) 15105 // Recover by falling back to int. 15106 EnumUnderlying = Context.IntTy.getTypePtr(); 15107 15108 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15109 UPPC_FixedUnderlyingType)) 15110 EnumUnderlying = Context.IntTy.getTypePtr(); 15111 15112 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15113 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15114 // of 'int'. However, if this is an unfixed forward declaration, don't set 15115 // the underlying type unless the user enables -fms-compatibility. This 15116 // makes unfixed forward declared enums incomplete and is more conforming. 15117 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15118 EnumUnderlying = Context.IntTy.getTypePtr(); 15119 } 15120 } 15121 15122 DeclContext *SearchDC = CurContext; 15123 DeclContext *DC = CurContext; 15124 bool isStdBadAlloc = false; 15125 bool isStdAlignValT = false; 15126 15127 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15128 if (TUK == TUK_Friend || TUK == TUK_Reference) 15129 Redecl = NotForRedeclaration; 15130 15131 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15132 /// implemented asks for structural equivalence checking, the returned decl 15133 /// here is passed back to the parser, allowing the tag body to be parsed. 15134 auto createTagFromNewDecl = [&]() -> TagDecl * { 15135 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15136 // If there is an identifier, use the location of the identifier as the 15137 // location of the decl, otherwise use the location of the struct/union 15138 // keyword. 15139 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15140 TagDecl *New = nullptr; 15141 15142 if (Kind == TTK_Enum) { 15143 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15144 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15145 // If this is an undefined enum, bail. 15146 if (TUK != TUK_Definition && !Invalid) 15147 return nullptr; 15148 if (EnumUnderlying) { 15149 EnumDecl *ED = cast<EnumDecl>(New); 15150 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15151 ED->setIntegerTypeSourceInfo(TI); 15152 else 15153 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15154 ED->setPromotionType(ED->getIntegerType()); 15155 } 15156 } else { // struct/union 15157 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15158 nullptr); 15159 } 15160 15161 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15162 // Add alignment attributes if necessary; these attributes are checked 15163 // when the ASTContext lays out the structure. 15164 // 15165 // It is important for implementing the correct semantics that this 15166 // happen here (in ActOnTag). The #pragma pack stack is 15167 // maintained as a result of parser callbacks which can occur at 15168 // many points during the parsing of a struct declaration (because 15169 // the #pragma tokens are effectively skipped over during the 15170 // parsing of the struct). 15171 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15172 AddAlignmentAttributesForRecord(RD); 15173 AddMsStructLayoutForRecord(RD); 15174 } 15175 } 15176 New->setLexicalDeclContext(CurContext); 15177 return New; 15178 }; 15179 15180 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15181 if (Name && SS.isNotEmpty()) { 15182 // We have a nested-name tag ('struct foo::bar'). 15183 15184 // Check for invalid 'foo::'. 15185 if (SS.isInvalid()) { 15186 Name = nullptr; 15187 goto CreateNewDecl; 15188 } 15189 15190 // If this is a friend or a reference to a class in a dependent 15191 // context, don't try to make a decl for it. 15192 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15193 DC = computeDeclContext(SS, false); 15194 if (!DC) { 15195 IsDependent = true; 15196 return nullptr; 15197 } 15198 } else { 15199 DC = computeDeclContext(SS, true); 15200 if (!DC) { 15201 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15202 << SS.getRange(); 15203 return nullptr; 15204 } 15205 } 15206 15207 if (RequireCompleteDeclContext(SS, DC)) 15208 return nullptr; 15209 15210 SearchDC = DC; 15211 // Look-up name inside 'foo::'. 15212 LookupQualifiedName(Previous, DC); 15213 15214 if (Previous.isAmbiguous()) 15215 return nullptr; 15216 15217 if (Previous.empty()) { 15218 // Name lookup did not find anything. However, if the 15219 // nested-name-specifier refers to the current instantiation, 15220 // and that current instantiation has any dependent base 15221 // classes, we might find something at instantiation time: treat 15222 // this as a dependent elaborated-type-specifier. 15223 // But this only makes any sense for reference-like lookups. 15224 if (Previous.wasNotFoundInCurrentInstantiation() && 15225 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15226 IsDependent = true; 15227 return nullptr; 15228 } 15229 15230 // A tag 'foo::bar' must already exist. 15231 Diag(NameLoc, diag::err_not_tag_in_scope) 15232 << Kind << Name << DC << SS.getRange(); 15233 Name = nullptr; 15234 Invalid = true; 15235 goto CreateNewDecl; 15236 } 15237 } else if (Name) { 15238 // C++14 [class.mem]p14: 15239 // If T is the name of a class, then each of the following shall have a 15240 // name different from T: 15241 // -- every member of class T that is itself a type 15242 if (TUK != TUK_Reference && TUK != TUK_Friend && 15243 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15244 return nullptr; 15245 15246 // If this is a named struct, check to see if there was a previous forward 15247 // declaration or definition. 15248 // FIXME: We're looking into outer scopes here, even when we 15249 // shouldn't be. Doing so can result in ambiguities that we 15250 // shouldn't be diagnosing. 15251 LookupName(Previous, S); 15252 15253 // When declaring or defining a tag, ignore ambiguities introduced 15254 // by types using'ed into this scope. 15255 if (Previous.isAmbiguous() && 15256 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15257 LookupResult::Filter F = Previous.makeFilter(); 15258 while (F.hasNext()) { 15259 NamedDecl *ND = F.next(); 15260 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15261 SearchDC->getRedeclContext())) 15262 F.erase(); 15263 } 15264 F.done(); 15265 } 15266 15267 // C++11 [namespace.memdef]p3: 15268 // If the name in a friend declaration is neither qualified nor 15269 // a template-id and the declaration is a function or an 15270 // elaborated-type-specifier, the lookup to determine whether 15271 // the entity has been previously declared shall not consider 15272 // any scopes outside the innermost enclosing namespace. 15273 // 15274 // MSVC doesn't implement the above rule for types, so a friend tag 15275 // declaration may be a redeclaration of a type declared in an enclosing 15276 // scope. They do implement this rule for friend functions. 15277 // 15278 // Does it matter that this should be by scope instead of by 15279 // semantic context? 15280 if (!Previous.empty() && TUK == TUK_Friend) { 15281 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15282 LookupResult::Filter F = Previous.makeFilter(); 15283 bool FriendSawTagOutsideEnclosingNamespace = false; 15284 while (F.hasNext()) { 15285 NamedDecl *ND = F.next(); 15286 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15287 if (DC->isFileContext() && 15288 !EnclosingNS->Encloses(ND->getDeclContext())) { 15289 if (getLangOpts().MSVCCompat) 15290 FriendSawTagOutsideEnclosingNamespace = true; 15291 else 15292 F.erase(); 15293 } 15294 } 15295 F.done(); 15296 15297 // Diagnose this MSVC extension in the easy case where lookup would have 15298 // unambiguously found something outside the enclosing namespace. 15299 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15300 NamedDecl *ND = Previous.getFoundDecl(); 15301 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15302 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15303 } 15304 } 15305 15306 // Note: there used to be some attempt at recovery here. 15307 if (Previous.isAmbiguous()) 15308 return nullptr; 15309 15310 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15311 // FIXME: This makes sure that we ignore the contexts associated 15312 // with C structs, unions, and enums when looking for a matching 15313 // tag declaration or definition. See the similar lookup tweak 15314 // in Sema::LookupName; is there a better way to deal with this? 15315 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15316 SearchDC = SearchDC->getParent(); 15317 } 15318 } 15319 15320 if (Previous.isSingleResult() && 15321 Previous.getFoundDecl()->isTemplateParameter()) { 15322 // Maybe we will complain about the shadowed template parameter. 15323 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15324 // Just pretend that we didn't see the previous declaration. 15325 Previous.clear(); 15326 } 15327 15328 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15329 DC->Equals(getStdNamespace())) { 15330 if (Name->isStr("bad_alloc")) { 15331 // This is a declaration of or a reference to "std::bad_alloc". 15332 isStdBadAlloc = true; 15333 15334 // If std::bad_alloc has been implicitly declared (but made invisible to 15335 // name lookup), fill in this implicit declaration as the previous 15336 // declaration, so that the declarations get chained appropriately. 15337 if (Previous.empty() && StdBadAlloc) 15338 Previous.addDecl(getStdBadAlloc()); 15339 } else if (Name->isStr("align_val_t")) { 15340 isStdAlignValT = true; 15341 if (Previous.empty() && StdAlignValT) 15342 Previous.addDecl(getStdAlignValT()); 15343 } 15344 } 15345 15346 // If we didn't find a previous declaration, and this is a reference 15347 // (or friend reference), move to the correct scope. In C++, we 15348 // also need to do a redeclaration lookup there, just in case 15349 // there's a shadow friend decl. 15350 if (Name && Previous.empty() && 15351 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15352 if (Invalid) goto CreateNewDecl; 15353 assert(SS.isEmpty()); 15354 15355 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15356 // C++ [basic.scope.pdecl]p5: 15357 // -- for an elaborated-type-specifier of the form 15358 // 15359 // class-key identifier 15360 // 15361 // if the elaborated-type-specifier is used in the 15362 // decl-specifier-seq or parameter-declaration-clause of a 15363 // function defined in namespace scope, the identifier is 15364 // declared as a class-name in the namespace that contains 15365 // the declaration; otherwise, except as a friend 15366 // declaration, the identifier is declared in the smallest 15367 // non-class, non-function-prototype scope that contains the 15368 // declaration. 15369 // 15370 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15371 // C structs and unions. 15372 // 15373 // It is an error in C++ to declare (rather than define) an enum 15374 // type, including via an elaborated type specifier. We'll 15375 // diagnose that later; for now, declare the enum in the same 15376 // scope as we would have picked for any other tag type. 15377 // 15378 // GNU C also supports this behavior as part of its incomplete 15379 // enum types extension, while GNU C++ does not. 15380 // 15381 // Find the context where we'll be declaring the tag. 15382 // FIXME: We would like to maintain the current DeclContext as the 15383 // lexical context, 15384 SearchDC = getTagInjectionContext(SearchDC); 15385 15386 // Find the scope where we'll be declaring the tag. 15387 S = getTagInjectionScope(S, getLangOpts()); 15388 } else { 15389 assert(TUK == TUK_Friend); 15390 // C++ [namespace.memdef]p3: 15391 // If a friend declaration in a non-local class first declares a 15392 // class or function, the friend class or function is a member of 15393 // the innermost enclosing namespace. 15394 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15395 } 15396 15397 // In C++, we need to do a redeclaration lookup to properly 15398 // diagnose some problems. 15399 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15400 // hidden declaration so that we don't get ambiguity errors when using a 15401 // type declared by an elaborated-type-specifier. In C that is not correct 15402 // and we should instead merge compatible types found by lookup. 15403 if (getLangOpts().CPlusPlus) { 15404 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15405 LookupQualifiedName(Previous, SearchDC); 15406 } else { 15407 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15408 LookupName(Previous, S); 15409 } 15410 } 15411 15412 // If we have a known previous declaration to use, then use it. 15413 if (Previous.empty() && SkipBody && SkipBody->Previous) 15414 Previous.addDecl(SkipBody->Previous); 15415 15416 if (!Previous.empty()) { 15417 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15418 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15419 15420 // It's okay to have a tag decl in the same scope as a typedef 15421 // which hides a tag decl in the same scope. Finding this 15422 // insanity with a redeclaration lookup can only actually happen 15423 // in C++. 15424 // 15425 // This is also okay for elaborated-type-specifiers, which is 15426 // technically forbidden by the current standard but which is 15427 // okay according to the likely resolution of an open issue; 15428 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15429 if (getLangOpts().CPlusPlus) { 15430 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15431 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15432 TagDecl *Tag = TT->getDecl(); 15433 if (Tag->getDeclName() == Name && 15434 Tag->getDeclContext()->getRedeclContext() 15435 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15436 PrevDecl = Tag; 15437 Previous.clear(); 15438 Previous.addDecl(Tag); 15439 Previous.resolveKind(); 15440 } 15441 } 15442 } 15443 } 15444 15445 // If this is a redeclaration of a using shadow declaration, it must 15446 // declare a tag in the same context. In MSVC mode, we allow a 15447 // redefinition if either context is within the other. 15448 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15449 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15450 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15451 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15452 !(OldTag && isAcceptableTagRedeclContext( 15453 *this, OldTag->getDeclContext(), SearchDC))) { 15454 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15455 Diag(Shadow->getTargetDecl()->getLocation(), 15456 diag::note_using_decl_target); 15457 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15458 << 0; 15459 // Recover by ignoring the old declaration. 15460 Previous.clear(); 15461 goto CreateNewDecl; 15462 } 15463 } 15464 15465 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15466 // If this is a use of a previous tag, or if the tag is already declared 15467 // in the same scope (so that the definition/declaration completes or 15468 // rementions the tag), reuse the decl. 15469 if (TUK == TUK_Reference || TUK == TUK_Friend || 15470 isDeclInScope(DirectPrevDecl, SearchDC, S, 15471 SS.isNotEmpty() || isMemberSpecialization)) { 15472 // Make sure that this wasn't declared as an enum and now used as a 15473 // struct or something similar. 15474 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15475 TUK == TUK_Definition, KWLoc, 15476 Name)) { 15477 bool SafeToContinue 15478 = (PrevTagDecl->getTagKind() != TTK_Enum && 15479 Kind != TTK_Enum); 15480 if (SafeToContinue) 15481 Diag(KWLoc, diag::err_use_with_wrong_tag) 15482 << Name 15483 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15484 PrevTagDecl->getKindName()); 15485 else 15486 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15487 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15488 15489 if (SafeToContinue) 15490 Kind = PrevTagDecl->getTagKind(); 15491 else { 15492 // Recover by making this an anonymous redefinition. 15493 Name = nullptr; 15494 Previous.clear(); 15495 Invalid = true; 15496 } 15497 } 15498 15499 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15500 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15501 15502 // If this is an elaborated-type-specifier for a scoped enumeration, 15503 // the 'class' keyword is not necessary and not permitted. 15504 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15505 if (ScopedEnum) 15506 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15507 << PrevEnum->isScoped() 15508 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15509 return PrevTagDecl; 15510 } 15511 15512 QualType EnumUnderlyingTy; 15513 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15514 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15515 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15516 EnumUnderlyingTy = QualType(T, 0); 15517 15518 // All conflicts with previous declarations are recovered by 15519 // returning the previous declaration, unless this is a definition, 15520 // in which case we want the caller to bail out. 15521 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15522 ScopedEnum, EnumUnderlyingTy, 15523 IsFixed, PrevEnum)) 15524 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15525 } 15526 15527 // C++11 [class.mem]p1: 15528 // A member shall not be declared twice in the member-specification, 15529 // except that a nested class or member class template can be declared 15530 // and then later defined. 15531 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15532 S->isDeclScope(PrevDecl)) { 15533 Diag(NameLoc, diag::ext_member_redeclared); 15534 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15535 } 15536 15537 if (!Invalid) { 15538 // If this is a use, just return the declaration we found, unless 15539 // we have attributes. 15540 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15541 if (!Attrs.empty()) { 15542 // FIXME: Diagnose these attributes. For now, we create a new 15543 // declaration to hold them. 15544 } else if (TUK == TUK_Reference && 15545 (PrevTagDecl->getFriendObjectKind() == 15546 Decl::FOK_Undeclared || 15547 PrevDecl->getOwningModule() != getCurrentModule()) && 15548 SS.isEmpty()) { 15549 // This declaration is a reference to an existing entity, but 15550 // has different visibility from that entity: it either makes 15551 // a friend visible or it makes a type visible in a new module. 15552 // In either case, create a new declaration. We only do this if 15553 // the declaration would have meant the same thing if no prior 15554 // declaration were found, that is, if it was found in the same 15555 // scope where we would have injected a declaration. 15556 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15557 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15558 return PrevTagDecl; 15559 // This is in the injected scope, create a new declaration in 15560 // that scope. 15561 S = getTagInjectionScope(S, getLangOpts()); 15562 } else { 15563 return PrevTagDecl; 15564 } 15565 } 15566 15567 // Diagnose attempts to redefine a tag. 15568 if (TUK == TUK_Definition) { 15569 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15570 // If we're defining a specialization and the previous definition 15571 // is from an implicit instantiation, don't emit an error 15572 // here; we'll catch this in the general case below. 15573 bool IsExplicitSpecializationAfterInstantiation = false; 15574 if (isMemberSpecialization) { 15575 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15576 IsExplicitSpecializationAfterInstantiation = 15577 RD->getTemplateSpecializationKind() != 15578 TSK_ExplicitSpecialization; 15579 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15580 IsExplicitSpecializationAfterInstantiation = 15581 ED->getTemplateSpecializationKind() != 15582 TSK_ExplicitSpecialization; 15583 } 15584 15585 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15586 // not keep more that one definition around (merge them). However, 15587 // ensure the decl passes the structural compatibility check in 15588 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15589 NamedDecl *Hidden = nullptr; 15590 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15591 // There is a definition of this tag, but it is not visible. We 15592 // explicitly make use of C++'s one definition rule here, and 15593 // assume that this definition is identical to the hidden one 15594 // we already have. Make the existing definition visible and 15595 // use it in place of this one. 15596 if (!getLangOpts().CPlusPlus) { 15597 // Postpone making the old definition visible until after we 15598 // complete parsing the new one and do the structural 15599 // comparison. 15600 SkipBody->CheckSameAsPrevious = true; 15601 SkipBody->New = createTagFromNewDecl(); 15602 SkipBody->Previous = Def; 15603 return Def; 15604 } else { 15605 SkipBody->ShouldSkip = true; 15606 SkipBody->Previous = Def; 15607 makeMergedDefinitionVisible(Hidden); 15608 // Carry on and handle it like a normal definition. We'll 15609 // skip starting the definitiion later. 15610 } 15611 } else if (!IsExplicitSpecializationAfterInstantiation) { 15612 // A redeclaration in function prototype scope in C isn't 15613 // visible elsewhere, so merely issue a warning. 15614 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15615 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15616 else 15617 Diag(NameLoc, diag::err_redefinition) << Name; 15618 notePreviousDefinition(Def, 15619 NameLoc.isValid() ? NameLoc : KWLoc); 15620 // If this is a redefinition, recover by making this 15621 // struct be anonymous, which will make any later 15622 // references get the previous definition. 15623 Name = nullptr; 15624 Previous.clear(); 15625 Invalid = true; 15626 } 15627 } else { 15628 // If the type is currently being defined, complain 15629 // about a nested redefinition. 15630 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15631 if (TD->isBeingDefined()) { 15632 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15633 Diag(PrevTagDecl->getLocation(), 15634 diag::note_previous_definition); 15635 Name = nullptr; 15636 Previous.clear(); 15637 Invalid = true; 15638 } 15639 } 15640 15641 // Okay, this is definition of a previously declared or referenced 15642 // tag. We're going to create a new Decl for it. 15643 } 15644 15645 // Okay, we're going to make a redeclaration. If this is some kind 15646 // of reference, make sure we build the redeclaration in the same DC 15647 // as the original, and ignore the current access specifier. 15648 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15649 SearchDC = PrevTagDecl->getDeclContext(); 15650 AS = AS_none; 15651 } 15652 } 15653 // If we get here we have (another) forward declaration or we 15654 // have a definition. Just create a new decl. 15655 15656 } else { 15657 // If we get here, this is a definition of a new tag type in a nested 15658 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15659 // new decl/type. We set PrevDecl to NULL so that the entities 15660 // have distinct types. 15661 Previous.clear(); 15662 } 15663 // If we get here, we're going to create a new Decl. If PrevDecl 15664 // is non-NULL, it's a definition of the tag declared by 15665 // PrevDecl. If it's NULL, we have a new definition. 15666 15667 // Otherwise, PrevDecl is not a tag, but was found with tag 15668 // lookup. This is only actually possible in C++, where a few 15669 // things like templates still live in the tag namespace. 15670 } else { 15671 // Use a better diagnostic if an elaborated-type-specifier 15672 // found the wrong kind of type on the first 15673 // (non-redeclaration) lookup. 15674 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15675 !Previous.isForRedeclaration()) { 15676 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15677 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15678 << Kind; 15679 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15680 Invalid = true; 15681 15682 // Otherwise, only diagnose if the declaration is in scope. 15683 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15684 SS.isNotEmpty() || isMemberSpecialization)) { 15685 // do nothing 15686 15687 // Diagnose implicit declarations introduced by elaborated types. 15688 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15689 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15690 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15691 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15692 Invalid = true; 15693 15694 // Otherwise it's a declaration. Call out a particularly common 15695 // case here. 15696 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15697 unsigned Kind = 0; 15698 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15699 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15700 << Name << Kind << TND->getUnderlyingType(); 15701 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15702 Invalid = true; 15703 15704 // Otherwise, diagnose. 15705 } else { 15706 // The tag name clashes with something else in the target scope, 15707 // issue an error and recover by making this tag be anonymous. 15708 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15709 notePreviousDefinition(PrevDecl, NameLoc); 15710 Name = nullptr; 15711 Invalid = true; 15712 } 15713 15714 // The existing declaration isn't relevant to us; we're in a 15715 // new scope, so clear out the previous declaration. 15716 Previous.clear(); 15717 } 15718 } 15719 15720 CreateNewDecl: 15721 15722 TagDecl *PrevDecl = nullptr; 15723 if (Previous.isSingleResult()) 15724 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15725 15726 // If there is an identifier, use the location of the identifier as the 15727 // location of the decl, otherwise use the location of the struct/union 15728 // keyword. 15729 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15730 15731 // Otherwise, create a new declaration. If there is a previous 15732 // declaration of the same entity, the two will be linked via 15733 // PrevDecl. 15734 TagDecl *New; 15735 15736 if (Kind == TTK_Enum) { 15737 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15738 // enum X { A, B, C } D; D should chain to X. 15739 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15740 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15741 ScopedEnumUsesClassTag, IsFixed); 15742 15743 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15744 StdAlignValT = cast<EnumDecl>(New); 15745 15746 // If this is an undefined enum, warn. 15747 if (TUK != TUK_Definition && !Invalid) { 15748 TagDecl *Def; 15749 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15750 // C++0x: 7.2p2: opaque-enum-declaration. 15751 // Conflicts are diagnosed above. Do nothing. 15752 } 15753 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15754 Diag(Loc, diag::ext_forward_ref_enum_def) 15755 << New; 15756 Diag(Def->getLocation(), diag::note_previous_definition); 15757 } else { 15758 unsigned DiagID = diag::ext_forward_ref_enum; 15759 if (getLangOpts().MSVCCompat) 15760 DiagID = diag::ext_ms_forward_ref_enum; 15761 else if (getLangOpts().CPlusPlus) 15762 DiagID = diag::err_forward_ref_enum; 15763 Diag(Loc, DiagID); 15764 } 15765 } 15766 15767 if (EnumUnderlying) { 15768 EnumDecl *ED = cast<EnumDecl>(New); 15769 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15770 ED->setIntegerTypeSourceInfo(TI); 15771 else 15772 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15773 ED->setPromotionType(ED->getIntegerType()); 15774 assert(ED->isComplete() && "enum with type should be complete"); 15775 } 15776 } else { 15777 // struct/union/class 15778 15779 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15780 // struct X { int A; } D; D should chain to X. 15781 if (getLangOpts().CPlusPlus) { 15782 // FIXME: Look for a way to use RecordDecl for simple structs. 15783 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15784 cast_or_null<CXXRecordDecl>(PrevDecl)); 15785 15786 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15787 StdBadAlloc = cast<CXXRecordDecl>(New); 15788 } else 15789 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15790 cast_or_null<RecordDecl>(PrevDecl)); 15791 } 15792 15793 // C++11 [dcl.type]p3: 15794 // A type-specifier-seq shall not define a class or enumeration [...]. 15795 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15796 TUK == TUK_Definition) { 15797 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15798 << Context.getTagDeclType(New); 15799 Invalid = true; 15800 } 15801 15802 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15803 DC->getDeclKind() == Decl::Enum) { 15804 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15805 << Context.getTagDeclType(New); 15806 Invalid = true; 15807 } 15808 15809 // Maybe add qualifier info. 15810 if (SS.isNotEmpty()) { 15811 if (SS.isSet()) { 15812 // If this is either a declaration or a definition, check the 15813 // nested-name-specifier against the current context. 15814 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15815 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15816 isMemberSpecialization)) 15817 Invalid = true; 15818 15819 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15820 if (TemplateParameterLists.size() > 0) { 15821 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15822 } 15823 } 15824 else 15825 Invalid = true; 15826 } 15827 15828 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15829 // Add alignment attributes if necessary; these attributes are checked when 15830 // the ASTContext lays out the structure. 15831 // 15832 // It is important for implementing the correct semantics that this 15833 // happen here (in ActOnTag). The #pragma pack stack is 15834 // maintained as a result of parser callbacks which can occur at 15835 // many points during the parsing of a struct declaration (because 15836 // the #pragma tokens are effectively skipped over during the 15837 // parsing of the struct). 15838 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15839 AddAlignmentAttributesForRecord(RD); 15840 AddMsStructLayoutForRecord(RD); 15841 } 15842 } 15843 15844 if (ModulePrivateLoc.isValid()) { 15845 if (isMemberSpecialization) 15846 Diag(New->getLocation(), diag::err_module_private_specialization) 15847 << 2 15848 << FixItHint::CreateRemoval(ModulePrivateLoc); 15849 // __module_private__ does not apply to local classes. However, we only 15850 // diagnose this as an error when the declaration specifiers are 15851 // freestanding. Here, we just ignore the __module_private__. 15852 else if (!SearchDC->isFunctionOrMethod()) 15853 New->setModulePrivate(); 15854 } 15855 15856 // If this is a specialization of a member class (of a class template), 15857 // check the specialization. 15858 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15859 Invalid = true; 15860 15861 // If we're declaring or defining a tag in function prototype scope in C, 15862 // note that this type can only be used within the function and add it to 15863 // the list of decls to inject into the function definition scope. 15864 if ((Name || Kind == TTK_Enum) && 15865 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15866 if (getLangOpts().CPlusPlus) { 15867 // C++ [dcl.fct]p6: 15868 // Types shall not be defined in return or parameter types. 15869 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15870 Diag(Loc, diag::err_type_defined_in_param_type) 15871 << Name; 15872 Invalid = true; 15873 } 15874 } else if (!PrevDecl) { 15875 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15876 } 15877 } 15878 15879 if (Invalid) 15880 New->setInvalidDecl(); 15881 15882 // Set the lexical context. If the tag has a C++ scope specifier, the 15883 // lexical context will be different from the semantic context. 15884 New->setLexicalDeclContext(CurContext); 15885 15886 // Mark this as a friend decl if applicable. 15887 // In Microsoft mode, a friend declaration also acts as a forward 15888 // declaration so we always pass true to setObjectOfFriendDecl to make 15889 // the tag name visible. 15890 if (TUK == TUK_Friend) 15891 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15892 15893 // Set the access specifier. 15894 if (!Invalid && SearchDC->isRecord()) 15895 SetMemberAccessSpecifier(New, PrevDecl, AS); 15896 15897 if (PrevDecl) 15898 CheckRedeclarationModuleOwnership(New, PrevDecl); 15899 15900 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15901 New->startDefinition(); 15902 15903 ProcessDeclAttributeList(S, New, Attrs); 15904 AddPragmaAttributes(S, New); 15905 15906 // If this has an identifier, add it to the scope stack. 15907 if (TUK == TUK_Friend) { 15908 // We might be replacing an existing declaration in the lookup tables; 15909 // if so, borrow its access specifier. 15910 if (PrevDecl) 15911 New->setAccess(PrevDecl->getAccess()); 15912 15913 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15914 DC->makeDeclVisibleInContext(New); 15915 if (Name) // can be null along some error paths 15916 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15917 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15918 } else if (Name) { 15919 S = getNonFieldDeclScope(S); 15920 PushOnScopeChains(New, S, true); 15921 } else { 15922 CurContext->addDecl(New); 15923 } 15924 15925 // If this is the C FILE type, notify the AST context. 15926 if (IdentifierInfo *II = New->getIdentifier()) 15927 if (!New->isInvalidDecl() && 15928 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15929 II->isStr("FILE")) 15930 Context.setFILEDecl(New); 15931 15932 if (PrevDecl) 15933 mergeDeclAttributes(New, PrevDecl); 15934 15935 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15936 inferGslOwnerPointerAttribute(CXXRD); 15937 15938 // If there's a #pragma GCC visibility in scope, set the visibility of this 15939 // record. 15940 AddPushedVisibilityAttribute(New); 15941 15942 if (isMemberSpecialization && !New->isInvalidDecl()) 15943 CompleteMemberSpecialization(New, Previous); 15944 15945 OwnedDecl = true; 15946 // In C++, don't return an invalid declaration. We can't recover well from 15947 // the cases where we make the type anonymous. 15948 if (Invalid && getLangOpts().CPlusPlus) { 15949 if (New->isBeingDefined()) 15950 if (auto RD = dyn_cast<RecordDecl>(New)) 15951 RD->completeDefinition(); 15952 return nullptr; 15953 } else if (SkipBody && SkipBody->ShouldSkip) { 15954 return SkipBody->Previous; 15955 } else { 15956 return New; 15957 } 15958 } 15959 15960 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15961 AdjustDeclIfTemplate(TagD); 15962 TagDecl *Tag = cast<TagDecl>(TagD); 15963 15964 // Enter the tag context. 15965 PushDeclContext(S, Tag); 15966 15967 ActOnDocumentableDecl(TagD); 15968 15969 // If there's a #pragma GCC visibility in scope, set the visibility of this 15970 // record. 15971 AddPushedVisibilityAttribute(Tag); 15972 } 15973 15974 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15975 SkipBodyInfo &SkipBody) { 15976 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15977 return false; 15978 15979 // Make the previous decl visible. 15980 makeMergedDefinitionVisible(SkipBody.Previous); 15981 return true; 15982 } 15983 15984 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15985 assert(isa<ObjCContainerDecl>(IDecl) && 15986 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15987 DeclContext *OCD = cast<DeclContext>(IDecl); 15988 assert(getContainingDC(OCD) == CurContext && 15989 "The next DeclContext should be lexically contained in the current one."); 15990 CurContext = OCD; 15991 return IDecl; 15992 } 15993 15994 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15995 SourceLocation FinalLoc, 15996 bool IsFinalSpelledSealed, 15997 SourceLocation LBraceLoc) { 15998 AdjustDeclIfTemplate(TagD); 15999 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16000 16001 FieldCollector->StartClass(); 16002 16003 if (!Record->getIdentifier()) 16004 return; 16005 16006 if (FinalLoc.isValid()) 16007 Record->addAttr(FinalAttr::Create( 16008 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16009 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16010 16011 // C++ [class]p2: 16012 // [...] The class-name is also inserted into the scope of the 16013 // class itself; this is known as the injected-class-name. For 16014 // purposes of access checking, the injected-class-name is treated 16015 // as if it were a public member name. 16016 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16017 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16018 Record->getLocation(), Record->getIdentifier(), 16019 /*PrevDecl=*/nullptr, 16020 /*DelayTypeCreation=*/true); 16021 Context.getTypeDeclType(InjectedClassName, Record); 16022 InjectedClassName->setImplicit(); 16023 InjectedClassName->setAccess(AS_public); 16024 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16025 InjectedClassName->setDescribedClassTemplate(Template); 16026 PushOnScopeChains(InjectedClassName, S); 16027 assert(InjectedClassName->isInjectedClassName() && 16028 "Broken injected-class-name"); 16029 } 16030 16031 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16032 SourceRange BraceRange) { 16033 AdjustDeclIfTemplate(TagD); 16034 TagDecl *Tag = cast<TagDecl>(TagD); 16035 Tag->setBraceRange(BraceRange); 16036 16037 // Make sure we "complete" the definition even it is invalid. 16038 if (Tag->isBeingDefined()) { 16039 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16040 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16041 RD->completeDefinition(); 16042 } 16043 16044 if (isa<CXXRecordDecl>(Tag)) { 16045 FieldCollector->FinishClass(); 16046 } 16047 16048 // Exit this scope of this tag's definition. 16049 PopDeclContext(); 16050 16051 if (getCurLexicalContext()->isObjCContainer() && 16052 Tag->getDeclContext()->isFileContext()) 16053 Tag->setTopLevelDeclInObjCContainer(); 16054 16055 // Notify the consumer that we've defined a tag. 16056 if (!Tag->isInvalidDecl()) 16057 Consumer.HandleTagDeclDefinition(Tag); 16058 } 16059 16060 void Sema::ActOnObjCContainerFinishDefinition() { 16061 // Exit this scope of this interface definition. 16062 PopDeclContext(); 16063 } 16064 16065 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16066 assert(DC == CurContext && "Mismatch of container contexts"); 16067 OriginalLexicalContext = DC; 16068 ActOnObjCContainerFinishDefinition(); 16069 } 16070 16071 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16072 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16073 OriginalLexicalContext = nullptr; 16074 } 16075 16076 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16077 AdjustDeclIfTemplate(TagD); 16078 TagDecl *Tag = cast<TagDecl>(TagD); 16079 Tag->setInvalidDecl(); 16080 16081 // Make sure we "complete" the definition even it is invalid. 16082 if (Tag->isBeingDefined()) { 16083 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16084 RD->completeDefinition(); 16085 } 16086 16087 // We're undoing ActOnTagStartDefinition here, not 16088 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16089 // the FieldCollector. 16090 16091 PopDeclContext(); 16092 } 16093 16094 // Note that FieldName may be null for anonymous bitfields. 16095 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16096 IdentifierInfo *FieldName, 16097 QualType FieldTy, bool IsMsStruct, 16098 Expr *BitWidth, bool *ZeroWidth) { 16099 // Default to true; that shouldn't confuse checks for emptiness 16100 if (ZeroWidth) 16101 *ZeroWidth = true; 16102 16103 // C99 6.7.2.1p4 - verify the field type. 16104 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16105 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16106 // Handle incomplete and sizeless types with a specific error. 16107 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16108 diag::err_field_incomplete_or_sizeless)) 16109 return ExprError(); 16110 if (FieldName) 16111 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16112 << FieldName << FieldTy << BitWidth->getSourceRange(); 16113 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16114 << FieldTy << BitWidth->getSourceRange(); 16115 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16116 UPPC_BitFieldWidth)) 16117 return ExprError(); 16118 16119 // If the bit-width is type- or value-dependent, don't try to check 16120 // it now. 16121 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16122 return BitWidth; 16123 16124 llvm::APSInt Value; 16125 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16126 if (ICE.isInvalid()) 16127 return ICE; 16128 BitWidth = ICE.get(); 16129 16130 if (Value != 0 && ZeroWidth) 16131 *ZeroWidth = false; 16132 16133 // Zero-width bitfield is ok for anonymous field. 16134 if (Value == 0 && FieldName) 16135 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16136 16137 if (Value.isSigned() && Value.isNegative()) { 16138 if (FieldName) 16139 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16140 << FieldName << Value.toString(10); 16141 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16142 << Value.toString(10); 16143 } 16144 16145 if (!FieldTy->isDependentType()) { 16146 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16147 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16148 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16149 16150 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16151 // ABI. 16152 bool CStdConstraintViolation = 16153 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16154 bool MSBitfieldViolation = 16155 Value.ugt(TypeStorageSize) && 16156 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16157 if (CStdConstraintViolation || MSBitfieldViolation) { 16158 unsigned DiagWidth = 16159 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16160 if (FieldName) 16161 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16162 << FieldName << (unsigned)Value.getZExtValue() 16163 << !CStdConstraintViolation << DiagWidth; 16164 16165 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16166 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16167 << DiagWidth; 16168 } 16169 16170 // Warn on types where the user might conceivably expect to get all 16171 // specified bits as value bits: that's all integral types other than 16172 // 'bool'. 16173 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16174 if (FieldName) 16175 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16176 << FieldName << (unsigned)Value.getZExtValue() 16177 << (unsigned)TypeWidth; 16178 else 16179 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16180 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16181 } 16182 } 16183 16184 return BitWidth; 16185 } 16186 16187 /// ActOnField - Each field of a C struct/union is passed into this in order 16188 /// to create a FieldDecl object for it. 16189 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16190 Declarator &D, Expr *BitfieldWidth) { 16191 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16192 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16193 /*InitStyle=*/ICIS_NoInit, AS_public); 16194 return Res; 16195 } 16196 16197 /// HandleField - Analyze a field of a C struct or a C++ data member. 16198 /// 16199 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16200 SourceLocation DeclStart, 16201 Declarator &D, Expr *BitWidth, 16202 InClassInitStyle InitStyle, 16203 AccessSpecifier AS) { 16204 if (D.isDecompositionDeclarator()) { 16205 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16206 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16207 << Decomp.getSourceRange(); 16208 return nullptr; 16209 } 16210 16211 IdentifierInfo *II = D.getIdentifier(); 16212 SourceLocation Loc = DeclStart; 16213 if (II) Loc = D.getIdentifierLoc(); 16214 16215 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16216 QualType T = TInfo->getType(); 16217 if (getLangOpts().CPlusPlus) { 16218 CheckExtraCXXDefaultArguments(D); 16219 16220 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16221 UPPC_DataMemberType)) { 16222 D.setInvalidType(); 16223 T = Context.IntTy; 16224 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16225 } 16226 } 16227 16228 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16229 16230 if (D.getDeclSpec().isInlineSpecified()) 16231 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16232 << getLangOpts().CPlusPlus17; 16233 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16234 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16235 diag::err_invalid_thread) 16236 << DeclSpec::getSpecifierName(TSCS); 16237 16238 // Check to see if this name was declared as a member previously 16239 NamedDecl *PrevDecl = nullptr; 16240 LookupResult Previous(*this, II, Loc, LookupMemberName, 16241 ForVisibleRedeclaration); 16242 LookupName(Previous, S); 16243 switch (Previous.getResultKind()) { 16244 case LookupResult::Found: 16245 case LookupResult::FoundUnresolvedValue: 16246 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16247 break; 16248 16249 case LookupResult::FoundOverloaded: 16250 PrevDecl = Previous.getRepresentativeDecl(); 16251 break; 16252 16253 case LookupResult::NotFound: 16254 case LookupResult::NotFoundInCurrentInstantiation: 16255 case LookupResult::Ambiguous: 16256 break; 16257 } 16258 Previous.suppressDiagnostics(); 16259 16260 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16261 // Maybe we will complain about the shadowed template parameter. 16262 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16263 // Just pretend that we didn't see the previous declaration. 16264 PrevDecl = nullptr; 16265 } 16266 16267 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16268 PrevDecl = nullptr; 16269 16270 bool Mutable 16271 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16272 SourceLocation TSSL = D.getBeginLoc(); 16273 FieldDecl *NewFD 16274 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16275 TSSL, AS, PrevDecl, &D); 16276 16277 if (NewFD->isInvalidDecl()) 16278 Record->setInvalidDecl(); 16279 16280 if (D.getDeclSpec().isModulePrivateSpecified()) 16281 NewFD->setModulePrivate(); 16282 16283 if (NewFD->isInvalidDecl() && PrevDecl) { 16284 // Don't introduce NewFD into scope; there's already something 16285 // with the same name in the same scope. 16286 } else if (II) { 16287 PushOnScopeChains(NewFD, S); 16288 } else 16289 Record->addDecl(NewFD); 16290 16291 return NewFD; 16292 } 16293 16294 /// Build a new FieldDecl and check its well-formedness. 16295 /// 16296 /// This routine builds a new FieldDecl given the fields name, type, 16297 /// record, etc. \p PrevDecl should refer to any previous declaration 16298 /// with the same name and in the same scope as the field to be 16299 /// created. 16300 /// 16301 /// \returns a new FieldDecl. 16302 /// 16303 /// \todo The Declarator argument is a hack. It will be removed once 16304 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16305 TypeSourceInfo *TInfo, 16306 RecordDecl *Record, SourceLocation Loc, 16307 bool Mutable, Expr *BitWidth, 16308 InClassInitStyle InitStyle, 16309 SourceLocation TSSL, 16310 AccessSpecifier AS, NamedDecl *PrevDecl, 16311 Declarator *D) { 16312 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16313 bool InvalidDecl = false; 16314 if (D) InvalidDecl = D->isInvalidType(); 16315 16316 // If we receive a broken type, recover by assuming 'int' and 16317 // marking this declaration as invalid. 16318 if (T.isNull()) { 16319 InvalidDecl = true; 16320 T = Context.IntTy; 16321 } 16322 16323 QualType EltTy = Context.getBaseElementType(T); 16324 if (!EltTy->isDependentType()) { 16325 if (RequireCompleteSizedType(Loc, EltTy, 16326 diag::err_field_incomplete_or_sizeless)) { 16327 // Fields of incomplete type force their record to be invalid. 16328 Record->setInvalidDecl(); 16329 InvalidDecl = true; 16330 } else { 16331 NamedDecl *Def; 16332 EltTy->isIncompleteType(&Def); 16333 if (Def && Def->isInvalidDecl()) { 16334 Record->setInvalidDecl(); 16335 InvalidDecl = true; 16336 } 16337 } 16338 } 16339 16340 // TR 18037 does not allow fields to be declared with address space 16341 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16342 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16343 Diag(Loc, diag::err_field_with_address_space); 16344 Record->setInvalidDecl(); 16345 InvalidDecl = true; 16346 } 16347 16348 if (LangOpts.OpenCL) { 16349 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16350 // used as structure or union field: image, sampler, event or block types. 16351 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16352 T->isBlockPointerType()) { 16353 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16354 Record->setInvalidDecl(); 16355 InvalidDecl = true; 16356 } 16357 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16358 if (BitWidth) { 16359 Diag(Loc, diag::err_opencl_bitfields); 16360 InvalidDecl = true; 16361 } 16362 } 16363 16364 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16365 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16366 T.hasQualifiers()) { 16367 InvalidDecl = true; 16368 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16369 } 16370 16371 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16372 // than a variably modified type. 16373 if (!InvalidDecl && T->isVariablyModifiedType()) { 16374 bool SizeIsNegative; 16375 llvm::APSInt Oversized; 16376 16377 TypeSourceInfo *FixedTInfo = 16378 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16379 SizeIsNegative, 16380 Oversized); 16381 if (FixedTInfo) { 16382 Diag(Loc, diag::warn_illegal_constant_array_size); 16383 TInfo = FixedTInfo; 16384 T = FixedTInfo->getType(); 16385 } else { 16386 if (SizeIsNegative) 16387 Diag(Loc, diag::err_typecheck_negative_array_size); 16388 else if (Oversized.getBoolValue()) 16389 Diag(Loc, diag::err_array_too_large) 16390 << Oversized.toString(10); 16391 else 16392 Diag(Loc, diag::err_typecheck_field_variable_size); 16393 InvalidDecl = true; 16394 } 16395 } 16396 16397 // Fields can not have abstract class types 16398 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16399 diag::err_abstract_type_in_decl, 16400 AbstractFieldType)) 16401 InvalidDecl = true; 16402 16403 bool ZeroWidth = false; 16404 if (InvalidDecl) 16405 BitWidth = nullptr; 16406 // If this is declared as a bit-field, check the bit-field. 16407 if (BitWidth) { 16408 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16409 &ZeroWidth).get(); 16410 if (!BitWidth) { 16411 InvalidDecl = true; 16412 BitWidth = nullptr; 16413 ZeroWidth = false; 16414 } 16415 } 16416 16417 // Check that 'mutable' is consistent with the type of the declaration. 16418 if (!InvalidDecl && Mutable) { 16419 unsigned DiagID = 0; 16420 if (T->isReferenceType()) 16421 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16422 : diag::err_mutable_reference; 16423 else if (T.isConstQualified()) 16424 DiagID = diag::err_mutable_const; 16425 16426 if (DiagID) { 16427 SourceLocation ErrLoc = Loc; 16428 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16429 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16430 Diag(ErrLoc, DiagID); 16431 if (DiagID != diag::ext_mutable_reference) { 16432 Mutable = false; 16433 InvalidDecl = true; 16434 } 16435 } 16436 } 16437 16438 // C++11 [class.union]p8 (DR1460): 16439 // At most one variant member of a union may have a 16440 // brace-or-equal-initializer. 16441 if (InitStyle != ICIS_NoInit) 16442 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16443 16444 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16445 BitWidth, Mutable, InitStyle); 16446 if (InvalidDecl) 16447 NewFD->setInvalidDecl(); 16448 16449 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16450 Diag(Loc, diag::err_duplicate_member) << II; 16451 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16452 NewFD->setInvalidDecl(); 16453 } 16454 16455 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16456 if (Record->isUnion()) { 16457 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16458 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16459 if (RDecl->getDefinition()) { 16460 // C++ [class.union]p1: An object of a class with a non-trivial 16461 // constructor, a non-trivial copy constructor, a non-trivial 16462 // destructor, or a non-trivial copy assignment operator 16463 // cannot be a member of a union, nor can an array of such 16464 // objects. 16465 if (CheckNontrivialField(NewFD)) 16466 NewFD->setInvalidDecl(); 16467 } 16468 } 16469 16470 // C++ [class.union]p1: If a union contains a member of reference type, 16471 // the program is ill-formed, except when compiling with MSVC extensions 16472 // enabled. 16473 if (EltTy->isReferenceType()) { 16474 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16475 diag::ext_union_member_of_reference_type : 16476 diag::err_union_member_of_reference_type) 16477 << NewFD->getDeclName() << EltTy; 16478 if (!getLangOpts().MicrosoftExt) 16479 NewFD->setInvalidDecl(); 16480 } 16481 } 16482 } 16483 16484 // FIXME: We need to pass in the attributes given an AST 16485 // representation, not a parser representation. 16486 if (D) { 16487 // FIXME: The current scope is almost... but not entirely... correct here. 16488 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16489 16490 if (NewFD->hasAttrs()) 16491 CheckAlignasUnderalignment(NewFD); 16492 } 16493 16494 // In auto-retain/release, infer strong retension for fields of 16495 // retainable type. 16496 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16497 NewFD->setInvalidDecl(); 16498 16499 if (T.isObjCGCWeak()) 16500 Diag(Loc, diag::warn_attribute_weak_on_field); 16501 16502 NewFD->setAccess(AS); 16503 return NewFD; 16504 } 16505 16506 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16507 assert(FD); 16508 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16509 16510 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16511 return false; 16512 16513 QualType EltTy = Context.getBaseElementType(FD->getType()); 16514 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16515 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16516 if (RDecl->getDefinition()) { 16517 // We check for copy constructors before constructors 16518 // because otherwise we'll never get complaints about 16519 // copy constructors. 16520 16521 CXXSpecialMember member = CXXInvalid; 16522 // We're required to check for any non-trivial constructors. Since the 16523 // implicit default constructor is suppressed if there are any 16524 // user-declared constructors, we just need to check that there is a 16525 // trivial default constructor and a trivial copy constructor. (We don't 16526 // worry about move constructors here, since this is a C++98 check.) 16527 if (RDecl->hasNonTrivialCopyConstructor()) 16528 member = CXXCopyConstructor; 16529 else if (!RDecl->hasTrivialDefaultConstructor()) 16530 member = CXXDefaultConstructor; 16531 else if (RDecl->hasNonTrivialCopyAssignment()) 16532 member = CXXCopyAssignment; 16533 else if (RDecl->hasNonTrivialDestructor()) 16534 member = CXXDestructor; 16535 16536 if (member != CXXInvalid) { 16537 if (!getLangOpts().CPlusPlus11 && 16538 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16539 // Objective-C++ ARC: it is an error to have a non-trivial field of 16540 // a union. However, system headers in Objective-C programs 16541 // occasionally have Objective-C lifetime objects within unions, 16542 // and rather than cause the program to fail, we make those 16543 // members unavailable. 16544 SourceLocation Loc = FD->getLocation(); 16545 if (getSourceManager().isInSystemHeader(Loc)) { 16546 if (!FD->hasAttr<UnavailableAttr>()) 16547 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16548 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16549 return false; 16550 } 16551 } 16552 16553 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16554 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16555 diag::err_illegal_union_or_anon_struct_member) 16556 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16557 DiagnoseNontrivial(RDecl, member); 16558 return !getLangOpts().CPlusPlus11; 16559 } 16560 } 16561 } 16562 16563 return false; 16564 } 16565 16566 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16567 /// AST enum value. 16568 static ObjCIvarDecl::AccessControl 16569 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16570 switch (ivarVisibility) { 16571 default: llvm_unreachable("Unknown visitibility kind"); 16572 case tok::objc_private: return ObjCIvarDecl::Private; 16573 case tok::objc_public: return ObjCIvarDecl::Public; 16574 case tok::objc_protected: return ObjCIvarDecl::Protected; 16575 case tok::objc_package: return ObjCIvarDecl::Package; 16576 } 16577 } 16578 16579 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16580 /// in order to create an IvarDecl object for it. 16581 Decl *Sema::ActOnIvar(Scope *S, 16582 SourceLocation DeclStart, 16583 Declarator &D, Expr *BitfieldWidth, 16584 tok::ObjCKeywordKind Visibility) { 16585 16586 IdentifierInfo *II = D.getIdentifier(); 16587 Expr *BitWidth = (Expr*)BitfieldWidth; 16588 SourceLocation Loc = DeclStart; 16589 if (II) Loc = D.getIdentifierLoc(); 16590 16591 // FIXME: Unnamed fields can be handled in various different ways, for 16592 // example, unnamed unions inject all members into the struct namespace! 16593 16594 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16595 QualType T = TInfo->getType(); 16596 16597 if (BitWidth) { 16598 // 6.7.2.1p3, 6.7.2.1p4 16599 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16600 if (!BitWidth) 16601 D.setInvalidType(); 16602 } else { 16603 // Not a bitfield. 16604 16605 // validate II. 16606 16607 } 16608 if (T->isReferenceType()) { 16609 Diag(Loc, diag::err_ivar_reference_type); 16610 D.setInvalidType(); 16611 } 16612 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16613 // than a variably modified type. 16614 else if (T->isVariablyModifiedType()) { 16615 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16616 D.setInvalidType(); 16617 } 16618 16619 // Get the visibility (access control) for this ivar. 16620 ObjCIvarDecl::AccessControl ac = 16621 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16622 : ObjCIvarDecl::None; 16623 // Must set ivar's DeclContext to its enclosing interface. 16624 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16625 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16626 return nullptr; 16627 ObjCContainerDecl *EnclosingContext; 16628 if (ObjCImplementationDecl *IMPDecl = 16629 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16630 if (LangOpts.ObjCRuntime.isFragile()) { 16631 // Case of ivar declared in an implementation. Context is that of its class. 16632 EnclosingContext = IMPDecl->getClassInterface(); 16633 assert(EnclosingContext && "Implementation has no class interface!"); 16634 } 16635 else 16636 EnclosingContext = EnclosingDecl; 16637 } else { 16638 if (ObjCCategoryDecl *CDecl = 16639 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16640 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16641 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16642 return nullptr; 16643 } 16644 } 16645 EnclosingContext = EnclosingDecl; 16646 } 16647 16648 // Construct the decl. 16649 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16650 DeclStart, Loc, II, T, 16651 TInfo, ac, (Expr *)BitfieldWidth); 16652 16653 if (II) { 16654 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16655 ForVisibleRedeclaration); 16656 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16657 && !isa<TagDecl>(PrevDecl)) { 16658 Diag(Loc, diag::err_duplicate_member) << II; 16659 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16660 NewID->setInvalidDecl(); 16661 } 16662 } 16663 16664 // Process attributes attached to the ivar. 16665 ProcessDeclAttributes(S, NewID, D); 16666 16667 if (D.isInvalidType()) 16668 NewID->setInvalidDecl(); 16669 16670 // In ARC, infer 'retaining' for ivars of retainable type. 16671 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16672 NewID->setInvalidDecl(); 16673 16674 if (D.getDeclSpec().isModulePrivateSpecified()) 16675 NewID->setModulePrivate(); 16676 16677 if (II) { 16678 // FIXME: When interfaces are DeclContexts, we'll need to add 16679 // these to the interface. 16680 S->AddDecl(NewID); 16681 IdResolver.AddDecl(NewID); 16682 } 16683 16684 if (LangOpts.ObjCRuntime.isNonFragile() && 16685 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16686 Diag(Loc, diag::warn_ivars_in_interface); 16687 16688 return NewID; 16689 } 16690 16691 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16692 /// class and class extensions. For every class \@interface and class 16693 /// extension \@interface, if the last ivar is a bitfield of any type, 16694 /// then add an implicit `char :0` ivar to the end of that interface. 16695 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16696 SmallVectorImpl<Decl *> &AllIvarDecls) { 16697 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16698 return; 16699 16700 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16701 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16702 16703 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16704 return; 16705 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16706 if (!ID) { 16707 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16708 if (!CD->IsClassExtension()) 16709 return; 16710 } 16711 // No need to add this to end of @implementation. 16712 else 16713 return; 16714 } 16715 // All conditions are met. Add a new bitfield to the tail end of ivars. 16716 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16717 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16718 16719 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16720 DeclLoc, DeclLoc, nullptr, 16721 Context.CharTy, 16722 Context.getTrivialTypeSourceInfo(Context.CharTy, 16723 DeclLoc), 16724 ObjCIvarDecl::Private, BW, 16725 true); 16726 AllIvarDecls.push_back(Ivar); 16727 } 16728 16729 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16730 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16731 SourceLocation RBrac, 16732 const ParsedAttributesView &Attrs) { 16733 assert(EnclosingDecl && "missing record or interface decl"); 16734 16735 // If this is an Objective-C @implementation or category and we have 16736 // new fields here we should reset the layout of the interface since 16737 // it will now change. 16738 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16739 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16740 switch (DC->getKind()) { 16741 default: break; 16742 case Decl::ObjCCategory: 16743 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16744 break; 16745 case Decl::ObjCImplementation: 16746 Context. 16747 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16748 break; 16749 } 16750 } 16751 16752 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16753 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16754 16755 // Start counting up the number of named members; make sure to include 16756 // members of anonymous structs and unions in the total. 16757 unsigned NumNamedMembers = 0; 16758 if (Record) { 16759 for (const auto *I : Record->decls()) { 16760 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16761 if (IFD->getDeclName()) 16762 ++NumNamedMembers; 16763 } 16764 } 16765 16766 // Verify that all the fields are okay. 16767 SmallVector<FieldDecl*, 32> RecFields; 16768 16769 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16770 i != end; ++i) { 16771 FieldDecl *FD = cast<FieldDecl>(*i); 16772 16773 // Get the type for the field. 16774 const Type *FDTy = FD->getType().getTypePtr(); 16775 16776 if (!FD->isAnonymousStructOrUnion()) { 16777 // Remember all fields written by the user. 16778 RecFields.push_back(FD); 16779 } 16780 16781 // If the field is already invalid for some reason, don't emit more 16782 // diagnostics about it. 16783 if (FD->isInvalidDecl()) { 16784 EnclosingDecl->setInvalidDecl(); 16785 continue; 16786 } 16787 16788 // C99 6.7.2.1p2: 16789 // A structure or union shall not contain a member with 16790 // incomplete or function type (hence, a structure shall not 16791 // contain an instance of itself, but may contain a pointer to 16792 // an instance of itself), except that the last member of a 16793 // structure with more than one named member may have incomplete 16794 // array type; such a structure (and any union containing, 16795 // possibly recursively, a member that is such a structure) 16796 // shall not be a member of a structure or an element of an 16797 // array. 16798 bool IsLastField = (i + 1 == Fields.end()); 16799 if (FDTy->isFunctionType()) { 16800 // Field declared as a function. 16801 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16802 << FD->getDeclName(); 16803 FD->setInvalidDecl(); 16804 EnclosingDecl->setInvalidDecl(); 16805 continue; 16806 } else if (FDTy->isIncompleteArrayType() && 16807 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16808 if (Record) { 16809 // Flexible array member. 16810 // Microsoft and g++ is more permissive regarding flexible array. 16811 // It will accept flexible array in union and also 16812 // as the sole element of a struct/class. 16813 unsigned DiagID = 0; 16814 if (!Record->isUnion() && !IsLastField) { 16815 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16816 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16817 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16818 FD->setInvalidDecl(); 16819 EnclosingDecl->setInvalidDecl(); 16820 continue; 16821 } else if (Record->isUnion()) 16822 DiagID = getLangOpts().MicrosoftExt 16823 ? diag::ext_flexible_array_union_ms 16824 : getLangOpts().CPlusPlus 16825 ? diag::ext_flexible_array_union_gnu 16826 : diag::err_flexible_array_union; 16827 else if (NumNamedMembers < 1) 16828 DiagID = getLangOpts().MicrosoftExt 16829 ? diag::ext_flexible_array_empty_aggregate_ms 16830 : getLangOpts().CPlusPlus 16831 ? diag::ext_flexible_array_empty_aggregate_gnu 16832 : diag::err_flexible_array_empty_aggregate; 16833 16834 if (DiagID) 16835 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16836 << Record->getTagKind(); 16837 // While the layout of types that contain virtual bases is not specified 16838 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16839 // virtual bases after the derived members. This would make a flexible 16840 // array member declared at the end of an object not adjacent to the end 16841 // of the type. 16842 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16843 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16844 << FD->getDeclName() << Record->getTagKind(); 16845 if (!getLangOpts().C99) 16846 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16847 << FD->getDeclName() << Record->getTagKind(); 16848 16849 // If the element type has a non-trivial destructor, we would not 16850 // implicitly destroy the elements, so disallow it for now. 16851 // 16852 // FIXME: GCC allows this. We should probably either implicitly delete 16853 // the destructor of the containing class, or just allow this. 16854 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16855 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16856 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16857 << FD->getDeclName() << FD->getType(); 16858 FD->setInvalidDecl(); 16859 EnclosingDecl->setInvalidDecl(); 16860 continue; 16861 } 16862 // Okay, we have a legal flexible array member at the end of the struct. 16863 Record->setHasFlexibleArrayMember(true); 16864 } else { 16865 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16866 // unless they are followed by another ivar. That check is done 16867 // elsewhere, after synthesized ivars are known. 16868 } 16869 } else if (!FDTy->isDependentType() && 16870 RequireCompleteSizedType( 16871 FD->getLocation(), FD->getType(), 16872 diag::err_field_incomplete_or_sizeless)) { 16873 // Incomplete type 16874 FD->setInvalidDecl(); 16875 EnclosingDecl->setInvalidDecl(); 16876 continue; 16877 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16878 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16879 // A type which contains a flexible array member is considered to be a 16880 // flexible array member. 16881 Record->setHasFlexibleArrayMember(true); 16882 if (!Record->isUnion()) { 16883 // If this is a struct/class and this is not the last element, reject 16884 // it. Note that GCC supports variable sized arrays in the middle of 16885 // structures. 16886 if (!IsLastField) 16887 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16888 << FD->getDeclName() << FD->getType(); 16889 else { 16890 // We support flexible arrays at the end of structs in 16891 // other structs as an extension. 16892 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16893 << FD->getDeclName(); 16894 } 16895 } 16896 } 16897 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16898 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16899 diag::err_abstract_type_in_decl, 16900 AbstractIvarType)) { 16901 // Ivars can not have abstract class types 16902 FD->setInvalidDecl(); 16903 } 16904 if (Record && FDTTy->getDecl()->hasObjectMember()) 16905 Record->setHasObjectMember(true); 16906 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16907 Record->setHasVolatileMember(true); 16908 } else if (FDTy->isObjCObjectType()) { 16909 /// A field cannot be an Objective-c object 16910 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16911 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16912 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16913 FD->setType(T); 16914 } else if (Record && Record->isUnion() && 16915 FD->getType().hasNonTrivialObjCLifetime() && 16916 getSourceManager().isInSystemHeader(FD->getLocation()) && 16917 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16918 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16919 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16920 // For backward compatibility, fields of C unions declared in system 16921 // headers that have non-trivial ObjC ownership qualifications are marked 16922 // as unavailable unless the qualifier is explicit and __strong. This can 16923 // break ABI compatibility between programs compiled with ARC and MRR, but 16924 // is a better option than rejecting programs using those unions under 16925 // ARC. 16926 FD->addAttr(UnavailableAttr::CreateImplicit( 16927 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16928 FD->getLocation())); 16929 } else if (getLangOpts().ObjC && 16930 getLangOpts().getGC() != LangOptions::NonGC && Record && 16931 !Record->hasObjectMember()) { 16932 if (FD->getType()->isObjCObjectPointerType() || 16933 FD->getType().isObjCGCStrong()) 16934 Record->setHasObjectMember(true); 16935 else if (Context.getAsArrayType(FD->getType())) { 16936 QualType BaseType = Context.getBaseElementType(FD->getType()); 16937 if (BaseType->isRecordType() && 16938 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 16939 Record->setHasObjectMember(true); 16940 else if (BaseType->isObjCObjectPointerType() || 16941 BaseType.isObjCGCStrong()) 16942 Record->setHasObjectMember(true); 16943 } 16944 } 16945 16946 if (Record && !getLangOpts().CPlusPlus && 16947 !shouldIgnoreForRecordTriviality(FD)) { 16948 QualType FT = FD->getType(); 16949 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16950 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16951 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16952 Record->isUnion()) 16953 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16954 } 16955 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16956 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16957 Record->setNonTrivialToPrimitiveCopy(true); 16958 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16959 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16960 } 16961 if (FT.isDestructedType()) { 16962 Record->setNonTrivialToPrimitiveDestroy(true); 16963 Record->setParamDestroyedInCallee(true); 16964 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16965 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16966 } 16967 16968 if (const auto *RT = FT->getAs<RecordType>()) { 16969 if (RT->getDecl()->getArgPassingRestrictions() == 16970 RecordDecl::APK_CanNeverPassInRegs) 16971 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16972 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16973 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16974 } 16975 16976 if (Record && FD->getType().isVolatileQualified()) 16977 Record->setHasVolatileMember(true); 16978 // Keep track of the number of named members. 16979 if (FD->getIdentifier()) 16980 ++NumNamedMembers; 16981 } 16982 16983 // Okay, we successfully defined 'Record'. 16984 if (Record) { 16985 bool Completed = false; 16986 if (CXXRecord) { 16987 if (!CXXRecord->isInvalidDecl()) { 16988 // Set access bits correctly on the directly-declared conversions. 16989 for (CXXRecordDecl::conversion_iterator 16990 I = CXXRecord->conversion_begin(), 16991 E = CXXRecord->conversion_end(); I != E; ++I) 16992 I.setAccess((*I)->getAccess()); 16993 } 16994 16995 if (!CXXRecord->isDependentType()) { 16996 // Add any implicitly-declared members to this class. 16997 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16998 16999 if (!CXXRecord->isInvalidDecl()) { 17000 // If we have virtual base classes, we may end up finding multiple 17001 // final overriders for a given virtual function. Check for this 17002 // problem now. 17003 if (CXXRecord->getNumVBases()) { 17004 CXXFinalOverriderMap FinalOverriders; 17005 CXXRecord->getFinalOverriders(FinalOverriders); 17006 17007 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17008 MEnd = FinalOverriders.end(); 17009 M != MEnd; ++M) { 17010 for (OverridingMethods::iterator SO = M->second.begin(), 17011 SOEnd = M->second.end(); 17012 SO != SOEnd; ++SO) { 17013 assert(SO->second.size() > 0 && 17014 "Virtual function without overriding functions?"); 17015 if (SO->second.size() == 1) 17016 continue; 17017 17018 // C++ [class.virtual]p2: 17019 // In a derived class, if a virtual member function of a base 17020 // class subobject has more than one final overrider the 17021 // program is ill-formed. 17022 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17023 << (const NamedDecl *)M->first << Record; 17024 Diag(M->first->getLocation(), 17025 diag::note_overridden_virtual_function); 17026 for (OverridingMethods::overriding_iterator 17027 OM = SO->second.begin(), 17028 OMEnd = SO->second.end(); 17029 OM != OMEnd; ++OM) 17030 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17031 << (const NamedDecl *)M->first << OM->Method->getParent(); 17032 17033 Record->setInvalidDecl(); 17034 } 17035 } 17036 CXXRecord->completeDefinition(&FinalOverriders); 17037 Completed = true; 17038 } 17039 } 17040 } 17041 } 17042 17043 if (!Completed) 17044 Record->completeDefinition(); 17045 17046 // Handle attributes before checking the layout. 17047 ProcessDeclAttributeList(S, Record, Attrs); 17048 17049 // We may have deferred checking for a deleted destructor. Check now. 17050 if (CXXRecord) { 17051 auto *Dtor = CXXRecord->getDestructor(); 17052 if (Dtor && Dtor->isImplicit() && 17053 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17054 CXXRecord->setImplicitDestructorIsDeleted(); 17055 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17056 } 17057 } 17058 17059 if (Record->hasAttrs()) { 17060 CheckAlignasUnderalignment(Record); 17061 17062 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17063 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17064 IA->getRange(), IA->getBestCase(), 17065 IA->getInheritanceModel()); 17066 } 17067 17068 // Check if the structure/union declaration is a type that can have zero 17069 // size in C. For C this is a language extension, for C++ it may cause 17070 // compatibility problems. 17071 bool CheckForZeroSize; 17072 if (!getLangOpts().CPlusPlus) { 17073 CheckForZeroSize = true; 17074 } else { 17075 // For C++ filter out types that cannot be referenced in C code. 17076 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17077 CheckForZeroSize = 17078 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17079 !CXXRecord->isDependentType() && 17080 CXXRecord->isCLike(); 17081 } 17082 if (CheckForZeroSize) { 17083 bool ZeroSize = true; 17084 bool IsEmpty = true; 17085 unsigned NonBitFields = 0; 17086 for (RecordDecl::field_iterator I = Record->field_begin(), 17087 E = Record->field_end(); 17088 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17089 IsEmpty = false; 17090 if (I->isUnnamedBitfield()) { 17091 if (!I->isZeroLengthBitField(Context)) 17092 ZeroSize = false; 17093 } else { 17094 ++NonBitFields; 17095 QualType FieldType = I->getType(); 17096 if (FieldType->isIncompleteType() || 17097 !Context.getTypeSizeInChars(FieldType).isZero()) 17098 ZeroSize = false; 17099 } 17100 } 17101 17102 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17103 // allowed in C++, but warn if its declaration is inside 17104 // extern "C" block. 17105 if (ZeroSize) { 17106 Diag(RecLoc, getLangOpts().CPlusPlus ? 17107 diag::warn_zero_size_struct_union_in_extern_c : 17108 diag::warn_zero_size_struct_union_compat) 17109 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17110 } 17111 17112 // Structs without named members are extension in C (C99 6.7.2.1p7), 17113 // but are accepted by GCC. 17114 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17115 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17116 diag::ext_no_named_members_in_struct_union) 17117 << Record->isUnion(); 17118 } 17119 } 17120 } else { 17121 ObjCIvarDecl **ClsFields = 17122 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17123 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17124 ID->setEndOfDefinitionLoc(RBrac); 17125 // Add ivar's to class's DeclContext. 17126 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17127 ClsFields[i]->setLexicalDeclContext(ID); 17128 ID->addDecl(ClsFields[i]); 17129 } 17130 // Must enforce the rule that ivars in the base classes may not be 17131 // duplicates. 17132 if (ID->getSuperClass()) 17133 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17134 } else if (ObjCImplementationDecl *IMPDecl = 17135 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17136 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17137 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17138 // Ivar declared in @implementation never belongs to the implementation. 17139 // Only it is in implementation's lexical context. 17140 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17141 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17142 IMPDecl->setIvarLBraceLoc(LBrac); 17143 IMPDecl->setIvarRBraceLoc(RBrac); 17144 } else if (ObjCCategoryDecl *CDecl = 17145 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17146 // case of ivars in class extension; all other cases have been 17147 // reported as errors elsewhere. 17148 // FIXME. Class extension does not have a LocEnd field. 17149 // CDecl->setLocEnd(RBrac); 17150 // Add ivar's to class extension's DeclContext. 17151 // Diagnose redeclaration of private ivars. 17152 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17153 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17154 if (IDecl) { 17155 if (const ObjCIvarDecl *ClsIvar = 17156 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17157 Diag(ClsFields[i]->getLocation(), 17158 diag::err_duplicate_ivar_declaration); 17159 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17160 continue; 17161 } 17162 for (const auto *Ext : IDecl->known_extensions()) { 17163 if (const ObjCIvarDecl *ClsExtIvar 17164 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17165 Diag(ClsFields[i]->getLocation(), 17166 diag::err_duplicate_ivar_declaration); 17167 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17168 continue; 17169 } 17170 } 17171 } 17172 ClsFields[i]->setLexicalDeclContext(CDecl); 17173 CDecl->addDecl(ClsFields[i]); 17174 } 17175 CDecl->setIvarLBraceLoc(LBrac); 17176 CDecl->setIvarRBraceLoc(RBrac); 17177 } 17178 } 17179 } 17180 17181 /// Determine whether the given integral value is representable within 17182 /// the given type T. 17183 static bool isRepresentableIntegerValue(ASTContext &Context, 17184 llvm::APSInt &Value, 17185 QualType T) { 17186 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17187 "Integral type required!"); 17188 unsigned BitWidth = Context.getIntWidth(T); 17189 17190 if (Value.isUnsigned() || Value.isNonNegative()) { 17191 if (T->isSignedIntegerOrEnumerationType()) 17192 --BitWidth; 17193 return Value.getActiveBits() <= BitWidth; 17194 } 17195 return Value.getMinSignedBits() <= BitWidth; 17196 } 17197 17198 // Given an integral type, return the next larger integral type 17199 // (or a NULL type of no such type exists). 17200 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17201 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17202 // enum checking below. 17203 assert((T->isIntegralType(Context) || 17204 T->isEnumeralType()) && "Integral type required!"); 17205 const unsigned NumTypes = 4; 17206 QualType SignedIntegralTypes[NumTypes] = { 17207 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17208 }; 17209 QualType UnsignedIntegralTypes[NumTypes] = { 17210 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17211 Context.UnsignedLongLongTy 17212 }; 17213 17214 unsigned BitWidth = Context.getTypeSize(T); 17215 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17216 : UnsignedIntegralTypes; 17217 for (unsigned I = 0; I != NumTypes; ++I) 17218 if (Context.getTypeSize(Types[I]) > BitWidth) 17219 return Types[I]; 17220 17221 return QualType(); 17222 } 17223 17224 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17225 EnumConstantDecl *LastEnumConst, 17226 SourceLocation IdLoc, 17227 IdentifierInfo *Id, 17228 Expr *Val) { 17229 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17230 llvm::APSInt EnumVal(IntWidth); 17231 QualType EltTy; 17232 17233 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17234 Val = nullptr; 17235 17236 if (Val) 17237 Val = DefaultLvalueConversion(Val).get(); 17238 17239 if (Val) { 17240 if (Enum->isDependentType() || Val->isTypeDependent()) 17241 EltTy = Context.DependentTy; 17242 else { 17243 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17244 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17245 // constant-expression in the enumerator-definition shall be a converted 17246 // constant expression of the underlying type. 17247 EltTy = Enum->getIntegerType(); 17248 ExprResult Converted = 17249 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17250 CCEK_Enumerator); 17251 if (Converted.isInvalid()) 17252 Val = nullptr; 17253 else 17254 Val = Converted.get(); 17255 } else if (!Val->isValueDependent() && 17256 !(Val = VerifyIntegerConstantExpression(Val, 17257 &EnumVal).get())) { 17258 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17259 } else { 17260 if (Enum->isComplete()) { 17261 EltTy = Enum->getIntegerType(); 17262 17263 // In Obj-C and Microsoft mode, require the enumeration value to be 17264 // representable in the underlying type of the enumeration. In C++11, 17265 // we perform a non-narrowing conversion as part of converted constant 17266 // expression checking. 17267 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17268 if (Context.getTargetInfo() 17269 .getTriple() 17270 .isWindowsMSVCEnvironment()) { 17271 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17272 } else { 17273 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17274 } 17275 } 17276 17277 // Cast to the underlying type. 17278 Val = ImpCastExprToType(Val, EltTy, 17279 EltTy->isBooleanType() ? CK_IntegralToBoolean 17280 : CK_IntegralCast) 17281 .get(); 17282 } else if (getLangOpts().CPlusPlus) { 17283 // C++11 [dcl.enum]p5: 17284 // If the underlying type is not fixed, the type of each enumerator 17285 // is the type of its initializing value: 17286 // - If an initializer is specified for an enumerator, the 17287 // initializing value has the same type as the expression. 17288 EltTy = Val->getType(); 17289 } else { 17290 // C99 6.7.2.2p2: 17291 // The expression that defines the value of an enumeration constant 17292 // shall be an integer constant expression that has a value 17293 // representable as an int. 17294 17295 // Complain if the value is not representable in an int. 17296 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17297 Diag(IdLoc, diag::ext_enum_value_not_int) 17298 << EnumVal.toString(10) << Val->getSourceRange() 17299 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17300 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17301 // Force the type of the expression to 'int'. 17302 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17303 } 17304 EltTy = Val->getType(); 17305 } 17306 } 17307 } 17308 } 17309 17310 if (!Val) { 17311 if (Enum->isDependentType()) 17312 EltTy = Context.DependentTy; 17313 else if (!LastEnumConst) { 17314 // C++0x [dcl.enum]p5: 17315 // If the underlying type is not fixed, the type of each enumerator 17316 // is the type of its initializing value: 17317 // - If no initializer is specified for the first enumerator, the 17318 // initializing value has an unspecified integral type. 17319 // 17320 // GCC uses 'int' for its unspecified integral type, as does 17321 // C99 6.7.2.2p3. 17322 if (Enum->isFixed()) { 17323 EltTy = Enum->getIntegerType(); 17324 } 17325 else { 17326 EltTy = Context.IntTy; 17327 } 17328 } else { 17329 // Assign the last value + 1. 17330 EnumVal = LastEnumConst->getInitVal(); 17331 ++EnumVal; 17332 EltTy = LastEnumConst->getType(); 17333 17334 // Check for overflow on increment. 17335 if (EnumVal < LastEnumConst->getInitVal()) { 17336 // C++0x [dcl.enum]p5: 17337 // If the underlying type is not fixed, the type of each enumerator 17338 // is the type of its initializing value: 17339 // 17340 // - Otherwise the type of the initializing value is the same as 17341 // the type of the initializing value of the preceding enumerator 17342 // unless the incremented value is not representable in that type, 17343 // in which case the type is an unspecified integral type 17344 // sufficient to contain the incremented value. If no such type 17345 // exists, the program is ill-formed. 17346 QualType T = getNextLargerIntegralType(Context, EltTy); 17347 if (T.isNull() || Enum->isFixed()) { 17348 // There is no integral type larger enough to represent this 17349 // value. Complain, then allow the value to wrap around. 17350 EnumVal = LastEnumConst->getInitVal(); 17351 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17352 ++EnumVal; 17353 if (Enum->isFixed()) 17354 // When the underlying type is fixed, this is ill-formed. 17355 Diag(IdLoc, diag::err_enumerator_wrapped) 17356 << EnumVal.toString(10) 17357 << EltTy; 17358 else 17359 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17360 << EnumVal.toString(10); 17361 } else { 17362 EltTy = T; 17363 } 17364 17365 // Retrieve the last enumerator's value, extent that type to the 17366 // type that is supposed to be large enough to represent the incremented 17367 // value, then increment. 17368 EnumVal = LastEnumConst->getInitVal(); 17369 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17370 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17371 ++EnumVal; 17372 17373 // If we're not in C++, diagnose the overflow of enumerator values, 17374 // which in C99 means that the enumerator value is not representable in 17375 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17376 // permits enumerator values that are representable in some larger 17377 // integral type. 17378 if (!getLangOpts().CPlusPlus && !T.isNull()) 17379 Diag(IdLoc, diag::warn_enum_value_overflow); 17380 } else if (!getLangOpts().CPlusPlus && 17381 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17382 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17383 Diag(IdLoc, diag::ext_enum_value_not_int) 17384 << EnumVal.toString(10) << 1; 17385 } 17386 } 17387 } 17388 17389 if (!EltTy->isDependentType()) { 17390 // Make the enumerator value match the signedness and size of the 17391 // enumerator's type. 17392 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17393 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17394 } 17395 17396 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17397 Val, EnumVal); 17398 } 17399 17400 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17401 SourceLocation IILoc) { 17402 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17403 !getLangOpts().CPlusPlus) 17404 return SkipBodyInfo(); 17405 17406 // We have an anonymous enum definition. Look up the first enumerator to 17407 // determine if we should merge the definition with an existing one and 17408 // skip the body. 17409 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17410 forRedeclarationInCurContext()); 17411 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17412 if (!PrevECD) 17413 return SkipBodyInfo(); 17414 17415 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17416 NamedDecl *Hidden; 17417 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17418 SkipBodyInfo Skip; 17419 Skip.Previous = Hidden; 17420 return Skip; 17421 } 17422 17423 return SkipBodyInfo(); 17424 } 17425 17426 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17427 SourceLocation IdLoc, IdentifierInfo *Id, 17428 const ParsedAttributesView &Attrs, 17429 SourceLocation EqualLoc, Expr *Val) { 17430 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17431 EnumConstantDecl *LastEnumConst = 17432 cast_or_null<EnumConstantDecl>(lastEnumConst); 17433 17434 // The scope passed in may not be a decl scope. Zip up the scope tree until 17435 // we find one that is. 17436 S = getNonFieldDeclScope(S); 17437 17438 // Verify that there isn't already something declared with this name in this 17439 // scope. 17440 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17441 LookupName(R, S); 17442 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17443 17444 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17445 // Maybe we will complain about the shadowed template parameter. 17446 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17447 // Just pretend that we didn't see the previous declaration. 17448 PrevDecl = nullptr; 17449 } 17450 17451 // C++ [class.mem]p15: 17452 // If T is the name of a class, then each of the following shall have a name 17453 // different from T: 17454 // - every enumerator of every member of class T that is an unscoped 17455 // enumerated type 17456 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17457 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17458 DeclarationNameInfo(Id, IdLoc)); 17459 17460 EnumConstantDecl *New = 17461 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17462 if (!New) 17463 return nullptr; 17464 17465 if (PrevDecl) { 17466 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17467 // Check for other kinds of shadowing not already handled. 17468 CheckShadow(New, PrevDecl, R); 17469 } 17470 17471 // When in C++, we may get a TagDecl with the same name; in this case the 17472 // enum constant will 'hide' the tag. 17473 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17474 "Received TagDecl when not in C++!"); 17475 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17476 if (isa<EnumConstantDecl>(PrevDecl)) 17477 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17478 else 17479 Diag(IdLoc, diag::err_redefinition) << Id; 17480 notePreviousDefinition(PrevDecl, IdLoc); 17481 return nullptr; 17482 } 17483 } 17484 17485 // Process attributes. 17486 ProcessDeclAttributeList(S, New, Attrs); 17487 AddPragmaAttributes(S, New); 17488 17489 // Register this decl in the current scope stack. 17490 New->setAccess(TheEnumDecl->getAccess()); 17491 PushOnScopeChains(New, S); 17492 17493 ActOnDocumentableDecl(New); 17494 17495 return New; 17496 } 17497 17498 // Returns true when the enum initial expression does not trigger the 17499 // duplicate enum warning. A few common cases are exempted as follows: 17500 // Element2 = Element1 17501 // Element2 = Element1 + 1 17502 // Element2 = Element1 - 1 17503 // Where Element2 and Element1 are from the same enum. 17504 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17505 Expr *InitExpr = ECD->getInitExpr(); 17506 if (!InitExpr) 17507 return true; 17508 InitExpr = InitExpr->IgnoreImpCasts(); 17509 17510 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17511 if (!BO->isAdditiveOp()) 17512 return true; 17513 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17514 if (!IL) 17515 return true; 17516 if (IL->getValue() != 1) 17517 return true; 17518 17519 InitExpr = BO->getLHS(); 17520 } 17521 17522 // This checks if the elements are from the same enum. 17523 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17524 if (!DRE) 17525 return true; 17526 17527 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17528 if (!EnumConstant) 17529 return true; 17530 17531 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17532 Enum) 17533 return true; 17534 17535 return false; 17536 } 17537 17538 // Emits a warning when an element is implicitly set a value that 17539 // a previous element has already been set to. 17540 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17541 EnumDecl *Enum, QualType EnumType) { 17542 // Avoid anonymous enums 17543 if (!Enum->getIdentifier()) 17544 return; 17545 17546 // Only check for small enums. 17547 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17548 return; 17549 17550 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17551 return; 17552 17553 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17554 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17555 17556 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17557 17558 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17559 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17560 17561 // Use int64_t as a key to avoid needing special handling for map keys. 17562 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17563 llvm::APSInt Val = D->getInitVal(); 17564 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17565 }; 17566 17567 DuplicatesVector DupVector; 17568 ValueToVectorMap EnumMap; 17569 17570 // Populate the EnumMap with all values represented by enum constants without 17571 // an initializer. 17572 for (auto *Element : Elements) { 17573 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17574 17575 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17576 // this constant. Skip this enum since it may be ill-formed. 17577 if (!ECD) { 17578 return; 17579 } 17580 17581 // Constants with initalizers are handled in the next loop. 17582 if (ECD->getInitExpr()) 17583 continue; 17584 17585 // Duplicate values are handled in the next loop. 17586 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17587 } 17588 17589 if (EnumMap.size() == 0) 17590 return; 17591 17592 // Create vectors for any values that has duplicates. 17593 for (auto *Element : Elements) { 17594 // The last loop returned if any constant was null. 17595 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17596 if (!ValidDuplicateEnum(ECD, Enum)) 17597 continue; 17598 17599 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17600 if (Iter == EnumMap.end()) 17601 continue; 17602 17603 DeclOrVector& Entry = Iter->second; 17604 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17605 // Ensure constants are different. 17606 if (D == ECD) 17607 continue; 17608 17609 // Create new vector and push values onto it. 17610 auto Vec = std::make_unique<ECDVector>(); 17611 Vec->push_back(D); 17612 Vec->push_back(ECD); 17613 17614 // Update entry to point to the duplicates vector. 17615 Entry = Vec.get(); 17616 17617 // Store the vector somewhere we can consult later for quick emission of 17618 // diagnostics. 17619 DupVector.emplace_back(std::move(Vec)); 17620 continue; 17621 } 17622 17623 ECDVector *Vec = Entry.get<ECDVector*>(); 17624 // Make sure constants are not added more than once. 17625 if (*Vec->begin() == ECD) 17626 continue; 17627 17628 Vec->push_back(ECD); 17629 } 17630 17631 // Emit diagnostics. 17632 for (const auto &Vec : DupVector) { 17633 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17634 17635 // Emit warning for one enum constant. 17636 auto *FirstECD = Vec->front(); 17637 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17638 << FirstECD << FirstECD->getInitVal().toString(10) 17639 << FirstECD->getSourceRange(); 17640 17641 // Emit one note for each of the remaining enum constants with 17642 // the same value. 17643 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17644 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17645 << ECD << ECD->getInitVal().toString(10) 17646 << ECD->getSourceRange(); 17647 } 17648 } 17649 17650 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17651 bool AllowMask) const { 17652 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17653 assert(ED->isCompleteDefinition() && "expected enum definition"); 17654 17655 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17656 llvm::APInt &FlagBits = R.first->second; 17657 17658 if (R.second) { 17659 for (auto *E : ED->enumerators()) { 17660 const auto &EVal = E->getInitVal(); 17661 // Only single-bit enumerators introduce new flag values. 17662 if (EVal.isPowerOf2()) 17663 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17664 } 17665 } 17666 17667 // A value is in a flag enum if either its bits are a subset of the enum's 17668 // flag bits (the first condition) or we are allowing masks and the same is 17669 // true of its complement (the second condition). When masks are allowed, we 17670 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17671 // 17672 // While it's true that any value could be used as a mask, the assumption is 17673 // that a mask will have all of the insignificant bits set. Anything else is 17674 // likely a logic error. 17675 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17676 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17677 } 17678 17679 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17680 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17681 const ParsedAttributesView &Attrs) { 17682 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17683 QualType EnumType = Context.getTypeDeclType(Enum); 17684 17685 ProcessDeclAttributeList(S, Enum, Attrs); 17686 17687 if (Enum->isDependentType()) { 17688 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17689 EnumConstantDecl *ECD = 17690 cast_or_null<EnumConstantDecl>(Elements[i]); 17691 if (!ECD) continue; 17692 17693 ECD->setType(EnumType); 17694 } 17695 17696 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17697 return; 17698 } 17699 17700 // TODO: If the result value doesn't fit in an int, it must be a long or long 17701 // long value. ISO C does not support this, but GCC does as an extension, 17702 // emit a warning. 17703 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17704 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17705 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17706 17707 // Verify that all the values are okay, compute the size of the values, and 17708 // reverse the list. 17709 unsigned NumNegativeBits = 0; 17710 unsigned NumPositiveBits = 0; 17711 17712 // Keep track of whether all elements have type int. 17713 bool AllElementsInt = true; 17714 17715 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17716 EnumConstantDecl *ECD = 17717 cast_or_null<EnumConstantDecl>(Elements[i]); 17718 if (!ECD) continue; // Already issued a diagnostic. 17719 17720 const llvm::APSInt &InitVal = ECD->getInitVal(); 17721 17722 // Keep track of the size of positive and negative values. 17723 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17724 NumPositiveBits = std::max(NumPositiveBits, 17725 (unsigned)InitVal.getActiveBits()); 17726 else 17727 NumNegativeBits = std::max(NumNegativeBits, 17728 (unsigned)InitVal.getMinSignedBits()); 17729 17730 // Keep track of whether every enum element has type int (very common). 17731 if (AllElementsInt) 17732 AllElementsInt = ECD->getType() == Context.IntTy; 17733 } 17734 17735 // Figure out the type that should be used for this enum. 17736 QualType BestType; 17737 unsigned BestWidth; 17738 17739 // C++0x N3000 [conv.prom]p3: 17740 // An rvalue of an unscoped enumeration type whose underlying 17741 // type is not fixed can be converted to an rvalue of the first 17742 // of the following types that can represent all the values of 17743 // the enumeration: int, unsigned int, long int, unsigned long 17744 // int, long long int, or unsigned long long int. 17745 // C99 6.4.4.3p2: 17746 // An identifier declared as an enumeration constant has type int. 17747 // The C99 rule is modified by a gcc extension 17748 QualType BestPromotionType; 17749 17750 bool Packed = Enum->hasAttr<PackedAttr>(); 17751 // -fshort-enums is the equivalent to specifying the packed attribute on all 17752 // enum definitions. 17753 if (LangOpts.ShortEnums) 17754 Packed = true; 17755 17756 // If the enum already has a type because it is fixed or dictated by the 17757 // target, promote that type instead of analyzing the enumerators. 17758 if (Enum->isComplete()) { 17759 BestType = Enum->getIntegerType(); 17760 if (BestType->isPromotableIntegerType()) 17761 BestPromotionType = Context.getPromotedIntegerType(BestType); 17762 else 17763 BestPromotionType = BestType; 17764 17765 BestWidth = Context.getIntWidth(BestType); 17766 } 17767 else if (NumNegativeBits) { 17768 // If there is a negative value, figure out the smallest integer type (of 17769 // int/long/longlong) that fits. 17770 // If it's packed, check also if it fits a char or a short. 17771 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17772 BestType = Context.SignedCharTy; 17773 BestWidth = CharWidth; 17774 } else if (Packed && NumNegativeBits <= ShortWidth && 17775 NumPositiveBits < ShortWidth) { 17776 BestType = Context.ShortTy; 17777 BestWidth = ShortWidth; 17778 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17779 BestType = Context.IntTy; 17780 BestWidth = IntWidth; 17781 } else { 17782 BestWidth = Context.getTargetInfo().getLongWidth(); 17783 17784 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17785 BestType = Context.LongTy; 17786 } else { 17787 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17788 17789 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17790 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17791 BestType = Context.LongLongTy; 17792 } 17793 } 17794 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17795 } else { 17796 // If there is no negative value, figure out the smallest type that fits 17797 // all of the enumerator values. 17798 // If it's packed, check also if it fits a char or a short. 17799 if (Packed && NumPositiveBits <= CharWidth) { 17800 BestType = Context.UnsignedCharTy; 17801 BestPromotionType = Context.IntTy; 17802 BestWidth = CharWidth; 17803 } else if (Packed && NumPositiveBits <= ShortWidth) { 17804 BestType = Context.UnsignedShortTy; 17805 BestPromotionType = Context.IntTy; 17806 BestWidth = ShortWidth; 17807 } else if (NumPositiveBits <= IntWidth) { 17808 BestType = Context.UnsignedIntTy; 17809 BestWidth = IntWidth; 17810 BestPromotionType 17811 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17812 ? Context.UnsignedIntTy : Context.IntTy; 17813 } else if (NumPositiveBits <= 17814 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17815 BestType = Context.UnsignedLongTy; 17816 BestPromotionType 17817 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17818 ? Context.UnsignedLongTy : Context.LongTy; 17819 } else { 17820 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17821 assert(NumPositiveBits <= BestWidth && 17822 "How could an initializer get larger than ULL?"); 17823 BestType = Context.UnsignedLongLongTy; 17824 BestPromotionType 17825 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17826 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17827 } 17828 } 17829 17830 // Loop over all of the enumerator constants, changing their types to match 17831 // the type of the enum if needed. 17832 for (auto *D : Elements) { 17833 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17834 if (!ECD) continue; // Already issued a diagnostic. 17835 17836 // Standard C says the enumerators have int type, but we allow, as an 17837 // extension, the enumerators to be larger than int size. If each 17838 // enumerator value fits in an int, type it as an int, otherwise type it the 17839 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17840 // that X has type 'int', not 'unsigned'. 17841 17842 // Determine whether the value fits into an int. 17843 llvm::APSInt InitVal = ECD->getInitVal(); 17844 17845 // If it fits into an integer type, force it. Otherwise force it to match 17846 // the enum decl type. 17847 QualType NewTy; 17848 unsigned NewWidth; 17849 bool NewSign; 17850 if (!getLangOpts().CPlusPlus && 17851 !Enum->isFixed() && 17852 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17853 NewTy = Context.IntTy; 17854 NewWidth = IntWidth; 17855 NewSign = true; 17856 } else if (ECD->getType() == BestType) { 17857 // Already the right type! 17858 if (getLangOpts().CPlusPlus) 17859 // C++ [dcl.enum]p4: Following the closing brace of an 17860 // enum-specifier, each enumerator has the type of its 17861 // enumeration. 17862 ECD->setType(EnumType); 17863 continue; 17864 } else { 17865 NewTy = BestType; 17866 NewWidth = BestWidth; 17867 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17868 } 17869 17870 // Adjust the APSInt value. 17871 InitVal = InitVal.extOrTrunc(NewWidth); 17872 InitVal.setIsSigned(NewSign); 17873 ECD->setInitVal(InitVal); 17874 17875 // Adjust the Expr initializer and type. 17876 if (ECD->getInitExpr() && 17877 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17878 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17879 CK_IntegralCast, 17880 ECD->getInitExpr(), 17881 /*base paths*/ nullptr, 17882 VK_RValue)); 17883 if (getLangOpts().CPlusPlus) 17884 // C++ [dcl.enum]p4: Following the closing brace of an 17885 // enum-specifier, each enumerator has the type of its 17886 // enumeration. 17887 ECD->setType(EnumType); 17888 else 17889 ECD->setType(NewTy); 17890 } 17891 17892 Enum->completeDefinition(BestType, BestPromotionType, 17893 NumPositiveBits, NumNegativeBits); 17894 17895 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17896 17897 if (Enum->isClosedFlag()) { 17898 for (Decl *D : Elements) { 17899 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17900 if (!ECD) continue; // Already issued a diagnostic. 17901 17902 llvm::APSInt InitVal = ECD->getInitVal(); 17903 if (InitVal != 0 && !InitVal.isPowerOf2() && 17904 !IsValueInFlagEnum(Enum, InitVal, true)) 17905 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17906 << ECD << Enum; 17907 } 17908 } 17909 17910 // Now that the enum type is defined, ensure it's not been underaligned. 17911 if (Enum->hasAttrs()) 17912 CheckAlignasUnderalignment(Enum); 17913 } 17914 17915 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17916 SourceLocation StartLoc, 17917 SourceLocation EndLoc) { 17918 StringLiteral *AsmString = cast<StringLiteral>(expr); 17919 17920 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17921 AsmString, StartLoc, 17922 EndLoc); 17923 CurContext->addDecl(New); 17924 return New; 17925 } 17926 17927 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17928 IdentifierInfo* AliasName, 17929 SourceLocation PragmaLoc, 17930 SourceLocation NameLoc, 17931 SourceLocation AliasNameLoc) { 17932 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17933 LookupOrdinaryName); 17934 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17935 AttributeCommonInfo::AS_Pragma); 17936 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 17937 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 17938 17939 // If a declaration that: 17940 // 1) declares a function or a variable 17941 // 2) has external linkage 17942 // already exists, add a label attribute to it. 17943 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17944 if (isDeclExternC(PrevDecl)) 17945 PrevDecl->addAttr(Attr); 17946 else 17947 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17948 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17949 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17950 } else 17951 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17952 } 17953 17954 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17955 SourceLocation PragmaLoc, 17956 SourceLocation NameLoc) { 17957 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17958 17959 if (PrevDecl) { 17960 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17961 } else { 17962 (void)WeakUndeclaredIdentifiers.insert( 17963 std::pair<IdentifierInfo*,WeakInfo> 17964 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17965 } 17966 } 17967 17968 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17969 IdentifierInfo* AliasName, 17970 SourceLocation PragmaLoc, 17971 SourceLocation NameLoc, 17972 SourceLocation AliasNameLoc) { 17973 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17974 LookupOrdinaryName); 17975 WeakInfo W = WeakInfo(Name, NameLoc); 17976 17977 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17978 if (!PrevDecl->hasAttr<AliasAttr>()) 17979 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17980 DeclApplyPragmaWeak(TUScope, ND, W); 17981 } else { 17982 (void)WeakUndeclaredIdentifiers.insert( 17983 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17984 } 17985 } 17986 17987 Decl *Sema::getObjCDeclContext() const { 17988 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17989 } 17990 17991 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { 17992 // Templates are emitted when they're instantiated. 17993 if (FD->isDependentContext()) 17994 return FunctionEmissionStatus::TemplateDiscarded; 17995 17996 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 17997 if (LangOpts.OpenMPIsDevice) { 17998 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17999 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18000 if (DevTy.hasValue()) { 18001 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18002 OMPES = FunctionEmissionStatus::OMPDiscarded; 18003 else if (DeviceKnownEmittedFns.count(FD) > 0) 18004 OMPES = FunctionEmissionStatus::Emitted; 18005 } 18006 } else if (LangOpts.OpenMP) { 18007 // In OpenMP 4.5 all the functions are host functions. 18008 if (LangOpts.OpenMP <= 45) { 18009 OMPES = FunctionEmissionStatus::Emitted; 18010 } else { 18011 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18012 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18013 // In OpenMP 5.0 or above, DevTy may be changed later by 18014 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18015 // having no value does not imply host. The emission status will be 18016 // checked again at the end of compilation unit. 18017 if (DevTy.hasValue()) { 18018 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18019 OMPES = FunctionEmissionStatus::OMPDiscarded; 18020 } else if (DeviceKnownEmittedFns.count(FD) > 0) { 18021 OMPES = FunctionEmissionStatus::Emitted; 18022 } 18023 } 18024 } 18025 } 18026 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18027 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18028 return OMPES; 18029 18030 if (LangOpts.CUDA) { 18031 // When compiling for device, host functions are never emitted. Similarly, 18032 // when compiling for host, device and global functions are never emitted. 18033 // (Technically, we do emit a host-side stub for global functions, but this 18034 // doesn't count for our purposes here.) 18035 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18036 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18037 return FunctionEmissionStatus::CUDADiscarded; 18038 if (!LangOpts.CUDAIsDevice && 18039 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18040 return FunctionEmissionStatus::CUDADiscarded; 18041 18042 // Check whether this function is externally visible -- if so, it's 18043 // known-emitted. 18044 // 18045 // We have to check the GVA linkage of the function's *definition* -- if we 18046 // only have a declaration, we don't know whether or not the function will 18047 // be emitted, because (say) the definition could include "inline". 18048 FunctionDecl *Def = FD->getDefinition(); 18049 18050 if (Def && 18051 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18052 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18053 return FunctionEmissionStatus::Emitted; 18054 } 18055 18056 // Otherwise, the function is known-emitted if it's in our set of 18057 // known-emitted functions. 18058 return (DeviceKnownEmittedFns.count(FD) > 0) 18059 ? FunctionEmissionStatus::Emitted 18060 : FunctionEmissionStatus::Unknown; 18061 } 18062 18063 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18064 // Host-side references to a __global__ function refer to the stub, so the 18065 // function itself is never emitted and therefore should not be marked. 18066 // If we have host fn calls kernel fn calls host+device, the HD function 18067 // does not get instantiated on the host. We model this by omitting at the 18068 // call to the kernel from the callgraph. This ensures that, when compiling 18069 // for host, only HD functions actually called from the host get marked as 18070 // known-emitted. 18071 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18072 IdentifyCUDATarget(Callee) == CFT_Global; 18073 } 18074