1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw__Float16: 142 case tok::kw___float128: 143 case tok::kw_wchar_t: 144 case tok::kw_bool: 145 case tok::kw___underlying_type: 146 case tok::kw___auto_type: 147 return true; 148 149 case tok::annot_typename: 150 case tok::kw_char16_t: 151 case tok::kw_char32_t: 152 case tok::kw_typeof: 153 case tok::annot_decltype: 154 case tok::kw_decltype: 155 return getLangOpts().CPlusPlus; 156 157 case tok::kw_char8_t: 158 return getLangOpts().Char8; 159 160 default: 161 break; 162 } 163 164 return false; 165 } 166 167 namespace { 168 enum class UnqualifiedTypeNameLookupResult { 169 NotFound, 170 FoundNonType, 171 FoundType 172 }; 173 } // end anonymous namespace 174 175 /// Tries to perform unqualified lookup of the type decls in bases for 176 /// dependent class. 177 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 178 /// type decl, \a FoundType if only type decls are found. 179 static UnqualifiedTypeNameLookupResult 180 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 181 SourceLocation NameLoc, 182 const CXXRecordDecl *RD) { 183 if (!RD->hasDefinition()) 184 return UnqualifiedTypeNameLookupResult::NotFound; 185 // Look for type decls in base classes. 186 UnqualifiedTypeNameLookupResult FoundTypeDecl = 187 UnqualifiedTypeNameLookupResult::NotFound; 188 for (const auto &Base : RD->bases()) { 189 const CXXRecordDecl *BaseRD = nullptr; 190 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 191 BaseRD = BaseTT->getAsCXXRecordDecl(); 192 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 193 // Look for type decls in dependent base classes that have known primary 194 // templates. 195 if (!TST || !TST->isDependentType()) 196 continue; 197 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 198 if (!TD) 199 continue; 200 if (auto *BasePrimaryTemplate = 201 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 202 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 203 BaseRD = BasePrimaryTemplate; 204 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 205 if (const ClassTemplatePartialSpecializationDecl *PS = 206 CTD->findPartialSpecialization(Base.getType())) 207 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 208 BaseRD = PS; 209 } 210 } 211 } 212 if (BaseRD) { 213 for (NamedDecl *ND : BaseRD->lookup(&II)) { 214 if (!isa<TypeDecl>(ND)) 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 217 } 218 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 219 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 220 case UnqualifiedTypeNameLookupResult::FoundNonType: 221 return UnqualifiedTypeNameLookupResult::FoundNonType; 222 case UnqualifiedTypeNameLookupResult::FoundType: 223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 224 break; 225 case UnqualifiedTypeNameLookupResult::NotFound: 226 break; 227 } 228 } 229 } 230 } 231 232 return FoundTypeDecl; 233 } 234 235 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 236 const IdentifierInfo &II, 237 SourceLocation NameLoc) { 238 // Lookup in the parent class template context, if any. 239 const CXXRecordDecl *RD = nullptr; 240 UnqualifiedTypeNameLookupResult FoundTypeDecl = 241 UnqualifiedTypeNameLookupResult::NotFound; 242 for (DeclContext *DC = S.CurContext; 243 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 244 DC = DC->getParent()) { 245 // Look for type decls in dependent base classes that have known primary 246 // templates. 247 RD = dyn_cast<CXXRecordDecl>(DC); 248 if (RD && RD->getDescribedClassTemplate()) 249 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 250 } 251 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 252 return nullptr; 253 254 // We found some types in dependent base classes. Recover as if the user 255 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 256 // lookup during template instantiation. 257 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 258 259 ASTContext &Context = S.Context; 260 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 261 cast<Type>(Context.getRecordType(RD))); 262 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 263 264 CXXScopeSpec SS; 265 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 266 267 TypeLocBuilder Builder; 268 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 269 DepTL.setNameLoc(NameLoc); 270 DepTL.setElaboratedKeywordLoc(SourceLocation()); 271 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 272 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 273 } 274 275 /// If the identifier refers to a type name within this scope, 276 /// return the declaration of that type. 277 /// 278 /// This routine performs ordinary name lookup of the identifier II 279 /// within the given scope, with optional C++ scope specifier SS, to 280 /// determine whether the name refers to a type. If so, returns an 281 /// opaque pointer (actually a QualType) corresponding to that 282 /// type. Otherwise, returns NULL. 283 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 284 Scope *S, CXXScopeSpec *SS, 285 bool isClassName, bool HasTrailingDot, 286 ParsedType ObjectTypePtr, 287 bool IsCtorOrDtorName, 288 bool WantNontrivialTypeSourceInfo, 289 bool IsClassTemplateDeductionContext, 290 IdentifierInfo **CorrectedII) { 291 // FIXME: Consider allowing this outside C++1z mode as an extension. 292 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 293 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 294 !isClassName && !HasTrailingDot; 295 296 // Determine where we will perform name lookup. 297 DeclContext *LookupCtx = nullptr; 298 if (ObjectTypePtr) { 299 QualType ObjectType = ObjectTypePtr.get(); 300 if (ObjectType->isRecordType()) 301 LookupCtx = computeDeclContext(ObjectType); 302 } else if (SS && SS->isNotEmpty()) { 303 LookupCtx = computeDeclContext(*SS, false); 304 305 if (!LookupCtx) { 306 if (isDependentScopeSpecifier(*SS)) { 307 // C++ [temp.res]p3: 308 // A qualified-id that refers to a type and in which the 309 // nested-name-specifier depends on a template-parameter (14.6.2) 310 // shall be prefixed by the keyword typename to indicate that the 311 // qualified-id denotes a type, forming an 312 // elaborated-type-specifier (7.1.5.3). 313 // 314 // We therefore do not perform any name lookup if the result would 315 // refer to a member of an unknown specialization. 316 if (!isClassName && !IsCtorOrDtorName) 317 return nullptr; 318 319 // We know from the grammar that this name refers to a type, 320 // so build a dependent node to describe the type. 321 if (WantNontrivialTypeSourceInfo) 322 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 323 324 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 325 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 326 II, NameLoc); 327 return ParsedType::make(T); 328 } 329 330 return nullptr; 331 } 332 333 if (!LookupCtx->isDependentContext() && 334 RequireCompleteDeclContext(*SS, LookupCtx)) 335 return nullptr; 336 } 337 338 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 339 // lookup for class-names. 340 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 341 LookupOrdinaryName; 342 LookupResult Result(*this, &II, NameLoc, Kind); 343 if (LookupCtx) { 344 // Perform "qualified" name lookup into the declaration context we 345 // computed, which is either the type of the base of a member access 346 // expression or the declaration context associated with a prior 347 // nested-name-specifier. 348 LookupQualifiedName(Result, LookupCtx); 349 350 if (ObjectTypePtr && Result.empty()) { 351 // C++ [basic.lookup.classref]p3: 352 // If the unqualified-id is ~type-name, the type-name is looked up 353 // in the context of the entire postfix-expression. If the type T of 354 // the object expression is of a class type C, the type-name is also 355 // looked up in the scope of class C. At least one of the lookups shall 356 // find a name that refers to (possibly cv-qualified) T. 357 LookupName(Result, S); 358 } 359 } else { 360 // Perform unqualified name lookup. 361 LookupName(Result, S); 362 363 // For unqualified lookup in a class template in MSVC mode, look into 364 // dependent base classes where the primary class template is known. 365 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 366 if (ParsedType TypeInBase = 367 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 368 return TypeInBase; 369 } 370 } 371 372 NamedDecl *IIDecl = nullptr; 373 switch (Result.getResultKind()) { 374 case LookupResult::NotFound: 375 case LookupResult::NotFoundInCurrentInstantiation: 376 if (CorrectedII) { 377 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 378 AllowDeducedTemplate); 379 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 380 S, SS, CCC, CTK_ErrorRecovery); 381 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 382 TemplateTy Template; 383 bool MemberOfUnknownSpecialization; 384 UnqualifiedId TemplateName; 385 TemplateName.setIdentifier(NewII, NameLoc); 386 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 387 CXXScopeSpec NewSS, *NewSSPtr = SS; 388 if (SS && NNS) { 389 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 390 NewSSPtr = &NewSS; 391 } 392 if (Correction && (NNS || NewII != &II) && 393 // Ignore a correction to a template type as the to-be-corrected 394 // identifier is not a template (typo correction for template names 395 // is handled elsewhere). 396 !(getLangOpts().CPlusPlus && NewSSPtr && 397 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 398 Template, MemberOfUnknownSpecialization))) { 399 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 400 isClassName, HasTrailingDot, ObjectTypePtr, 401 IsCtorOrDtorName, 402 WantNontrivialTypeSourceInfo, 403 IsClassTemplateDeductionContext); 404 if (Ty) { 405 diagnoseTypo(Correction, 406 PDiag(diag::err_unknown_type_or_class_name_suggest) 407 << Result.getLookupName() << isClassName); 408 if (SS && NNS) 409 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 410 *CorrectedII = NewII; 411 return Ty; 412 } 413 } 414 } 415 // If typo correction failed or was not performed, fall through 416 LLVM_FALLTHROUGH; 417 case LookupResult::FoundOverloaded: 418 case LookupResult::FoundUnresolvedValue: 419 Result.suppressDiagnostics(); 420 return nullptr; 421 422 case LookupResult::Ambiguous: 423 // Recover from type-hiding ambiguities by hiding the type. We'll 424 // do the lookup again when looking for an object, and we can 425 // diagnose the error then. If we don't do this, then the error 426 // about hiding the type will be immediately followed by an error 427 // that only makes sense if the identifier was treated like a type. 428 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 429 Result.suppressDiagnostics(); 430 return nullptr; 431 } 432 433 // Look to see if we have a type anywhere in the list of results. 434 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 435 Res != ResEnd; ++Res) { 436 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 437 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 438 if (!IIDecl || 439 (*Res)->getLocation().getRawEncoding() < 440 IIDecl->getLocation().getRawEncoding()) 441 IIDecl = *Res; 442 } 443 } 444 445 if (!IIDecl) { 446 // None of the entities we found is a type, so there is no way 447 // to even assume that the result is a type. In this case, don't 448 // complain about the ambiguity. The parser will either try to 449 // perform this lookup again (e.g., as an object name), which 450 // will produce the ambiguity, or will complain that it expected 451 // a type name. 452 Result.suppressDiagnostics(); 453 return nullptr; 454 } 455 456 // We found a type within the ambiguous lookup; diagnose the 457 // ambiguity and then return that type. This might be the right 458 // answer, or it might not be, but it suppresses any attempt to 459 // perform the name lookup again. 460 break; 461 462 case LookupResult::Found: 463 IIDecl = Result.getFoundDecl(); 464 break; 465 } 466 467 assert(IIDecl && "Didn't find decl"); 468 469 QualType T; 470 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 471 // C++ [class.qual]p2: A lookup that would find the injected-class-name 472 // instead names the constructors of the class, except when naming a class. 473 // This is ill-formed when we're not actually forming a ctor or dtor name. 474 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 475 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 476 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 477 FoundRD->isInjectedClassName() && 478 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 479 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 480 << &II << /*Type*/1; 481 482 DiagnoseUseOfDecl(IIDecl, NameLoc); 483 484 T = Context.getTypeDeclType(TD); 485 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 486 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 487 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 488 if (!HasTrailingDot) 489 T = Context.getObjCInterfaceType(IDecl); 490 } else if (AllowDeducedTemplate) { 491 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 492 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 493 QualType(), false); 494 } 495 496 if (T.isNull()) { 497 // If it's not plausibly a type, suppress diagnostics. 498 Result.suppressDiagnostics(); 499 return nullptr; 500 } 501 502 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 503 // constructor or destructor name (in such a case, the scope specifier 504 // will be attached to the enclosing Expr or Decl node). 505 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 506 !isa<ObjCInterfaceDecl>(IIDecl)) { 507 if (WantNontrivialTypeSourceInfo) { 508 // Construct a type with type-source information. 509 TypeLocBuilder Builder; 510 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 511 512 T = getElaboratedType(ETK_None, *SS, T); 513 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 514 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 515 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 516 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 517 } else { 518 T = getElaboratedType(ETK_None, *SS, T); 519 } 520 } 521 522 return ParsedType::make(T); 523 } 524 525 // Builds a fake NNS for the given decl context. 526 static NestedNameSpecifier * 527 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 528 for (;; DC = DC->getLookupParent()) { 529 DC = DC->getPrimaryContext(); 530 auto *ND = dyn_cast<NamespaceDecl>(DC); 531 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 532 return NestedNameSpecifier::Create(Context, nullptr, ND); 533 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 534 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 535 RD->getTypeForDecl()); 536 else if (isa<TranslationUnitDecl>(DC)) 537 return NestedNameSpecifier::GlobalSpecifier(Context); 538 } 539 llvm_unreachable("something isn't in TU scope?"); 540 } 541 542 /// Find the parent class with dependent bases of the innermost enclosing method 543 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 544 /// up allowing unqualified dependent type names at class-level, which MSVC 545 /// correctly rejects. 546 static const CXXRecordDecl * 547 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 548 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 549 DC = DC->getPrimaryContext(); 550 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 551 if (MD->getParent()->hasAnyDependentBases()) 552 return MD->getParent(); 553 } 554 return nullptr; 555 } 556 557 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 558 SourceLocation NameLoc, 559 bool IsTemplateTypeArg) { 560 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 561 562 NestedNameSpecifier *NNS = nullptr; 563 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 564 // If we weren't able to parse a default template argument, delay lookup 565 // until instantiation time by making a non-dependent DependentTypeName. We 566 // pretend we saw a NestedNameSpecifier referring to the current scope, and 567 // lookup is retried. 568 // FIXME: This hurts our diagnostic quality, since we get errors like "no 569 // type named 'Foo' in 'current_namespace'" when the user didn't write any 570 // name specifiers. 571 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 572 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 573 } else if (const CXXRecordDecl *RD = 574 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 575 // Build a DependentNameType that will perform lookup into RD at 576 // instantiation time. 577 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 578 RD->getTypeForDecl()); 579 580 // Diagnose that this identifier was undeclared, and retry the lookup during 581 // template instantiation. 582 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 583 << RD; 584 } else { 585 // This is not a situation that we should recover from. 586 return ParsedType(); 587 } 588 589 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 590 591 // Build type location information. We synthesized the qualifier, so we have 592 // to build a fake NestedNameSpecifierLoc. 593 NestedNameSpecifierLocBuilder NNSLocBuilder; 594 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 595 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 596 597 TypeLocBuilder Builder; 598 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 599 DepTL.setNameLoc(NameLoc); 600 DepTL.setElaboratedKeywordLoc(SourceLocation()); 601 DepTL.setQualifierLoc(QualifierLoc); 602 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 603 } 604 605 /// isTagName() - This method is called *for error recovery purposes only* 606 /// to determine if the specified name is a valid tag name ("struct foo"). If 607 /// so, this returns the TST for the tag corresponding to it (TST_enum, 608 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 609 /// cases in C where the user forgot to specify the tag. 610 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 611 // Do a tag name lookup in this scope. 612 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 613 LookupName(R, S, false); 614 R.suppressDiagnostics(); 615 if (R.getResultKind() == LookupResult::Found) 616 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 617 switch (TD->getTagKind()) { 618 case TTK_Struct: return DeclSpec::TST_struct; 619 case TTK_Interface: return DeclSpec::TST_interface; 620 case TTK_Union: return DeclSpec::TST_union; 621 case TTK_Class: return DeclSpec::TST_class; 622 case TTK_Enum: return DeclSpec::TST_enum; 623 } 624 } 625 626 return DeclSpec::TST_unspecified; 627 } 628 629 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 630 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 631 /// then downgrade the missing typename error to a warning. 632 /// This is needed for MSVC compatibility; Example: 633 /// @code 634 /// template<class T> class A { 635 /// public: 636 /// typedef int TYPE; 637 /// }; 638 /// template<class T> class B : public A<T> { 639 /// public: 640 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 641 /// }; 642 /// @endcode 643 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 644 if (CurContext->isRecord()) { 645 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 646 return true; 647 648 const Type *Ty = SS->getScopeRep()->getAsType(); 649 650 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 651 for (const auto &Base : RD->bases()) 652 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 653 return true; 654 return S->isFunctionPrototypeScope(); 655 } 656 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 657 } 658 659 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 660 SourceLocation IILoc, 661 Scope *S, 662 CXXScopeSpec *SS, 663 ParsedType &SuggestedType, 664 bool IsTemplateName) { 665 // Don't report typename errors for editor placeholders. 666 if (II->isEditorPlaceholder()) 667 return; 668 // We don't have anything to suggest (yet). 669 SuggestedType = nullptr; 670 671 // There may have been a typo in the name of the type. Look up typo 672 // results, in case we have something that we can suggest. 673 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 674 /*AllowTemplates=*/IsTemplateName, 675 /*AllowNonTemplates=*/!IsTemplateName); 676 if (TypoCorrection Corrected = 677 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 678 CCC, CTK_ErrorRecovery)) { 679 // FIXME: Support error recovery for the template-name case. 680 bool CanRecover = !IsTemplateName; 681 if (Corrected.isKeyword()) { 682 // We corrected to a keyword. 683 diagnoseTypo(Corrected, 684 PDiag(IsTemplateName ? diag::err_no_template_suggest 685 : diag::err_unknown_typename_suggest) 686 << II); 687 II = Corrected.getCorrectionAsIdentifierInfo(); 688 } else { 689 // We found a similarly-named type or interface; suggest that. 690 if (!SS || !SS->isSet()) { 691 diagnoseTypo(Corrected, 692 PDiag(IsTemplateName ? diag::err_no_template_suggest 693 : diag::err_unknown_typename_suggest) 694 << II, CanRecover); 695 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 696 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 697 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 698 II->getName().equals(CorrectedStr); 699 diagnoseTypo(Corrected, 700 PDiag(IsTemplateName 701 ? diag::err_no_member_template_suggest 702 : diag::err_unknown_nested_typename_suggest) 703 << II << DC << DroppedSpecifier << SS->getRange(), 704 CanRecover); 705 } else { 706 llvm_unreachable("could not have corrected a typo here"); 707 } 708 709 if (!CanRecover) 710 return; 711 712 CXXScopeSpec tmpSS; 713 if (Corrected.getCorrectionSpecifier()) 714 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 715 SourceRange(IILoc)); 716 // FIXME: Support class template argument deduction here. 717 SuggestedType = 718 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 719 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 720 /*IsCtorOrDtorName=*/false, 721 /*WantNontrivialTypeSourceInfo=*/true); 722 } 723 return; 724 } 725 726 if (getLangOpts().CPlusPlus && !IsTemplateName) { 727 // See if II is a class template that the user forgot to pass arguments to. 728 UnqualifiedId Name; 729 Name.setIdentifier(II, IILoc); 730 CXXScopeSpec EmptySS; 731 TemplateTy TemplateResult; 732 bool MemberOfUnknownSpecialization; 733 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 734 Name, nullptr, true, TemplateResult, 735 MemberOfUnknownSpecialization) == TNK_Type_template) { 736 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 737 return; 738 } 739 } 740 741 // FIXME: Should we move the logic that tries to recover from a missing tag 742 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 743 744 if (!SS || (!SS->isSet() && !SS->isInvalid())) 745 Diag(IILoc, IsTemplateName ? diag::err_no_template 746 : diag::err_unknown_typename) 747 << II; 748 else if (DeclContext *DC = computeDeclContext(*SS, false)) 749 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 750 : diag::err_typename_nested_not_found) 751 << II << DC << SS->getRange(); 752 else if (isDependentScopeSpecifier(*SS)) { 753 unsigned DiagID = diag::err_typename_missing; 754 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 755 DiagID = diag::ext_typename_missing; 756 757 Diag(SS->getRange().getBegin(), DiagID) 758 << SS->getScopeRep() << II->getName() 759 << SourceRange(SS->getRange().getBegin(), IILoc) 760 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 761 SuggestedType = ActOnTypenameType(S, SourceLocation(), 762 *SS, *II, IILoc).get(); 763 } else { 764 assert(SS && SS->isInvalid() && 765 "Invalid scope specifier has already been diagnosed"); 766 } 767 } 768 769 /// Determine whether the given result set contains either a type name 770 /// or 771 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 772 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 773 NextToken.is(tok::less); 774 775 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 776 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 777 return true; 778 779 if (CheckTemplate && isa<TemplateDecl>(*I)) 780 return true; 781 } 782 783 return false; 784 } 785 786 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 787 Scope *S, CXXScopeSpec &SS, 788 IdentifierInfo *&Name, 789 SourceLocation NameLoc) { 790 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 791 SemaRef.LookupParsedName(R, S, &SS); 792 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 793 StringRef FixItTagName; 794 switch (Tag->getTagKind()) { 795 case TTK_Class: 796 FixItTagName = "class "; 797 break; 798 799 case TTK_Enum: 800 FixItTagName = "enum "; 801 break; 802 803 case TTK_Struct: 804 FixItTagName = "struct "; 805 break; 806 807 case TTK_Interface: 808 FixItTagName = "__interface "; 809 break; 810 811 case TTK_Union: 812 FixItTagName = "union "; 813 break; 814 } 815 816 StringRef TagName = FixItTagName.drop_back(); 817 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 818 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 819 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 820 821 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 822 I != IEnd; ++I) 823 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 824 << Name << TagName; 825 826 // Replace lookup results with just the tag decl. 827 Result.clear(Sema::LookupTagName); 828 SemaRef.LookupParsedName(Result, S, &SS); 829 return true; 830 } 831 832 return false; 833 } 834 835 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 836 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 837 QualType T, SourceLocation NameLoc) { 838 ASTContext &Context = S.Context; 839 840 TypeLocBuilder Builder; 841 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 842 843 T = S.getElaboratedType(ETK_None, SS, T); 844 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 845 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 846 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 847 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 848 } 849 850 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 851 IdentifierInfo *&Name, 852 SourceLocation NameLoc, 853 const Token &NextToken, 854 CorrectionCandidateCallback *CCC) { 855 DeclarationNameInfo NameInfo(Name, NameLoc); 856 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 857 858 assert(NextToken.isNot(tok::coloncolon) && 859 "parse nested name specifiers before calling ClassifyName"); 860 if (getLangOpts().CPlusPlus && SS.isSet() && 861 isCurrentClassName(*Name, S, &SS)) { 862 // Per [class.qual]p2, this names the constructors of SS, not the 863 // injected-class-name. We don't have a classification for that. 864 // There's not much point caching this result, since the parser 865 // will reject it later. 866 return NameClassification::Unknown(); 867 } 868 869 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 870 LookupParsedName(Result, S, &SS, !CurMethod); 871 872 if (SS.isInvalid()) 873 return NameClassification::Error(); 874 875 // For unqualified lookup in a class template in MSVC mode, look into 876 // dependent base classes where the primary class template is known. 877 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 878 if (ParsedType TypeInBase = 879 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 880 return TypeInBase; 881 } 882 883 // Perform lookup for Objective-C instance variables (including automatically 884 // synthesized instance variables), if we're in an Objective-C method. 885 // FIXME: This lookup really, really needs to be folded in to the normal 886 // unqualified lookup mechanism. 887 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 888 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 889 if (Ivar.isInvalid()) 890 return NameClassification::Error(); 891 if (Ivar.isUsable()) 892 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 893 894 // We defer builtin creation until after ivar lookup inside ObjC methods. 895 if (Result.empty()) 896 LookupBuiltin(Result); 897 } 898 899 bool SecondTry = false; 900 bool IsFilteredTemplateName = false; 901 902 Corrected: 903 switch (Result.getResultKind()) { 904 case LookupResult::NotFound: 905 // If an unqualified-id is followed by a '(', then we have a function 906 // call. 907 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 908 // In C++, this is an ADL-only call. 909 // FIXME: Reference? 910 if (getLangOpts().CPlusPlus) 911 return NameClassification::UndeclaredNonType(); 912 913 // C90 6.3.2.2: 914 // If the expression that precedes the parenthesized argument list in a 915 // function call consists solely of an identifier, and if no 916 // declaration is visible for this identifier, the identifier is 917 // implicitly declared exactly as if, in the innermost block containing 918 // the function call, the declaration 919 // 920 // extern int identifier (); 921 // 922 // appeared. 923 // 924 // We also allow this in C99 as an extension. 925 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 926 return NameClassification::NonType(D); 927 } 928 929 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 930 // In C++20 onwards, this could be an ADL-only call to a function 931 // template, and we're required to assume that this is a template name. 932 // 933 // FIXME: Find a way to still do typo correction in this case. 934 TemplateName Template = 935 Context.getAssumedTemplateName(NameInfo.getName()); 936 return NameClassification::UndeclaredTemplate(Template); 937 } 938 939 // In C, we first see whether there is a tag type by the same name, in 940 // which case it's likely that the user just forgot to write "enum", 941 // "struct", or "union". 942 if (!getLangOpts().CPlusPlus && !SecondTry && 943 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 944 break; 945 } 946 947 // Perform typo correction to determine if there is another name that is 948 // close to this name. 949 if (!SecondTry && CCC) { 950 SecondTry = true; 951 if (TypoCorrection Corrected = 952 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 953 &SS, *CCC, CTK_ErrorRecovery)) { 954 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 955 unsigned QualifiedDiag = diag::err_no_member_suggest; 956 957 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 958 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 959 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 960 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 961 UnqualifiedDiag = diag::err_no_template_suggest; 962 QualifiedDiag = diag::err_no_member_template_suggest; 963 } else if (UnderlyingFirstDecl && 964 (isa<TypeDecl>(UnderlyingFirstDecl) || 965 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 966 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 967 UnqualifiedDiag = diag::err_unknown_typename_suggest; 968 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 969 } 970 971 if (SS.isEmpty()) { 972 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 973 } else {// FIXME: is this even reachable? Test it. 974 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 975 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 976 Name->getName().equals(CorrectedStr); 977 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 978 << Name << computeDeclContext(SS, false) 979 << DroppedSpecifier << SS.getRange()); 980 } 981 982 // Update the name, so that the caller has the new name. 983 Name = Corrected.getCorrectionAsIdentifierInfo(); 984 985 // Typo correction corrected to a keyword. 986 if (Corrected.isKeyword()) 987 return Name; 988 989 // Also update the LookupResult... 990 // FIXME: This should probably go away at some point 991 Result.clear(); 992 Result.setLookupName(Corrected.getCorrection()); 993 if (FirstDecl) 994 Result.addDecl(FirstDecl); 995 996 // If we found an Objective-C instance variable, let 997 // LookupInObjCMethod build the appropriate expression to 998 // reference the ivar. 999 // FIXME: This is a gross hack. 1000 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1001 DeclResult R = 1002 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1003 if (R.isInvalid()) 1004 return NameClassification::Error(); 1005 if (R.isUsable()) 1006 return NameClassification::NonType(Ivar); 1007 } 1008 1009 goto Corrected; 1010 } 1011 } 1012 1013 // We failed to correct; just fall through and let the parser deal with it. 1014 Result.suppressDiagnostics(); 1015 return NameClassification::Unknown(); 1016 1017 case LookupResult::NotFoundInCurrentInstantiation: { 1018 // We performed name lookup into the current instantiation, and there were 1019 // dependent bases, so we treat this result the same way as any other 1020 // dependent nested-name-specifier. 1021 1022 // C++ [temp.res]p2: 1023 // A name used in a template declaration or definition and that is 1024 // dependent on a template-parameter is assumed not to name a type 1025 // unless the applicable name lookup finds a type name or the name is 1026 // qualified by the keyword typename. 1027 // 1028 // FIXME: If the next token is '<', we might want to ask the parser to 1029 // perform some heroics to see if we actually have a 1030 // template-argument-list, which would indicate a missing 'template' 1031 // keyword here. 1032 return NameClassification::DependentNonType(); 1033 } 1034 1035 case LookupResult::Found: 1036 case LookupResult::FoundOverloaded: 1037 case LookupResult::FoundUnresolvedValue: 1038 break; 1039 1040 case LookupResult::Ambiguous: 1041 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1042 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1043 /*AllowDependent=*/false)) { 1044 // C++ [temp.local]p3: 1045 // A lookup that finds an injected-class-name (10.2) can result in an 1046 // ambiguity in certain cases (for example, if it is found in more than 1047 // one base class). If all of the injected-class-names that are found 1048 // refer to specializations of the same class template, and if the name 1049 // is followed by a template-argument-list, the reference refers to the 1050 // class template itself and not a specialization thereof, and is not 1051 // ambiguous. 1052 // 1053 // This filtering can make an ambiguous result into an unambiguous one, 1054 // so try again after filtering out template names. 1055 FilterAcceptableTemplateNames(Result); 1056 if (!Result.isAmbiguous()) { 1057 IsFilteredTemplateName = true; 1058 break; 1059 } 1060 } 1061 1062 // Diagnose the ambiguity and return an error. 1063 return NameClassification::Error(); 1064 } 1065 1066 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1067 (IsFilteredTemplateName || 1068 hasAnyAcceptableTemplateNames( 1069 Result, /*AllowFunctionTemplates=*/true, 1070 /*AllowDependent=*/false, 1071 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1072 getLangOpts().CPlusPlus20))) { 1073 // C++ [temp.names]p3: 1074 // After name lookup (3.4) finds that a name is a template-name or that 1075 // an operator-function-id or a literal- operator-id refers to a set of 1076 // overloaded functions any member of which is a function template if 1077 // this is followed by a <, the < is always taken as the delimiter of a 1078 // template-argument-list and never as the less-than operator. 1079 // C++2a [temp.names]p2: 1080 // A name is also considered to refer to a template if it is an 1081 // unqualified-id followed by a < and name lookup finds either one 1082 // or more functions or finds nothing. 1083 if (!IsFilteredTemplateName) 1084 FilterAcceptableTemplateNames(Result); 1085 1086 bool IsFunctionTemplate; 1087 bool IsVarTemplate; 1088 TemplateName Template; 1089 if (Result.end() - Result.begin() > 1) { 1090 IsFunctionTemplate = true; 1091 Template = Context.getOverloadedTemplateName(Result.begin(), 1092 Result.end()); 1093 } else if (!Result.empty()) { 1094 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1095 *Result.begin(), /*AllowFunctionTemplates=*/true, 1096 /*AllowDependent=*/false)); 1097 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1098 IsVarTemplate = isa<VarTemplateDecl>(TD); 1099 1100 if (SS.isNotEmpty()) 1101 Template = 1102 Context.getQualifiedTemplateName(SS.getScopeRep(), 1103 /*TemplateKeyword=*/false, TD); 1104 else 1105 Template = TemplateName(TD); 1106 } else { 1107 // All results were non-template functions. This is a function template 1108 // name. 1109 IsFunctionTemplate = true; 1110 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1111 } 1112 1113 if (IsFunctionTemplate) { 1114 // Function templates always go through overload resolution, at which 1115 // point we'll perform the various checks (e.g., accessibility) we need 1116 // to based on which function we selected. 1117 Result.suppressDiagnostics(); 1118 1119 return NameClassification::FunctionTemplate(Template); 1120 } 1121 1122 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1123 : NameClassification::TypeTemplate(Template); 1124 } 1125 1126 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1127 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1128 DiagnoseUseOfDecl(Type, NameLoc); 1129 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1130 QualType T = Context.getTypeDeclType(Type); 1131 if (SS.isNotEmpty()) 1132 return buildNestedType(*this, SS, T, NameLoc); 1133 return ParsedType::make(T); 1134 } 1135 1136 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1137 if (!Class) { 1138 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1139 if (ObjCCompatibleAliasDecl *Alias = 1140 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1141 Class = Alias->getClassInterface(); 1142 } 1143 1144 if (Class) { 1145 DiagnoseUseOfDecl(Class, NameLoc); 1146 1147 if (NextToken.is(tok::period)) { 1148 // Interface. <something> is parsed as a property reference expression. 1149 // Just return "unknown" as a fall-through for now. 1150 Result.suppressDiagnostics(); 1151 return NameClassification::Unknown(); 1152 } 1153 1154 QualType T = Context.getObjCInterfaceType(Class); 1155 return ParsedType::make(T); 1156 } 1157 1158 if (isa<ConceptDecl>(FirstDecl)) 1159 return NameClassification::Concept( 1160 TemplateName(cast<TemplateDecl>(FirstDecl))); 1161 1162 // We can have a type template here if we're classifying a template argument. 1163 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1164 !isa<VarTemplateDecl>(FirstDecl)) 1165 return NameClassification::TypeTemplate( 1166 TemplateName(cast<TemplateDecl>(FirstDecl))); 1167 1168 // Check for a tag type hidden by a non-type decl in a few cases where it 1169 // seems likely a type is wanted instead of the non-type that was found. 1170 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1171 if ((NextToken.is(tok::identifier) || 1172 (NextIsOp && 1173 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1174 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1175 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1176 DiagnoseUseOfDecl(Type, NameLoc); 1177 QualType T = Context.getTypeDeclType(Type); 1178 if (SS.isNotEmpty()) 1179 return buildNestedType(*this, SS, T, NameLoc); 1180 return ParsedType::make(T); 1181 } 1182 1183 // FIXME: This is context-dependent. We need to defer building the member 1184 // expression until the classification is consumed. 1185 if (FirstDecl->isCXXClassMember()) 1186 return NameClassification::ContextIndependentExpr( 1187 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1188 S)); 1189 1190 // If we already know which single declaration is referenced, just annotate 1191 // that declaration directly. 1192 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1193 if (Result.isSingleResult() && !ADL) 1194 return NameClassification::NonType(Result.getRepresentativeDecl()); 1195 1196 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1197 // context in which we performed classification, so it's safe to do now. 1198 return NameClassification::ContextIndependentExpr( 1199 BuildDeclarationNameExpr(SS, Result, ADL)); 1200 } 1201 1202 ExprResult 1203 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1204 SourceLocation NameLoc) { 1205 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1206 CXXScopeSpec SS; 1207 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1208 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1209 } 1210 1211 ExprResult 1212 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1213 IdentifierInfo *Name, 1214 SourceLocation NameLoc, 1215 bool IsAddressOfOperand) { 1216 DeclarationNameInfo NameInfo(Name, NameLoc); 1217 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1218 NameInfo, IsAddressOfOperand, 1219 /*TemplateArgs=*/nullptr); 1220 } 1221 1222 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1223 NamedDecl *Found, 1224 SourceLocation NameLoc, 1225 const Token &NextToken) { 1226 if (getCurMethodDecl() && SS.isEmpty()) 1227 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1228 return BuildIvarRefExpr(S, NameLoc, Ivar); 1229 1230 // Reconstruct the lookup result. 1231 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1232 Result.addDecl(Found); 1233 Result.resolveKind(); 1234 1235 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1236 return BuildDeclarationNameExpr(SS, Result, ADL); 1237 } 1238 1239 Sema::TemplateNameKindForDiagnostics 1240 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1241 auto *TD = Name.getAsTemplateDecl(); 1242 if (!TD) 1243 return TemplateNameKindForDiagnostics::DependentTemplate; 1244 if (isa<ClassTemplateDecl>(TD)) 1245 return TemplateNameKindForDiagnostics::ClassTemplate; 1246 if (isa<FunctionTemplateDecl>(TD)) 1247 return TemplateNameKindForDiagnostics::FunctionTemplate; 1248 if (isa<VarTemplateDecl>(TD)) 1249 return TemplateNameKindForDiagnostics::VarTemplate; 1250 if (isa<TypeAliasTemplateDecl>(TD)) 1251 return TemplateNameKindForDiagnostics::AliasTemplate; 1252 if (isa<TemplateTemplateParmDecl>(TD)) 1253 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1254 if (isa<ConceptDecl>(TD)) 1255 return TemplateNameKindForDiagnostics::Concept; 1256 return TemplateNameKindForDiagnostics::DependentTemplate; 1257 } 1258 1259 // Determines the context to return to after temporarily entering a 1260 // context. This depends in an unnecessarily complicated way on the 1261 // exact ordering of callbacks from the parser. 1262 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1263 1264 // Functions defined inline within classes aren't parsed until we've 1265 // finished parsing the top-level class, so the top-level class is 1266 // the context we'll need to return to. 1267 // A Lambda call operator whose parent is a class must not be treated 1268 // as an inline member function. A Lambda can be used legally 1269 // either as an in-class member initializer or a default argument. These 1270 // are parsed once the class has been marked complete and so the containing 1271 // context would be the nested class (when the lambda is defined in one); 1272 // If the class is not complete, then the lambda is being used in an 1273 // ill-formed fashion (such as to specify the width of a bit-field, or 1274 // in an array-bound) - in which case we still want to return the 1275 // lexically containing DC (which could be a nested class). 1276 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1277 DC = DC->getLexicalParent(); 1278 1279 // A function not defined within a class will always return to its 1280 // lexical context. 1281 if (!isa<CXXRecordDecl>(DC)) 1282 return DC; 1283 1284 // A C++ inline method/friend is parsed *after* the topmost class 1285 // it was declared in is fully parsed ("complete"); the topmost 1286 // class is the context we need to return to. 1287 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1288 DC = RD; 1289 1290 // Return the declaration context of the topmost class the inline method is 1291 // declared in. 1292 return DC; 1293 } 1294 1295 return DC->getLexicalParent(); 1296 } 1297 1298 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1299 assert(getContainingDC(DC) == CurContext && 1300 "The next DeclContext should be lexically contained in the current one."); 1301 CurContext = DC; 1302 S->setEntity(DC); 1303 } 1304 1305 void Sema::PopDeclContext() { 1306 assert(CurContext && "DeclContext imbalance!"); 1307 1308 CurContext = getContainingDC(CurContext); 1309 assert(CurContext && "Popped translation unit!"); 1310 } 1311 1312 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1313 Decl *D) { 1314 // Unlike PushDeclContext, the context to which we return is not necessarily 1315 // the containing DC of TD, because the new context will be some pre-existing 1316 // TagDecl definition instead of a fresh one. 1317 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1318 CurContext = cast<TagDecl>(D)->getDefinition(); 1319 assert(CurContext && "skipping definition of undefined tag"); 1320 // Start lookups from the parent of the current context; we don't want to look 1321 // into the pre-existing complete definition. 1322 S->setEntity(CurContext->getLookupParent()); 1323 return Result; 1324 } 1325 1326 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1327 CurContext = static_cast<decltype(CurContext)>(Context); 1328 } 1329 1330 /// EnterDeclaratorContext - Used when we must lookup names in the context 1331 /// of a declarator's nested name specifier. 1332 /// 1333 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1334 // C++0x [basic.lookup.unqual]p13: 1335 // A name used in the definition of a static data member of class 1336 // X (after the qualified-id of the static member) is looked up as 1337 // if the name was used in a member function of X. 1338 // C++0x [basic.lookup.unqual]p14: 1339 // If a variable member of a namespace is defined outside of the 1340 // scope of its namespace then any name used in the definition of 1341 // the variable member (after the declarator-id) is looked up as 1342 // if the definition of the variable member occurred in its 1343 // namespace. 1344 // Both of these imply that we should push a scope whose context 1345 // is the semantic context of the declaration. We can't use 1346 // PushDeclContext here because that context is not necessarily 1347 // lexically contained in the current context. Fortunately, 1348 // the containing scope should have the appropriate information. 1349 1350 assert(!S->getEntity() && "scope already has entity"); 1351 1352 #ifndef NDEBUG 1353 Scope *Ancestor = S->getParent(); 1354 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1355 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1356 #endif 1357 1358 CurContext = DC; 1359 S->setEntity(DC); 1360 } 1361 1362 void Sema::ExitDeclaratorContext(Scope *S) { 1363 assert(S->getEntity() == CurContext && "Context imbalance!"); 1364 1365 // Switch back to the lexical context. The safety of this is 1366 // enforced by an assert in EnterDeclaratorContext. 1367 Scope *Ancestor = S->getParent(); 1368 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1369 CurContext = Ancestor->getEntity(); 1370 1371 // We don't need to do anything with the scope, which is going to 1372 // disappear. 1373 } 1374 1375 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1376 // We assume that the caller has already called 1377 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1378 FunctionDecl *FD = D->getAsFunction(); 1379 if (!FD) 1380 return; 1381 1382 // Same implementation as PushDeclContext, but enters the context 1383 // from the lexical parent, rather than the top-level class. 1384 assert(CurContext == FD->getLexicalParent() && 1385 "The next DeclContext should be lexically contained in the current one."); 1386 CurContext = FD; 1387 S->setEntity(CurContext); 1388 1389 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1390 ParmVarDecl *Param = FD->getParamDecl(P); 1391 // If the parameter has an identifier, then add it to the scope 1392 if (Param->getIdentifier()) { 1393 S->AddDecl(Param); 1394 IdResolver.AddDecl(Param); 1395 } 1396 } 1397 } 1398 1399 void Sema::ActOnExitFunctionContext() { 1400 // Same implementation as PopDeclContext, but returns to the lexical parent, 1401 // rather than the top-level class. 1402 assert(CurContext && "DeclContext imbalance!"); 1403 CurContext = CurContext->getLexicalParent(); 1404 assert(CurContext && "Popped translation unit!"); 1405 } 1406 1407 /// Determine whether we allow overloading of the function 1408 /// PrevDecl with another declaration. 1409 /// 1410 /// This routine determines whether overloading is possible, not 1411 /// whether some new function is actually an overload. It will return 1412 /// true in C++ (where we can always provide overloads) or, as an 1413 /// extension, in C when the previous function is already an 1414 /// overloaded function declaration or has the "overloadable" 1415 /// attribute. 1416 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1417 ASTContext &Context, 1418 const FunctionDecl *New) { 1419 if (Context.getLangOpts().CPlusPlus) 1420 return true; 1421 1422 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1423 return true; 1424 1425 return Previous.getResultKind() == LookupResult::Found && 1426 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1427 New->hasAttr<OverloadableAttr>()); 1428 } 1429 1430 /// Add this decl to the scope shadowed decl chains. 1431 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1432 // Move up the scope chain until we find the nearest enclosing 1433 // non-transparent context. The declaration will be introduced into this 1434 // scope. 1435 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1436 S = S->getParent(); 1437 1438 // Add scoped declarations into their context, so that they can be 1439 // found later. Declarations without a context won't be inserted 1440 // into any context. 1441 if (AddToContext) 1442 CurContext->addDecl(D); 1443 1444 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1445 // are function-local declarations. 1446 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1447 !D->getDeclContext()->getRedeclContext()->Equals( 1448 D->getLexicalDeclContext()->getRedeclContext()) && 1449 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1450 return; 1451 1452 // Template instantiations should also not be pushed into scope. 1453 if (isa<FunctionDecl>(D) && 1454 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1455 return; 1456 1457 // If this replaces anything in the current scope, 1458 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1459 IEnd = IdResolver.end(); 1460 for (; I != IEnd; ++I) { 1461 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1462 S->RemoveDecl(*I); 1463 IdResolver.RemoveDecl(*I); 1464 1465 // Should only need to replace one decl. 1466 break; 1467 } 1468 } 1469 1470 S->AddDecl(D); 1471 1472 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1473 // Implicitly-generated labels may end up getting generated in an order that 1474 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1475 // the label at the appropriate place in the identifier chain. 1476 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1477 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1478 if (IDC == CurContext) { 1479 if (!S->isDeclScope(*I)) 1480 continue; 1481 } else if (IDC->Encloses(CurContext)) 1482 break; 1483 } 1484 1485 IdResolver.InsertDeclAfter(I, D); 1486 } else { 1487 IdResolver.AddDecl(D); 1488 } 1489 } 1490 1491 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1492 bool AllowInlineNamespace) { 1493 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1494 } 1495 1496 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1497 DeclContext *TargetDC = DC->getPrimaryContext(); 1498 do { 1499 if (DeclContext *ScopeDC = S->getEntity()) 1500 if (ScopeDC->getPrimaryContext() == TargetDC) 1501 return S; 1502 } while ((S = S->getParent())); 1503 1504 return nullptr; 1505 } 1506 1507 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1508 DeclContext*, 1509 ASTContext&); 1510 1511 /// Filters out lookup results that don't fall within the given scope 1512 /// as determined by isDeclInScope. 1513 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1514 bool ConsiderLinkage, 1515 bool AllowInlineNamespace) { 1516 LookupResult::Filter F = R.makeFilter(); 1517 while (F.hasNext()) { 1518 NamedDecl *D = F.next(); 1519 1520 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1521 continue; 1522 1523 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1524 continue; 1525 1526 F.erase(); 1527 } 1528 1529 F.done(); 1530 } 1531 1532 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1533 /// have compatible owning modules. 1534 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1535 // FIXME: The Modules TS is not clear about how friend declarations are 1536 // to be treated. It's not meaningful to have different owning modules for 1537 // linkage in redeclarations of the same entity, so for now allow the 1538 // redeclaration and change the owning modules to match. 1539 if (New->getFriendObjectKind() && 1540 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1541 New->setLocalOwningModule(Old->getOwningModule()); 1542 makeMergedDefinitionVisible(New); 1543 return false; 1544 } 1545 1546 Module *NewM = New->getOwningModule(); 1547 Module *OldM = Old->getOwningModule(); 1548 1549 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1550 NewM = NewM->Parent; 1551 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1552 OldM = OldM->Parent; 1553 1554 if (NewM == OldM) 1555 return false; 1556 1557 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1558 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1559 if (NewIsModuleInterface || OldIsModuleInterface) { 1560 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1561 // if a declaration of D [...] appears in the purview of a module, all 1562 // other such declarations shall appear in the purview of the same module 1563 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1564 << New 1565 << NewIsModuleInterface 1566 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1567 << OldIsModuleInterface 1568 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1569 Diag(Old->getLocation(), diag::note_previous_declaration); 1570 New->setInvalidDecl(); 1571 return true; 1572 } 1573 1574 return false; 1575 } 1576 1577 static bool isUsingDecl(NamedDecl *D) { 1578 return isa<UsingShadowDecl>(D) || 1579 isa<UnresolvedUsingTypenameDecl>(D) || 1580 isa<UnresolvedUsingValueDecl>(D); 1581 } 1582 1583 /// Removes using shadow declarations from the lookup results. 1584 static void RemoveUsingDecls(LookupResult &R) { 1585 LookupResult::Filter F = R.makeFilter(); 1586 while (F.hasNext()) 1587 if (isUsingDecl(F.next())) 1588 F.erase(); 1589 1590 F.done(); 1591 } 1592 1593 /// Check for this common pattern: 1594 /// @code 1595 /// class S { 1596 /// S(const S&); // DO NOT IMPLEMENT 1597 /// void operator=(const S&); // DO NOT IMPLEMENT 1598 /// }; 1599 /// @endcode 1600 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1601 // FIXME: Should check for private access too but access is set after we get 1602 // the decl here. 1603 if (D->doesThisDeclarationHaveABody()) 1604 return false; 1605 1606 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1607 return CD->isCopyConstructor(); 1608 return D->isCopyAssignmentOperator(); 1609 } 1610 1611 // We need this to handle 1612 // 1613 // typedef struct { 1614 // void *foo() { return 0; } 1615 // } A; 1616 // 1617 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1618 // for example. If 'A', foo will have external linkage. If we have '*A', 1619 // foo will have no linkage. Since we can't know until we get to the end 1620 // of the typedef, this function finds out if D might have non-external linkage. 1621 // Callers should verify at the end of the TU if it D has external linkage or 1622 // not. 1623 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1624 const DeclContext *DC = D->getDeclContext(); 1625 while (!DC->isTranslationUnit()) { 1626 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1627 if (!RD->hasNameForLinkage()) 1628 return true; 1629 } 1630 DC = DC->getParent(); 1631 } 1632 1633 return !D->isExternallyVisible(); 1634 } 1635 1636 // FIXME: This needs to be refactored; some other isInMainFile users want 1637 // these semantics. 1638 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1639 if (S.TUKind != TU_Complete) 1640 return false; 1641 return S.SourceMgr.isInMainFile(Loc); 1642 } 1643 1644 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1645 assert(D); 1646 1647 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1648 return false; 1649 1650 // Ignore all entities declared within templates, and out-of-line definitions 1651 // of members of class templates. 1652 if (D->getDeclContext()->isDependentContext() || 1653 D->getLexicalDeclContext()->isDependentContext()) 1654 return false; 1655 1656 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1657 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1658 return false; 1659 // A non-out-of-line declaration of a member specialization was implicitly 1660 // instantiated; it's the out-of-line declaration that we're interested in. 1661 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1662 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1663 return false; 1664 1665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1666 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1667 return false; 1668 } else { 1669 // 'static inline' functions are defined in headers; don't warn. 1670 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1671 return false; 1672 } 1673 1674 if (FD->doesThisDeclarationHaveABody() && 1675 Context.DeclMustBeEmitted(FD)) 1676 return false; 1677 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1678 // Constants and utility variables are defined in headers with internal 1679 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1680 // like "inline".) 1681 if (!isMainFileLoc(*this, VD->getLocation())) 1682 return false; 1683 1684 if (Context.DeclMustBeEmitted(VD)) 1685 return false; 1686 1687 if (VD->isStaticDataMember() && 1688 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1689 return false; 1690 if (VD->isStaticDataMember() && 1691 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1693 return false; 1694 1695 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1696 return false; 1697 } else { 1698 return false; 1699 } 1700 1701 // Only warn for unused decls internal to the translation unit. 1702 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1703 // for inline functions defined in the main source file, for instance. 1704 return mightHaveNonExternalLinkage(D); 1705 } 1706 1707 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1708 if (!D) 1709 return; 1710 1711 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1712 const FunctionDecl *First = FD->getFirstDecl(); 1713 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1714 return; // First should already be in the vector. 1715 } 1716 1717 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1718 const VarDecl *First = VD->getFirstDecl(); 1719 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1720 return; // First should already be in the vector. 1721 } 1722 1723 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1724 UnusedFileScopedDecls.push_back(D); 1725 } 1726 1727 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1728 if (D->isInvalidDecl()) 1729 return false; 1730 1731 bool Referenced = false; 1732 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1733 // For a decomposition declaration, warn if none of the bindings are 1734 // referenced, instead of if the variable itself is referenced (which 1735 // it is, by the bindings' expressions). 1736 for (auto *BD : DD->bindings()) { 1737 if (BD->isReferenced()) { 1738 Referenced = true; 1739 break; 1740 } 1741 } 1742 } else if (!D->getDeclName()) { 1743 return false; 1744 } else if (D->isReferenced() || D->isUsed()) { 1745 Referenced = true; 1746 } 1747 1748 if (Referenced || D->hasAttr<UnusedAttr>() || 1749 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1750 return false; 1751 1752 if (isa<LabelDecl>(D)) 1753 return true; 1754 1755 // Except for labels, we only care about unused decls that are local to 1756 // functions. 1757 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1758 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1759 // For dependent types, the diagnostic is deferred. 1760 WithinFunction = 1761 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1762 if (!WithinFunction) 1763 return false; 1764 1765 if (isa<TypedefNameDecl>(D)) 1766 return true; 1767 1768 // White-list anything that isn't a local variable. 1769 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1770 return false; 1771 1772 // Types of valid local variables should be complete, so this should succeed. 1773 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1774 1775 // White-list anything with an __attribute__((unused)) type. 1776 const auto *Ty = VD->getType().getTypePtr(); 1777 1778 // Only look at the outermost level of typedef. 1779 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1780 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1781 return false; 1782 } 1783 1784 // If we failed to complete the type for some reason, or if the type is 1785 // dependent, don't diagnose the variable. 1786 if (Ty->isIncompleteType() || Ty->isDependentType()) 1787 return false; 1788 1789 // Look at the element type to ensure that the warning behaviour is 1790 // consistent for both scalars and arrays. 1791 Ty = Ty->getBaseElementTypeUnsafe(); 1792 1793 if (const TagType *TT = Ty->getAs<TagType>()) { 1794 const TagDecl *Tag = TT->getDecl(); 1795 if (Tag->hasAttr<UnusedAttr>()) 1796 return false; 1797 1798 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1799 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1800 return false; 1801 1802 if (const Expr *Init = VD->getInit()) { 1803 if (const ExprWithCleanups *Cleanups = 1804 dyn_cast<ExprWithCleanups>(Init)) 1805 Init = Cleanups->getSubExpr(); 1806 const CXXConstructExpr *Construct = 1807 dyn_cast<CXXConstructExpr>(Init); 1808 if (Construct && !Construct->isElidable()) { 1809 CXXConstructorDecl *CD = Construct->getConstructor(); 1810 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1811 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1812 return false; 1813 } 1814 1815 // Suppress the warning if we don't know how this is constructed, and 1816 // it could possibly be non-trivial constructor. 1817 if (Init->isTypeDependent()) 1818 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1819 if (!Ctor->isTrivial()) 1820 return false; 1821 } 1822 } 1823 } 1824 1825 // TODO: __attribute__((unused)) templates? 1826 } 1827 1828 return true; 1829 } 1830 1831 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1832 FixItHint &Hint) { 1833 if (isa<LabelDecl>(D)) { 1834 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1835 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1836 true); 1837 if (AfterColon.isInvalid()) 1838 return; 1839 Hint = FixItHint::CreateRemoval( 1840 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1841 } 1842 } 1843 1844 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1845 if (D->getTypeForDecl()->isDependentType()) 1846 return; 1847 1848 for (auto *TmpD : D->decls()) { 1849 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1850 DiagnoseUnusedDecl(T); 1851 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1852 DiagnoseUnusedNestedTypedefs(R); 1853 } 1854 } 1855 1856 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1857 /// unless they are marked attr(unused). 1858 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1859 if (!ShouldDiagnoseUnusedDecl(D)) 1860 return; 1861 1862 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1863 // typedefs can be referenced later on, so the diagnostics are emitted 1864 // at end-of-translation-unit. 1865 UnusedLocalTypedefNameCandidates.insert(TD); 1866 return; 1867 } 1868 1869 FixItHint Hint; 1870 GenerateFixForUnusedDecl(D, Context, Hint); 1871 1872 unsigned DiagID; 1873 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1874 DiagID = diag::warn_unused_exception_param; 1875 else if (isa<LabelDecl>(D)) 1876 DiagID = diag::warn_unused_label; 1877 else 1878 DiagID = diag::warn_unused_variable; 1879 1880 Diag(D->getLocation(), DiagID) << D << Hint; 1881 } 1882 1883 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1884 // Verify that we have no forward references left. If so, there was a goto 1885 // or address of a label taken, but no definition of it. Label fwd 1886 // definitions are indicated with a null substmt which is also not a resolved 1887 // MS inline assembly label name. 1888 bool Diagnose = false; 1889 if (L->isMSAsmLabel()) 1890 Diagnose = !L->isResolvedMSAsmLabel(); 1891 else 1892 Diagnose = L->getStmt() == nullptr; 1893 if (Diagnose) 1894 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1895 } 1896 1897 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1898 S->mergeNRVOIntoParent(); 1899 1900 if (S->decl_empty()) return; 1901 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1902 "Scope shouldn't contain decls!"); 1903 1904 for (auto *TmpD : S->decls()) { 1905 assert(TmpD && "This decl didn't get pushed??"); 1906 1907 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1908 NamedDecl *D = cast<NamedDecl>(TmpD); 1909 1910 // Diagnose unused variables in this scope. 1911 if (!S->hasUnrecoverableErrorOccurred()) { 1912 DiagnoseUnusedDecl(D); 1913 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1914 DiagnoseUnusedNestedTypedefs(RD); 1915 } 1916 1917 if (!D->getDeclName()) continue; 1918 1919 // If this was a forward reference to a label, verify it was defined. 1920 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1921 CheckPoppedLabel(LD, *this); 1922 1923 // Remove this name from our lexical scope, and warn on it if we haven't 1924 // already. 1925 IdResolver.RemoveDecl(D); 1926 auto ShadowI = ShadowingDecls.find(D); 1927 if (ShadowI != ShadowingDecls.end()) { 1928 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1929 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1930 << D << FD << FD->getParent(); 1931 Diag(FD->getLocation(), diag::note_previous_declaration); 1932 } 1933 ShadowingDecls.erase(ShadowI); 1934 } 1935 } 1936 } 1937 1938 /// Look for an Objective-C class in the translation unit. 1939 /// 1940 /// \param Id The name of the Objective-C class we're looking for. If 1941 /// typo-correction fixes this name, the Id will be updated 1942 /// to the fixed name. 1943 /// 1944 /// \param IdLoc The location of the name in the translation unit. 1945 /// 1946 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1947 /// if there is no class with the given name. 1948 /// 1949 /// \returns The declaration of the named Objective-C class, or NULL if the 1950 /// class could not be found. 1951 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1952 SourceLocation IdLoc, 1953 bool DoTypoCorrection) { 1954 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1955 // creation from this context. 1956 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1957 1958 if (!IDecl && DoTypoCorrection) { 1959 // Perform typo correction at the given location, but only if we 1960 // find an Objective-C class name. 1961 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1962 if (TypoCorrection C = 1963 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1964 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1965 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1966 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1967 Id = IDecl->getIdentifier(); 1968 } 1969 } 1970 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1971 // This routine must always return a class definition, if any. 1972 if (Def && Def->getDefinition()) 1973 Def = Def->getDefinition(); 1974 return Def; 1975 } 1976 1977 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1978 /// from S, where a non-field would be declared. This routine copes 1979 /// with the difference between C and C++ scoping rules in structs and 1980 /// unions. For example, the following code is well-formed in C but 1981 /// ill-formed in C++: 1982 /// @code 1983 /// struct S6 { 1984 /// enum { BAR } e; 1985 /// }; 1986 /// 1987 /// void test_S6() { 1988 /// struct S6 a; 1989 /// a.e = BAR; 1990 /// } 1991 /// @endcode 1992 /// For the declaration of BAR, this routine will return a different 1993 /// scope. The scope S will be the scope of the unnamed enumeration 1994 /// within S6. In C++, this routine will return the scope associated 1995 /// with S6, because the enumeration's scope is a transparent 1996 /// context but structures can contain non-field names. In C, this 1997 /// routine will return the translation unit scope, since the 1998 /// enumeration's scope is a transparent context and structures cannot 1999 /// contain non-field names. 2000 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2001 while (((S->getFlags() & Scope::DeclScope) == 0) || 2002 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2003 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2004 S = S->getParent(); 2005 return S; 2006 } 2007 2008 /// Looks up the declaration of "struct objc_super" and 2009 /// saves it for later use in building builtin declaration of 2010 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2011 /// pre-existing declaration exists no action takes place. 2012 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2013 IdentifierInfo *II) { 2014 if (!II->isStr("objc_msgSendSuper")) 2015 return; 2016 ASTContext &Context = ThisSema.Context; 2017 2018 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2019 SourceLocation(), Sema::LookupTagName); 2020 ThisSema.LookupName(Result, S); 2021 if (Result.getResultKind() == LookupResult::Found) 2022 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2023 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2024 } 2025 2026 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2027 ASTContext::GetBuiltinTypeError Error) { 2028 switch (Error) { 2029 case ASTContext::GE_None: 2030 return ""; 2031 case ASTContext::GE_Missing_type: 2032 return BuiltinInfo.getHeaderName(ID); 2033 case ASTContext::GE_Missing_stdio: 2034 return "stdio.h"; 2035 case ASTContext::GE_Missing_setjmp: 2036 return "setjmp.h"; 2037 case ASTContext::GE_Missing_ucontext: 2038 return "ucontext.h"; 2039 } 2040 llvm_unreachable("unhandled error kind"); 2041 } 2042 2043 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2044 /// file scope. lazily create a decl for it. ForRedeclaration is true 2045 /// if we're creating this built-in in anticipation of redeclaring the 2046 /// built-in. 2047 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2048 Scope *S, bool ForRedeclaration, 2049 SourceLocation Loc) { 2050 LookupPredefedObjCSuperType(*this, S, II); 2051 2052 ASTContext::GetBuiltinTypeError Error; 2053 QualType R = Context.GetBuiltinType(ID, Error); 2054 if (Error) { 2055 if (!ForRedeclaration) 2056 return nullptr; 2057 2058 // If we have a builtin without an associated type we should not emit a 2059 // warning when we were not able to find a type for it. 2060 if (Error == ASTContext::GE_Missing_type) 2061 return nullptr; 2062 2063 // If we could not find a type for setjmp it is because the jmp_buf type was 2064 // not defined prior to the setjmp declaration. 2065 if (Error == ASTContext::GE_Missing_setjmp) { 2066 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2067 << Context.BuiltinInfo.getName(ID); 2068 return nullptr; 2069 } 2070 2071 // Generally, we emit a warning that the declaration requires the 2072 // appropriate header. 2073 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2074 << getHeaderName(Context.BuiltinInfo, ID, Error) 2075 << Context.BuiltinInfo.getName(ID); 2076 return nullptr; 2077 } 2078 2079 if (!ForRedeclaration && 2080 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2081 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2082 Diag(Loc, diag::ext_implicit_lib_function_decl) 2083 << Context.BuiltinInfo.getName(ID) << R; 2084 if (Context.BuiltinInfo.getHeaderName(ID) && 2085 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2086 Diag(Loc, diag::note_include_header_or_declare) 2087 << Context.BuiltinInfo.getHeaderName(ID) 2088 << Context.BuiltinInfo.getName(ID); 2089 } 2090 2091 if (R.isNull()) 2092 return nullptr; 2093 2094 DeclContext *Parent = Context.getTranslationUnitDecl(); 2095 if (getLangOpts().CPlusPlus) { 2096 LinkageSpecDecl *CLinkageDecl = 2097 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2098 LinkageSpecDecl::lang_c, false); 2099 CLinkageDecl->setImplicit(); 2100 Parent->addDecl(CLinkageDecl); 2101 Parent = CLinkageDecl; 2102 } 2103 2104 FunctionDecl *New = FunctionDecl::Create(Context, 2105 Parent, 2106 Loc, Loc, II, R, /*TInfo=*/nullptr, 2107 SC_Extern, 2108 false, 2109 R->isFunctionProtoType()); 2110 New->setImplicit(); 2111 2112 // Create Decl objects for each parameter, adding them to the 2113 // FunctionDecl. 2114 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2115 SmallVector<ParmVarDecl*, 16> Params; 2116 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2117 ParmVarDecl *parm = 2118 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2119 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2120 SC_None, nullptr); 2121 parm->setScopeInfo(0, i); 2122 Params.push_back(parm); 2123 } 2124 New->setParams(Params); 2125 } 2126 2127 AddKnownFunctionAttributes(New); 2128 RegisterLocallyScopedExternCDecl(New, S); 2129 2130 // TUScope is the translation-unit scope to insert this function into. 2131 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2132 // relate Scopes to DeclContexts, and probably eliminate CurContext 2133 // entirely, but we're not there yet. 2134 DeclContext *SavedContext = CurContext; 2135 CurContext = Parent; 2136 PushOnScopeChains(New, TUScope); 2137 CurContext = SavedContext; 2138 return New; 2139 } 2140 2141 /// Typedef declarations don't have linkage, but they still denote the same 2142 /// entity if their types are the same. 2143 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2144 /// isSameEntity. 2145 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2146 TypedefNameDecl *Decl, 2147 LookupResult &Previous) { 2148 // This is only interesting when modules are enabled. 2149 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2150 return; 2151 2152 // Empty sets are uninteresting. 2153 if (Previous.empty()) 2154 return; 2155 2156 LookupResult::Filter Filter = Previous.makeFilter(); 2157 while (Filter.hasNext()) { 2158 NamedDecl *Old = Filter.next(); 2159 2160 // Non-hidden declarations are never ignored. 2161 if (S.isVisible(Old)) 2162 continue; 2163 2164 // Declarations of the same entity are not ignored, even if they have 2165 // different linkages. 2166 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2167 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2168 Decl->getUnderlyingType())) 2169 continue; 2170 2171 // If both declarations give a tag declaration a typedef name for linkage 2172 // purposes, then they declare the same entity. 2173 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2174 Decl->getAnonDeclWithTypedefName()) 2175 continue; 2176 } 2177 2178 Filter.erase(); 2179 } 2180 2181 Filter.done(); 2182 } 2183 2184 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2185 QualType OldType; 2186 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2187 OldType = OldTypedef->getUnderlyingType(); 2188 else 2189 OldType = Context.getTypeDeclType(Old); 2190 QualType NewType = New->getUnderlyingType(); 2191 2192 if (NewType->isVariablyModifiedType()) { 2193 // Must not redefine a typedef with a variably-modified type. 2194 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2195 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2196 << Kind << NewType; 2197 if (Old->getLocation().isValid()) 2198 notePreviousDefinition(Old, New->getLocation()); 2199 New->setInvalidDecl(); 2200 return true; 2201 } 2202 2203 if (OldType != NewType && 2204 !OldType->isDependentType() && 2205 !NewType->isDependentType() && 2206 !Context.hasSameType(OldType, NewType)) { 2207 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2208 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2209 << Kind << NewType << OldType; 2210 if (Old->getLocation().isValid()) 2211 notePreviousDefinition(Old, New->getLocation()); 2212 New->setInvalidDecl(); 2213 return true; 2214 } 2215 return false; 2216 } 2217 2218 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2219 /// same name and scope as a previous declaration 'Old'. Figure out 2220 /// how to resolve this situation, merging decls or emitting 2221 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2222 /// 2223 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2224 LookupResult &OldDecls) { 2225 // If the new decl is known invalid already, don't bother doing any 2226 // merging checks. 2227 if (New->isInvalidDecl()) return; 2228 2229 // Allow multiple definitions for ObjC built-in typedefs. 2230 // FIXME: Verify the underlying types are equivalent! 2231 if (getLangOpts().ObjC) { 2232 const IdentifierInfo *TypeID = New->getIdentifier(); 2233 switch (TypeID->getLength()) { 2234 default: break; 2235 case 2: 2236 { 2237 if (!TypeID->isStr("id")) 2238 break; 2239 QualType T = New->getUnderlyingType(); 2240 if (!T->isPointerType()) 2241 break; 2242 if (!T->isVoidPointerType()) { 2243 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2244 if (!PT->isStructureType()) 2245 break; 2246 } 2247 Context.setObjCIdRedefinitionType(T); 2248 // Install the built-in type for 'id', ignoring the current definition. 2249 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2250 return; 2251 } 2252 case 5: 2253 if (!TypeID->isStr("Class")) 2254 break; 2255 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2256 // Install the built-in type for 'Class', ignoring the current definition. 2257 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2258 return; 2259 case 3: 2260 if (!TypeID->isStr("SEL")) 2261 break; 2262 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2263 // Install the built-in type for 'SEL', ignoring the current definition. 2264 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2265 return; 2266 } 2267 // Fall through - the typedef name was not a builtin type. 2268 } 2269 2270 // Verify the old decl was also a type. 2271 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2272 if (!Old) { 2273 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2274 << New->getDeclName(); 2275 2276 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2277 if (OldD->getLocation().isValid()) 2278 notePreviousDefinition(OldD, New->getLocation()); 2279 2280 return New->setInvalidDecl(); 2281 } 2282 2283 // If the old declaration is invalid, just give up here. 2284 if (Old->isInvalidDecl()) 2285 return New->setInvalidDecl(); 2286 2287 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2288 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2289 auto *NewTag = New->getAnonDeclWithTypedefName(); 2290 NamedDecl *Hidden = nullptr; 2291 if (OldTag && NewTag && 2292 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2293 !hasVisibleDefinition(OldTag, &Hidden)) { 2294 // There is a definition of this tag, but it is not visible. Use it 2295 // instead of our tag. 2296 New->setTypeForDecl(OldTD->getTypeForDecl()); 2297 if (OldTD->isModed()) 2298 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2299 OldTD->getUnderlyingType()); 2300 else 2301 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2302 2303 // Make the old tag definition visible. 2304 makeMergedDefinitionVisible(Hidden); 2305 2306 // If this was an unscoped enumeration, yank all of its enumerators 2307 // out of the scope. 2308 if (isa<EnumDecl>(NewTag)) { 2309 Scope *EnumScope = getNonFieldDeclScope(S); 2310 for (auto *D : NewTag->decls()) { 2311 auto *ED = cast<EnumConstantDecl>(D); 2312 assert(EnumScope->isDeclScope(ED)); 2313 EnumScope->RemoveDecl(ED); 2314 IdResolver.RemoveDecl(ED); 2315 ED->getLexicalDeclContext()->removeDecl(ED); 2316 } 2317 } 2318 } 2319 } 2320 2321 // If the typedef types are not identical, reject them in all languages and 2322 // with any extensions enabled. 2323 if (isIncompatibleTypedef(Old, New)) 2324 return; 2325 2326 // The types match. Link up the redeclaration chain and merge attributes if 2327 // the old declaration was a typedef. 2328 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2329 New->setPreviousDecl(Typedef); 2330 mergeDeclAttributes(New, Old); 2331 } 2332 2333 if (getLangOpts().MicrosoftExt) 2334 return; 2335 2336 if (getLangOpts().CPlusPlus) { 2337 // C++ [dcl.typedef]p2: 2338 // In a given non-class scope, a typedef specifier can be used to 2339 // redefine the name of any type declared in that scope to refer 2340 // to the type to which it already refers. 2341 if (!isa<CXXRecordDecl>(CurContext)) 2342 return; 2343 2344 // C++0x [dcl.typedef]p4: 2345 // In a given class scope, a typedef specifier can be used to redefine 2346 // any class-name declared in that scope that is not also a typedef-name 2347 // to refer to the type to which it already refers. 2348 // 2349 // This wording came in via DR424, which was a correction to the 2350 // wording in DR56, which accidentally banned code like: 2351 // 2352 // struct S { 2353 // typedef struct A { } A; 2354 // }; 2355 // 2356 // in the C++03 standard. We implement the C++0x semantics, which 2357 // allow the above but disallow 2358 // 2359 // struct S { 2360 // typedef int I; 2361 // typedef int I; 2362 // }; 2363 // 2364 // since that was the intent of DR56. 2365 if (!isa<TypedefNameDecl>(Old)) 2366 return; 2367 2368 Diag(New->getLocation(), diag::err_redefinition) 2369 << New->getDeclName(); 2370 notePreviousDefinition(Old, New->getLocation()); 2371 return New->setInvalidDecl(); 2372 } 2373 2374 // Modules always permit redefinition of typedefs, as does C11. 2375 if (getLangOpts().Modules || getLangOpts().C11) 2376 return; 2377 2378 // If we have a redefinition of a typedef in C, emit a warning. This warning 2379 // is normally mapped to an error, but can be controlled with 2380 // -Wtypedef-redefinition. If either the original or the redefinition is 2381 // in a system header, don't emit this for compatibility with GCC. 2382 if (getDiagnostics().getSuppressSystemWarnings() && 2383 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2384 (Old->isImplicit() || 2385 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2386 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2387 return; 2388 2389 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2390 << New->getDeclName(); 2391 notePreviousDefinition(Old, New->getLocation()); 2392 } 2393 2394 /// DeclhasAttr - returns true if decl Declaration already has the target 2395 /// attribute. 2396 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2397 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2398 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2399 for (const auto *i : D->attrs()) 2400 if (i->getKind() == A->getKind()) { 2401 if (Ann) { 2402 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2403 return true; 2404 continue; 2405 } 2406 // FIXME: Don't hardcode this check 2407 if (OA && isa<OwnershipAttr>(i)) 2408 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2409 return true; 2410 } 2411 2412 return false; 2413 } 2414 2415 static bool isAttributeTargetADefinition(Decl *D) { 2416 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2417 return VD->isThisDeclarationADefinition(); 2418 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2419 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2420 return true; 2421 } 2422 2423 /// Merge alignment attributes from \p Old to \p New, taking into account the 2424 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2425 /// 2426 /// \return \c true if any attributes were added to \p New. 2427 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2428 // Look for alignas attributes on Old, and pick out whichever attribute 2429 // specifies the strictest alignment requirement. 2430 AlignedAttr *OldAlignasAttr = nullptr; 2431 AlignedAttr *OldStrictestAlignAttr = nullptr; 2432 unsigned OldAlign = 0; 2433 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2434 // FIXME: We have no way of representing inherited dependent alignments 2435 // in a case like: 2436 // template<int A, int B> struct alignas(A) X; 2437 // template<int A, int B> struct alignas(B) X {}; 2438 // For now, we just ignore any alignas attributes which are not on the 2439 // definition in such a case. 2440 if (I->isAlignmentDependent()) 2441 return false; 2442 2443 if (I->isAlignas()) 2444 OldAlignasAttr = I; 2445 2446 unsigned Align = I->getAlignment(S.Context); 2447 if (Align > OldAlign) { 2448 OldAlign = Align; 2449 OldStrictestAlignAttr = I; 2450 } 2451 } 2452 2453 // Look for alignas attributes on New. 2454 AlignedAttr *NewAlignasAttr = nullptr; 2455 unsigned NewAlign = 0; 2456 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2457 if (I->isAlignmentDependent()) 2458 return false; 2459 2460 if (I->isAlignas()) 2461 NewAlignasAttr = I; 2462 2463 unsigned Align = I->getAlignment(S.Context); 2464 if (Align > NewAlign) 2465 NewAlign = Align; 2466 } 2467 2468 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2469 // Both declarations have 'alignas' attributes. We require them to match. 2470 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2471 // fall short. (If two declarations both have alignas, they must both match 2472 // every definition, and so must match each other if there is a definition.) 2473 2474 // If either declaration only contains 'alignas(0)' specifiers, then it 2475 // specifies the natural alignment for the type. 2476 if (OldAlign == 0 || NewAlign == 0) { 2477 QualType Ty; 2478 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2479 Ty = VD->getType(); 2480 else 2481 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2482 2483 if (OldAlign == 0) 2484 OldAlign = S.Context.getTypeAlign(Ty); 2485 if (NewAlign == 0) 2486 NewAlign = S.Context.getTypeAlign(Ty); 2487 } 2488 2489 if (OldAlign != NewAlign) { 2490 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2491 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2492 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2493 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2494 } 2495 } 2496 2497 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2498 // C++11 [dcl.align]p6: 2499 // if any declaration of an entity has an alignment-specifier, 2500 // every defining declaration of that entity shall specify an 2501 // equivalent alignment. 2502 // C11 6.7.5/7: 2503 // If the definition of an object does not have an alignment 2504 // specifier, any other declaration of that object shall also 2505 // have no alignment specifier. 2506 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2507 << OldAlignasAttr; 2508 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2509 << OldAlignasAttr; 2510 } 2511 2512 bool AnyAdded = false; 2513 2514 // Ensure we have an attribute representing the strictest alignment. 2515 if (OldAlign > NewAlign) { 2516 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2517 Clone->setInherited(true); 2518 New->addAttr(Clone); 2519 AnyAdded = true; 2520 } 2521 2522 // Ensure we have an alignas attribute if the old declaration had one. 2523 if (OldAlignasAttr && !NewAlignasAttr && 2524 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2525 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 return AnyAdded; 2532 } 2533 2534 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2535 const InheritableAttr *Attr, 2536 Sema::AvailabilityMergeKind AMK) { 2537 // This function copies an attribute Attr from a previous declaration to the 2538 // new declaration D if the new declaration doesn't itself have that attribute 2539 // yet or if that attribute allows duplicates. 2540 // If you're adding a new attribute that requires logic different from 2541 // "use explicit attribute on decl if present, else use attribute from 2542 // previous decl", for example if the attribute needs to be consistent 2543 // between redeclarations, you need to call a custom merge function here. 2544 InheritableAttr *NewAttr = nullptr; 2545 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2546 NewAttr = S.mergeAvailabilityAttr( 2547 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2548 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2549 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2550 AA->getPriority()); 2551 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2552 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2553 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2554 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2555 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2556 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2557 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2558 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2559 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2560 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2561 FA->getFirstArg()); 2562 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2563 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2564 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2565 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2566 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2567 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2568 IA->getInheritanceModel()); 2569 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2570 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2571 &S.Context.Idents.get(AA->getSpelling())); 2572 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2573 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2574 isa<CUDAGlobalAttr>(Attr))) { 2575 // CUDA target attributes are part of function signature for 2576 // overloading purposes and must not be merged. 2577 return false; 2578 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2579 NewAttr = S.mergeMinSizeAttr(D, *MA); 2580 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2581 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2582 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2583 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2584 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2585 NewAttr = S.mergeCommonAttr(D, *CommonA); 2586 else if (isa<AlignedAttr>(Attr)) 2587 // AlignedAttrs are handled separately, because we need to handle all 2588 // such attributes on a declaration at the same time. 2589 NewAttr = nullptr; 2590 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2591 (AMK == Sema::AMK_Override || 2592 AMK == Sema::AMK_ProtocolImplementation)) 2593 NewAttr = nullptr; 2594 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2595 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2596 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2597 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2598 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2599 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2600 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2601 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2602 2603 if (NewAttr) { 2604 NewAttr->setInherited(true); 2605 D->addAttr(NewAttr); 2606 if (isa<MSInheritanceAttr>(NewAttr)) 2607 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2608 return true; 2609 } 2610 2611 return false; 2612 } 2613 2614 static const NamedDecl *getDefinition(const Decl *D) { 2615 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2616 return TD->getDefinition(); 2617 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2618 const VarDecl *Def = VD->getDefinition(); 2619 if (Def) 2620 return Def; 2621 return VD->getActingDefinition(); 2622 } 2623 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2624 return FD->getDefinition(); 2625 return nullptr; 2626 } 2627 2628 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2629 for (const auto *Attribute : D->attrs()) 2630 if (Attribute->getKind() == Kind) 2631 return true; 2632 return false; 2633 } 2634 2635 /// checkNewAttributesAfterDef - If we already have a definition, check that 2636 /// there are no new attributes in this declaration. 2637 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2638 if (!New->hasAttrs()) 2639 return; 2640 2641 const NamedDecl *Def = getDefinition(Old); 2642 if (!Def || Def == New) 2643 return; 2644 2645 AttrVec &NewAttributes = New->getAttrs(); 2646 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2647 const Attr *NewAttribute = NewAttributes[I]; 2648 2649 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2651 Sema::SkipBodyInfo SkipBody; 2652 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2653 2654 // If we're skipping this definition, drop the "alias" attribute. 2655 if (SkipBody.ShouldSkip) { 2656 NewAttributes.erase(NewAttributes.begin() + I); 2657 --E; 2658 continue; 2659 } 2660 } else { 2661 VarDecl *VD = cast<VarDecl>(New); 2662 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2663 VarDecl::TentativeDefinition 2664 ? diag::err_alias_after_tentative 2665 : diag::err_redefinition; 2666 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2667 if (Diag == diag::err_redefinition) 2668 S.notePreviousDefinition(Def, VD->getLocation()); 2669 else 2670 S.Diag(Def->getLocation(), diag::note_previous_definition); 2671 VD->setInvalidDecl(); 2672 } 2673 ++I; 2674 continue; 2675 } 2676 2677 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2678 // Tentative definitions are only interesting for the alias check above. 2679 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2680 ++I; 2681 continue; 2682 } 2683 } 2684 2685 if (hasAttribute(Def, NewAttribute->getKind())) { 2686 ++I; 2687 continue; // regular attr merging will take care of validating this. 2688 } 2689 2690 if (isa<C11NoReturnAttr>(NewAttribute)) { 2691 // C's _Noreturn is allowed to be added to a function after it is defined. 2692 ++I; 2693 continue; 2694 } else if (isa<UuidAttr>(NewAttribute)) { 2695 // msvc will allow a subsequent definition to add an uuid to a class 2696 ++I; 2697 continue; 2698 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2699 if (AA->isAlignas()) { 2700 // C++11 [dcl.align]p6: 2701 // if any declaration of an entity has an alignment-specifier, 2702 // every defining declaration of that entity shall specify an 2703 // equivalent alignment. 2704 // C11 6.7.5/7: 2705 // If the definition of an object does not have an alignment 2706 // specifier, any other declaration of that object shall also 2707 // have no alignment specifier. 2708 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2709 << AA; 2710 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2711 << AA; 2712 NewAttributes.erase(NewAttributes.begin() + I); 2713 --E; 2714 continue; 2715 } 2716 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2717 // If there is a C definition followed by a redeclaration with this 2718 // attribute then there are two different definitions. In C++, prefer the 2719 // standard diagnostics. 2720 if (!S.getLangOpts().CPlusPlus) { 2721 S.Diag(NewAttribute->getLocation(), 2722 diag::err_loader_uninitialized_redeclaration); 2723 S.Diag(Def->getLocation(), diag::note_previous_definition); 2724 NewAttributes.erase(NewAttributes.begin() + I); 2725 --E; 2726 continue; 2727 } 2728 } else if (isa<SelectAnyAttr>(NewAttribute) && 2729 cast<VarDecl>(New)->isInline() && 2730 !cast<VarDecl>(New)->isInlineSpecified()) { 2731 // Don't warn about applying selectany to implicitly inline variables. 2732 // Older compilers and language modes would require the use of selectany 2733 // to make such variables inline, and it would have no effect if we 2734 // honored it. 2735 ++I; 2736 continue; 2737 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2738 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2739 // declarations after defintions. 2740 ++I; 2741 continue; 2742 } 2743 2744 S.Diag(NewAttribute->getLocation(), 2745 diag::warn_attribute_precede_definition); 2746 S.Diag(Def->getLocation(), diag::note_previous_definition); 2747 NewAttributes.erase(NewAttributes.begin() + I); 2748 --E; 2749 } 2750 } 2751 2752 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2753 const ConstInitAttr *CIAttr, 2754 bool AttrBeforeInit) { 2755 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2756 2757 // Figure out a good way to write this specifier on the old declaration. 2758 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2759 // enough of the attribute list spelling information to extract that without 2760 // heroics. 2761 std::string SuitableSpelling; 2762 if (S.getLangOpts().CPlusPlus20) 2763 SuitableSpelling = std::string( 2764 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2765 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2766 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2767 InsertLoc, {tok::l_square, tok::l_square, 2768 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2769 S.PP.getIdentifierInfo("require_constant_initialization"), 2770 tok::r_square, tok::r_square})); 2771 if (SuitableSpelling.empty()) 2772 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2773 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2774 S.PP.getIdentifierInfo("require_constant_initialization"), 2775 tok::r_paren, tok::r_paren})); 2776 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2777 SuitableSpelling = "constinit"; 2778 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2779 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2780 if (SuitableSpelling.empty()) 2781 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2782 SuitableSpelling += " "; 2783 2784 if (AttrBeforeInit) { 2785 // extern constinit int a; 2786 // int a = 0; // error (missing 'constinit'), accepted as extension 2787 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2788 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2789 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2790 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2791 } else { 2792 // int a = 0; 2793 // constinit extern int a; // error (missing 'constinit') 2794 S.Diag(CIAttr->getLocation(), 2795 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2796 : diag::warn_require_const_init_added_too_late) 2797 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2798 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2799 << CIAttr->isConstinit() 2800 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2801 } 2802 } 2803 2804 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2805 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2806 AvailabilityMergeKind AMK) { 2807 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2808 UsedAttr *NewAttr = OldAttr->clone(Context); 2809 NewAttr->setInherited(true); 2810 New->addAttr(NewAttr); 2811 } 2812 2813 if (!Old->hasAttrs() && !New->hasAttrs()) 2814 return; 2815 2816 // [dcl.constinit]p1: 2817 // If the [constinit] specifier is applied to any declaration of a 2818 // variable, it shall be applied to the initializing declaration. 2819 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2820 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2821 if (bool(OldConstInit) != bool(NewConstInit)) { 2822 const auto *OldVD = cast<VarDecl>(Old); 2823 auto *NewVD = cast<VarDecl>(New); 2824 2825 // Find the initializing declaration. Note that we might not have linked 2826 // the new declaration into the redeclaration chain yet. 2827 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2828 if (!InitDecl && 2829 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2830 InitDecl = NewVD; 2831 2832 if (InitDecl == NewVD) { 2833 // This is the initializing declaration. If it would inherit 'constinit', 2834 // that's ill-formed. (Note that we do not apply this to the attribute 2835 // form). 2836 if (OldConstInit && OldConstInit->isConstinit()) 2837 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2838 /*AttrBeforeInit=*/true); 2839 } else if (NewConstInit) { 2840 // This is the first time we've been told that this declaration should 2841 // have a constant initializer. If we already saw the initializing 2842 // declaration, this is too late. 2843 if (InitDecl && InitDecl != NewVD) { 2844 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2845 /*AttrBeforeInit=*/false); 2846 NewVD->dropAttr<ConstInitAttr>(); 2847 } 2848 } 2849 } 2850 2851 // Attributes declared post-definition are currently ignored. 2852 checkNewAttributesAfterDef(*this, New, Old); 2853 2854 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2855 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2856 if (!OldA->isEquivalent(NewA)) { 2857 // This redeclaration changes __asm__ label. 2858 Diag(New->getLocation(), diag::err_different_asm_label); 2859 Diag(OldA->getLocation(), diag::note_previous_declaration); 2860 } 2861 } else if (Old->isUsed()) { 2862 // This redeclaration adds an __asm__ label to a declaration that has 2863 // already been ODR-used. 2864 Diag(New->getLocation(), diag::err_late_asm_label_name) 2865 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2866 } 2867 } 2868 2869 // Re-declaration cannot add abi_tag's. 2870 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2871 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2872 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2873 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2874 NewTag) == OldAbiTagAttr->tags_end()) { 2875 Diag(NewAbiTagAttr->getLocation(), 2876 diag::err_new_abi_tag_on_redeclaration) 2877 << NewTag; 2878 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2879 } 2880 } 2881 } else { 2882 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2883 Diag(Old->getLocation(), diag::note_previous_declaration); 2884 } 2885 } 2886 2887 // This redeclaration adds a section attribute. 2888 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2889 if (auto *VD = dyn_cast<VarDecl>(New)) { 2890 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2891 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2892 Diag(Old->getLocation(), diag::note_previous_declaration); 2893 } 2894 } 2895 } 2896 2897 // Redeclaration adds code-seg attribute. 2898 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2899 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2900 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2901 Diag(New->getLocation(), diag::warn_mismatched_section) 2902 << 0 /*codeseg*/; 2903 Diag(Old->getLocation(), diag::note_previous_declaration); 2904 } 2905 2906 if (!Old->hasAttrs()) 2907 return; 2908 2909 bool foundAny = New->hasAttrs(); 2910 2911 // Ensure that any moving of objects within the allocated map is done before 2912 // we process them. 2913 if (!foundAny) New->setAttrs(AttrVec()); 2914 2915 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2916 // Ignore deprecated/unavailable/availability attributes if requested. 2917 AvailabilityMergeKind LocalAMK = AMK_None; 2918 if (isa<DeprecatedAttr>(I) || 2919 isa<UnavailableAttr>(I) || 2920 isa<AvailabilityAttr>(I)) { 2921 switch (AMK) { 2922 case AMK_None: 2923 continue; 2924 2925 case AMK_Redeclaration: 2926 case AMK_Override: 2927 case AMK_ProtocolImplementation: 2928 LocalAMK = AMK; 2929 break; 2930 } 2931 } 2932 2933 // Already handled. 2934 if (isa<UsedAttr>(I)) 2935 continue; 2936 2937 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2938 foundAny = true; 2939 } 2940 2941 if (mergeAlignedAttrs(*this, New, Old)) 2942 foundAny = true; 2943 2944 if (!foundAny) New->dropAttrs(); 2945 } 2946 2947 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2948 /// to the new one. 2949 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2950 const ParmVarDecl *oldDecl, 2951 Sema &S) { 2952 // C++11 [dcl.attr.depend]p2: 2953 // The first declaration of a function shall specify the 2954 // carries_dependency attribute for its declarator-id if any declaration 2955 // of the function specifies the carries_dependency attribute. 2956 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2957 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2958 S.Diag(CDA->getLocation(), 2959 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2960 // Find the first declaration of the parameter. 2961 // FIXME: Should we build redeclaration chains for function parameters? 2962 const FunctionDecl *FirstFD = 2963 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2964 const ParmVarDecl *FirstVD = 2965 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2966 S.Diag(FirstVD->getLocation(), 2967 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2968 } 2969 2970 if (!oldDecl->hasAttrs()) 2971 return; 2972 2973 bool foundAny = newDecl->hasAttrs(); 2974 2975 // Ensure that any moving of objects within the allocated map is 2976 // done before we process them. 2977 if (!foundAny) newDecl->setAttrs(AttrVec()); 2978 2979 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2980 if (!DeclHasAttr(newDecl, I)) { 2981 InheritableAttr *newAttr = 2982 cast<InheritableParamAttr>(I->clone(S.Context)); 2983 newAttr->setInherited(true); 2984 newDecl->addAttr(newAttr); 2985 foundAny = true; 2986 } 2987 } 2988 2989 if (!foundAny) newDecl->dropAttrs(); 2990 } 2991 2992 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2993 const ParmVarDecl *OldParam, 2994 Sema &S) { 2995 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2996 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2997 if (*Oldnullability != *Newnullability) { 2998 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2999 << DiagNullabilityKind( 3000 *Newnullability, 3001 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3002 != 0)) 3003 << DiagNullabilityKind( 3004 *Oldnullability, 3005 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3006 != 0)); 3007 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3008 } 3009 } else { 3010 QualType NewT = NewParam->getType(); 3011 NewT = S.Context.getAttributedType( 3012 AttributedType::getNullabilityAttrKind(*Oldnullability), 3013 NewT, NewT); 3014 NewParam->setType(NewT); 3015 } 3016 } 3017 } 3018 3019 namespace { 3020 3021 /// Used in MergeFunctionDecl to keep track of function parameters in 3022 /// C. 3023 struct GNUCompatibleParamWarning { 3024 ParmVarDecl *OldParm; 3025 ParmVarDecl *NewParm; 3026 QualType PromotedType; 3027 }; 3028 3029 } // end anonymous namespace 3030 3031 // Determine whether the previous declaration was a definition, implicit 3032 // declaration, or a declaration. 3033 template <typename T> 3034 static std::pair<diag::kind, SourceLocation> 3035 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3036 diag::kind PrevDiag; 3037 SourceLocation OldLocation = Old->getLocation(); 3038 if (Old->isThisDeclarationADefinition()) 3039 PrevDiag = diag::note_previous_definition; 3040 else if (Old->isImplicit()) { 3041 PrevDiag = diag::note_previous_implicit_declaration; 3042 if (OldLocation.isInvalid()) 3043 OldLocation = New->getLocation(); 3044 } else 3045 PrevDiag = diag::note_previous_declaration; 3046 return std::make_pair(PrevDiag, OldLocation); 3047 } 3048 3049 /// canRedefineFunction - checks if a function can be redefined. Currently, 3050 /// only extern inline functions can be redefined, and even then only in 3051 /// GNU89 mode. 3052 static bool canRedefineFunction(const FunctionDecl *FD, 3053 const LangOptions& LangOpts) { 3054 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3055 !LangOpts.CPlusPlus && 3056 FD->isInlineSpecified() && 3057 FD->getStorageClass() == SC_Extern); 3058 } 3059 3060 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3061 const AttributedType *AT = T->getAs<AttributedType>(); 3062 while (AT && !AT->isCallingConv()) 3063 AT = AT->getModifiedType()->getAs<AttributedType>(); 3064 return AT; 3065 } 3066 3067 template <typename T> 3068 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3069 const DeclContext *DC = Old->getDeclContext(); 3070 if (DC->isRecord()) 3071 return false; 3072 3073 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3074 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3075 return true; 3076 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3077 return true; 3078 return false; 3079 } 3080 3081 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3082 static bool isExternC(VarTemplateDecl *) { return false; } 3083 3084 /// Check whether a redeclaration of an entity introduced by a 3085 /// using-declaration is valid, given that we know it's not an overload 3086 /// (nor a hidden tag declaration). 3087 template<typename ExpectedDecl> 3088 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3089 ExpectedDecl *New) { 3090 // C++11 [basic.scope.declarative]p4: 3091 // Given a set of declarations in a single declarative region, each of 3092 // which specifies the same unqualified name, 3093 // -- they shall all refer to the same entity, or all refer to functions 3094 // and function templates; or 3095 // -- exactly one declaration shall declare a class name or enumeration 3096 // name that is not a typedef name and the other declarations shall all 3097 // refer to the same variable or enumerator, or all refer to functions 3098 // and function templates; in this case the class name or enumeration 3099 // name is hidden (3.3.10). 3100 3101 // C++11 [namespace.udecl]p14: 3102 // If a function declaration in namespace scope or block scope has the 3103 // same name and the same parameter-type-list as a function introduced 3104 // by a using-declaration, and the declarations do not declare the same 3105 // function, the program is ill-formed. 3106 3107 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3108 if (Old && 3109 !Old->getDeclContext()->getRedeclContext()->Equals( 3110 New->getDeclContext()->getRedeclContext()) && 3111 !(isExternC(Old) && isExternC(New))) 3112 Old = nullptr; 3113 3114 if (!Old) { 3115 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3116 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3117 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3118 return true; 3119 } 3120 return false; 3121 } 3122 3123 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3124 const FunctionDecl *B) { 3125 assert(A->getNumParams() == B->getNumParams()); 3126 3127 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3128 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3129 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3130 if (AttrA == AttrB) 3131 return true; 3132 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3133 AttrA->isDynamic() == AttrB->isDynamic(); 3134 }; 3135 3136 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3137 } 3138 3139 /// If necessary, adjust the semantic declaration context for a qualified 3140 /// declaration to name the correct inline namespace within the qualifier. 3141 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3142 DeclaratorDecl *OldD) { 3143 // The only case where we need to update the DeclContext is when 3144 // redeclaration lookup for a qualified name finds a declaration 3145 // in an inline namespace within the context named by the qualifier: 3146 // 3147 // inline namespace N { int f(); } 3148 // int ::f(); // Sema DC needs adjusting from :: to N::. 3149 // 3150 // For unqualified declarations, the semantic context *can* change 3151 // along the redeclaration chain (for local extern declarations, 3152 // extern "C" declarations, and friend declarations in particular). 3153 if (!NewD->getQualifier()) 3154 return; 3155 3156 // NewD is probably already in the right context. 3157 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3158 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3159 if (NamedDC->Equals(SemaDC)) 3160 return; 3161 3162 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3163 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3164 "unexpected context for redeclaration"); 3165 3166 auto *LexDC = NewD->getLexicalDeclContext(); 3167 auto FixSemaDC = [=](NamedDecl *D) { 3168 if (!D) 3169 return; 3170 D->setDeclContext(SemaDC); 3171 D->setLexicalDeclContext(LexDC); 3172 }; 3173 3174 FixSemaDC(NewD); 3175 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3176 FixSemaDC(FD->getDescribedFunctionTemplate()); 3177 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3178 FixSemaDC(VD->getDescribedVarTemplate()); 3179 } 3180 3181 /// MergeFunctionDecl - We just parsed a function 'New' from 3182 /// declarator D which has the same name and scope as a previous 3183 /// declaration 'Old'. Figure out how to resolve this situation, 3184 /// merging decls or emitting diagnostics as appropriate. 3185 /// 3186 /// In C++, New and Old must be declarations that are not 3187 /// overloaded. Use IsOverload to determine whether New and Old are 3188 /// overloaded, and to select the Old declaration that New should be 3189 /// merged with. 3190 /// 3191 /// Returns true if there was an error, false otherwise. 3192 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3193 Scope *S, bool MergeTypeWithOld) { 3194 // Verify the old decl was also a function. 3195 FunctionDecl *Old = OldD->getAsFunction(); 3196 if (!Old) { 3197 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3198 if (New->getFriendObjectKind()) { 3199 Diag(New->getLocation(), diag::err_using_decl_friend); 3200 Diag(Shadow->getTargetDecl()->getLocation(), 3201 diag::note_using_decl_target); 3202 Diag(Shadow->getUsingDecl()->getLocation(), 3203 diag::note_using_decl) << 0; 3204 return true; 3205 } 3206 3207 // Check whether the two declarations might declare the same function. 3208 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3209 return true; 3210 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3211 } else { 3212 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3213 << New->getDeclName(); 3214 notePreviousDefinition(OldD, New->getLocation()); 3215 return true; 3216 } 3217 } 3218 3219 // If the old declaration is invalid, just give up here. 3220 if (Old->isInvalidDecl()) 3221 return true; 3222 3223 // Disallow redeclaration of some builtins. 3224 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3225 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3226 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3227 << Old << Old->getType(); 3228 return true; 3229 } 3230 3231 diag::kind PrevDiag; 3232 SourceLocation OldLocation; 3233 std::tie(PrevDiag, OldLocation) = 3234 getNoteDiagForInvalidRedeclaration(Old, New); 3235 3236 // Don't complain about this if we're in GNU89 mode and the old function 3237 // is an extern inline function. 3238 // Don't complain about specializations. They are not supposed to have 3239 // storage classes. 3240 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3241 New->getStorageClass() == SC_Static && 3242 Old->hasExternalFormalLinkage() && 3243 !New->getTemplateSpecializationInfo() && 3244 !canRedefineFunction(Old, getLangOpts())) { 3245 if (getLangOpts().MicrosoftExt) { 3246 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3247 Diag(OldLocation, PrevDiag); 3248 } else { 3249 Diag(New->getLocation(), diag::err_static_non_static) << New; 3250 Diag(OldLocation, PrevDiag); 3251 return true; 3252 } 3253 } 3254 3255 if (New->hasAttr<InternalLinkageAttr>() && 3256 !Old->hasAttr<InternalLinkageAttr>()) { 3257 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3258 << New->getDeclName(); 3259 notePreviousDefinition(Old, New->getLocation()); 3260 New->dropAttr<InternalLinkageAttr>(); 3261 } 3262 3263 if (CheckRedeclarationModuleOwnership(New, Old)) 3264 return true; 3265 3266 if (!getLangOpts().CPlusPlus) { 3267 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3268 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3269 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3270 << New << OldOvl; 3271 3272 // Try our best to find a decl that actually has the overloadable 3273 // attribute for the note. In most cases (e.g. programs with only one 3274 // broken declaration/definition), this won't matter. 3275 // 3276 // FIXME: We could do this if we juggled some extra state in 3277 // OverloadableAttr, rather than just removing it. 3278 const Decl *DiagOld = Old; 3279 if (OldOvl) { 3280 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3281 const auto *A = D->getAttr<OverloadableAttr>(); 3282 return A && !A->isImplicit(); 3283 }); 3284 // If we've implicitly added *all* of the overloadable attrs to this 3285 // chain, emitting a "previous redecl" note is pointless. 3286 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3287 } 3288 3289 if (DiagOld) 3290 Diag(DiagOld->getLocation(), 3291 diag::note_attribute_overloadable_prev_overload) 3292 << OldOvl; 3293 3294 if (OldOvl) 3295 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3296 else 3297 New->dropAttr<OverloadableAttr>(); 3298 } 3299 } 3300 3301 // If a function is first declared with a calling convention, but is later 3302 // declared or defined without one, all following decls assume the calling 3303 // convention of the first. 3304 // 3305 // It's OK if a function is first declared without a calling convention, 3306 // but is later declared or defined with the default calling convention. 3307 // 3308 // To test if either decl has an explicit calling convention, we look for 3309 // AttributedType sugar nodes on the type as written. If they are missing or 3310 // were canonicalized away, we assume the calling convention was implicit. 3311 // 3312 // Note also that we DO NOT return at this point, because we still have 3313 // other tests to run. 3314 QualType OldQType = Context.getCanonicalType(Old->getType()); 3315 QualType NewQType = Context.getCanonicalType(New->getType()); 3316 const FunctionType *OldType = cast<FunctionType>(OldQType); 3317 const FunctionType *NewType = cast<FunctionType>(NewQType); 3318 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3319 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3320 bool RequiresAdjustment = false; 3321 3322 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3323 FunctionDecl *First = Old->getFirstDecl(); 3324 const FunctionType *FT = 3325 First->getType().getCanonicalType()->castAs<FunctionType>(); 3326 FunctionType::ExtInfo FI = FT->getExtInfo(); 3327 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3328 if (!NewCCExplicit) { 3329 // Inherit the CC from the previous declaration if it was specified 3330 // there but not here. 3331 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3332 RequiresAdjustment = true; 3333 } else if (New->getBuiltinID()) { 3334 // Calling Conventions on a Builtin aren't really useful and setting a 3335 // default calling convention and cdecl'ing some builtin redeclarations is 3336 // common, so warn and ignore the calling convention on the redeclaration. 3337 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3338 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3339 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3340 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3341 RequiresAdjustment = true; 3342 } else { 3343 // Calling conventions aren't compatible, so complain. 3344 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3345 Diag(New->getLocation(), diag::err_cconv_change) 3346 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3347 << !FirstCCExplicit 3348 << (!FirstCCExplicit ? "" : 3349 FunctionType::getNameForCallConv(FI.getCC())); 3350 3351 // Put the note on the first decl, since it is the one that matters. 3352 Diag(First->getLocation(), diag::note_previous_declaration); 3353 return true; 3354 } 3355 } 3356 3357 // FIXME: diagnose the other way around? 3358 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3359 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3360 RequiresAdjustment = true; 3361 } 3362 3363 // Merge regparm attribute. 3364 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3365 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3366 if (NewTypeInfo.getHasRegParm()) { 3367 Diag(New->getLocation(), diag::err_regparm_mismatch) 3368 << NewType->getRegParmType() 3369 << OldType->getRegParmType(); 3370 Diag(OldLocation, diag::note_previous_declaration); 3371 return true; 3372 } 3373 3374 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3375 RequiresAdjustment = true; 3376 } 3377 3378 // Merge ns_returns_retained attribute. 3379 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3380 if (NewTypeInfo.getProducesResult()) { 3381 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3382 << "'ns_returns_retained'"; 3383 Diag(OldLocation, diag::note_previous_declaration); 3384 return true; 3385 } 3386 3387 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3388 RequiresAdjustment = true; 3389 } 3390 3391 if (OldTypeInfo.getNoCallerSavedRegs() != 3392 NewTypeInfo.getNoCallerSavedRegs()) { 3393 if (NewTypeInfo.getNoCallerSavedRegs()) { 3394 AnyX86NoCallerSavedRegistersAttr *Attr = 3395 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3396 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3397 Diag(OldLocation, diag::note_previous_declaration); 3398 return true; 3399 } 3400 3401 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3402 RequiresAdjustment = true; 3403 } 3404 3405 if (RequiresAdjustment) { 3406 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3407 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3408 New->setType(QualType(AdjustedType, 0)); 3409 NewQType = Context.getCanonicalType(New->getType()); 3410 } 3411 3412 // If this redeclaration makes the function inline, we may need to add it to 3413 // UndefinedButUsed. 3414 if (!Old->isInlined() && New->isInlined() && 3415 !New->hasAttr<GNUInlineAttr>() && 3416 !getLangOpts().GNUInline && 3417 Old->isUsed(false) && 3418 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3419 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3420 SourceLocation())); 3421 3422 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3423 // about it. 3424 if (New->hasAttr<GNUInlineAttr>() && 3425 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3426 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3427 } 3428 3429 // If pass_object_size params don't match up perfectly, this isn't a valid 3430 // redeclaration. 3431 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3432 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3433 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3434 << New->getDeclName(); 3435 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3436 return true; 3437 } 3438 3439 if (getLangOpts().CPlusPlus) { 3440 // C++1z [over.load]p2 3441 // Certain function declarations cannot be overloaded: 3442 // -- Function declarations that differ only in the return type, 3443 // the exception specification, or both cannot be overloaded. 3444 3445 // Check the exception specifications match. This may recompute the type of 3446 // both Old and New if it resolved exception specifications, so grab the 3447 // types again after this. Because this updates the type, we do this before 3448 // any of the other checks below, which may update the "de facto" NewQType 3449 // but do not necessarily update the type of New. 3450 if (CheckEquivalentExceptionSpec(Old, New)) 3451 return true; 3452 OldQType = Context.getCanonicalType(Old->getType()); 3453 NewQType = Context.getCanonicalType(New->getType()); 3454 3455 // Go back to the type source info to compare the declared return types, 3456 // per C++1y [dcl.type.auto]p13: 3457 // Redeclarations or specializations of a function or function template 3458 // with a declared return type that uses a placeholder type shall also 3459 // use that placeholder, not a deduced type. 3460 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3461 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3462 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3463 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3464 OldDeclaredReturnType)) { 3465 QualType ResQT; 3466 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3467 OldDeclaredReturnType->isObjCObjectPointerType()) 3468 // FIXME: This does the wrong thing for a deduced return type. 3469 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3470 if (ResQT.isNull()) { 3471 if (New->isCXXClassMember() && New->isOutOfLine()) 3472 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3473 << New << New->getReturnTypeSourceRange(); 3474 else 3475 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3476 << New->getReturnTypeSourceRange(); 3477 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3478 << Old->getReturnTypeSourceRange(); 3479 return true; 3480 } 3481 else 3482 NewQType = ResQT; 3483 } 3484 3485 QualType OldReturnType = OldType->getReturnType(); 3486 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3487 if (OldReturnType != NewReturnType) { 3488 // If this function has a deduced return type and has already been 3489 // defined, copy the deduced value from the old declaration. 3490 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3491 if (OldAT && OldAT->isDeduced()) { 3492 New->setType( 3493 SubstAutoType(New->getType(), 3494 OldAT->isDependentType() ? Context.DependentTy 3495 : OldAT->getDeducedType())); 3496 NewQType = Context.getCanonicalType( 3497 SubstAutoType(NewQType, 3498 OldAT->isDependentType() ? Context.DependentTy 3499 : OldAT->getDeducedType())); 3500 } 3501 } 3502 3503 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3504 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3505 if (OldMethod && NewMethod) { 3506 // Preserve triviality. 3507 NewMethod->setTrivial(OldMethod->isTrivial()); 3508 3509 // MSVC allows explicit template specialization at class scope: 3510 // 2 CXXMethodDecls referring to the same function will be injected. 3511 // We don't want a redeclaration error. 3512 bool IsClassScopeExplicitSpecialization = 3513 OldMethod->isFunctionTemplateSpecialization() && 3514 NewMethod->isFunctionTemplateSpecialization(); 3515 bool isFriend = NewMethod->getFriendObjectKind(); 3516 3517 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3518 !IsClassScopeExplicitSpecialization) { 3519 // -- Member function declarations with the same name and the 3520 // same parameter types cannot be overloaded if any of them 3521 // is a static member function declaration. 3522 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3523 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3524 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3525 return true; 3526 } 3527 3528 // C++ [class.mem]p1: 3529 // [...] A member shall not be declared twice in the 3530 // member-specification, except that a nested class or member 3531 // class template can be declared and then later defined. 3532 if (!inTemplateInstantiation()) { 3533 unsigned NewDiag; 3534 if (isa<CXXConstructorDecl>(OldMethod)) 3535 NewDiag = diag::err_constructor_redeclared; 3536 else if (isa<CXXDestructorDecl>(NewMethod)) 3537 NewDiag = diag::err_destructor_redeclared; 3538 else if (isa<CXXConversionDecl>(NewMethod)) 3539 NewDiag = diag::err_conv_function_redeclared; 3540 else 3541 NewDiag = diag::err_member_redeclared; 3542 3543 Diag(New->getLocation(), NewDiag); 3544 } else { 3545 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3546 << New << New->getType(); 3547 } 3548 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3549 return true; 3550 3551 // Complain if this is an explicit declaration of a special 3552 // member that was initially declared implicitly. 3553 // 3554 // As an exception, it's okay to befriend such methods in order 3555 // to permit the implicit constructor/destructor/operator calls. 3556 } else if (OldMethod->isImplicit()) { 3557 if (isFriend) { 3558 NewMethod->setImplicit(); 3559 } else { 3560 Diag(NewMethod->getLocation(), 3561 diag::err_definition_of_implicitly_declared_member) 3562 << New << getSpecialMember(OldMethod); 3563 return true; 3564 } 3565 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3566 Diag(NewMethod->getLocation(), 3567 diag::err_definition_of_explicitly_defaulted_member) 3568 << getSpecialMember(OldMethod); 3569 return true; 3570 } 3571 } 3572 3573 // C++11 [dcl.attr.noreturn]p1: 3574 // The first declaration of a function shall specify the noreturn 3575 // attribute if any declaration of that function specifies the noreturn 3576 // attribute. 3577 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3578 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3579 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3580 Diag(Old->getFirstDecl()->getLocation(), 3581 diag::note_noreturn_missing_first_decl); 3582 } 3583 3584 // C++11 [dcl.attr.depend]p2: 3585 // The first declaration of a function shall specify the 3586 // carries_dependency attribute for its declarator-id if any declaration 3587 // of the function specifies the carries_dependency attribute. 3588 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3589 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3590 Diag(CDA->getLocation(), 3591 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3592 Diag(Old->getFirstDecl()->getLocation(), 3593 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3594 } 3595 3596 // (C++98 8.3.5p3): 3597 // All declarations for a function shall agree exactly in both the 3598 // return type and the parameter-type-list. 3599 // We also want to respect all the extended bits except noreturn. 3600 3601 // noreturn should now match unless the old type info didn't have it. 3602 QualType OldQTypeForComparison = OldQType; 3603 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3604 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3605 const FunctionType *OldTypeForComparison 3606 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3607 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3608 assert(OldQTypeForComparison.isCanonical()); 3609 } 3610 3611 if (haveIncompatibleLanguageLinkages(Old, New)) { 3612 // As a special case, retain the language linkage from previous 3613 // declarations of a friend function as an extension. 3614 // 3615 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3616 // and is useful because there's otherwise no way to specify language 3617 // linkage within class scope. 3618 // 3619 // Check cautiously as the friend object kind isn't yet complete. 3620 if (New->getFriendObjectKind() != Decl::FOK_None) { 3621 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3622 Diag(OldLocation, PrevDiag); 3623 } else { 3624 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3625 Diag(OldLocation, PrevDiag); 3626 return true; 3627 } 3628 } 3629 3630 // If the function types are compatible, merge the declarations. Ignore the 3631 // exception specifier because it was already checked above in 3632 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3633 // about incompatible types under -fms-compatibility. 3634 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3635 NewQType)) 3636 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3637 3638 // If the types are imprecise (due to dependent constructs in friends or 3639 // local extern declarations), it's OK if they differ. We'll check again 3640 // during instantiation. 3641 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3642 return false; 3643 3644 // Fall through for conflicting redeclarations and redefinitions. 3645 } 3646 3647 // C: Function types need to be compatible, not identical. This handles 3648 // duplicate function decls like "void f(int); void f(enum X);" properly. 3649 if (!getLangOpts().CPlusPlus && 3650 Context.typesAreCompatible(OldQType, NewQType)) { 3651 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3652 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3653 const FunctionProtoType *OldProto = nullptr; 3654 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3655 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3656 // The old declaration provided a function prototype, but the 3657 // new declaration does not. Merge in the prototype. 3658 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3659 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3660 NewQType = 3661 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3662 OldProto->getExtProtoInfo()); 3663 New->setType(NewQType); 3664 New->setHasInheritedPrototype(); 3665 3666 // Synthesize parameters with the same types. 3667 SmallVector<ParmVarDecl*, 16> Params; 3668 for (const auto &ParamType : OldProto->param_types()) { 3669 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3670 SourceLocation(), nullptr, 3671 ParamType, /*TInfo=*/nullptr, 3672 SC_None, nullptr); 3673 Param->setScopeInfo(0, Params.size()); 3674 Param->setImplicit(); 3675 Params.push_back(Param); 3676 } 3677 3678 New->setParams(Params); 3679 } 3680 3681 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3682 } 3683 3684 // Check if the function types are compatible when pointer size address 3685 // spaces are ignored. 3686 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3687 return false; 3688 3689 // GNU C permits a K&R definition to follow a prototype declaration 3690 // if the declared types of the parameters in the K&R definition 3691 // match the types in the prototype declaration, even when the 3692 // promoted types of the parameters from the K&R definition differ 3693 // from the types in the prototype. GCC then keeps the types from 3694 // the prototype. 3695 // 3696 // If a variadic prototype is followed by a non-variadic K&R definition, 3697 // the K&R definition becomes variadic. This is sort of an edge case, but 3698 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3699 // C99 6.9.1p8. 3700 if (!getLangOpts().CPlusPlus && 3701 Old->hasPrototype() && !New->hasPrototype() && 3702 New->getType()->getAs<FunctionProtoType>() && 3703 Old->getNumParams() == New->getNumParams()) { 3704 SmallVector<QualType, 16> ArgTypes; 3705 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3706 const FunctionProtoType *OldProto 3707 = Old->getType()->getAs<FunctionProtoType>(); 3708 const FunctionProtoType *NewProto 3709 = New->getType()->getAs<FunctionProtoType>(); 3710 3711 // Determine whether this is the GNU C extension. 3712 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3713 NewProto->getReturnType()); 3714 bool LooseCompatible = !MergedReturn.isNull(); 3715 for (unsigned Idx = 0, End = Old->getNumParams(); 3716 LooseCompatible && Idx != End; ++Idx) { 3717 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3718 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3719 if (Context.typesAreCompatible(OldParm->getType(), 3720 NewProto->getParamType(Idx))) { 3721 ArgTypes.push_back(NewParm->getType()); 3722 } else if (Context.typesAreCompatible(OldParm->getType(), 3723 NewParm->getType(), 3724 /*CompareUnqualified=*/true)) { 3725 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3726 NewProto->getParamType(Idx) }; 3727 Warnings.push_back(Warn); 3728 ArgTypes.push_back(NewParm->getType()); 3729 } else 3730 LooseCompatible = false; 3731 } 3732 3733 if (LooseCompatible) { 3734 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3735 Diag(Warnings[Warn].NewParm->getLocation(), 3736 diag::ext_param_promoted_not_compatible_with_prototype) 3737 << Warnings[Warn].PromotedType 3738 << Warnings[Warn].OldParm->getType(); 3739 if (Warnings[Warn].OldParm->getLocation().isValid()) 3740 Diag(Warnings[Warn].OldParm->getLocation(), 3741 diag::note_previous_declaration); 3742 } 3743 3744 if (MergeTypeWithOld) 3745 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3746 OldProto->getExtProtoInfo())); 3747 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3748 } 3749 3750 // Fall through to diagnose conflicting types. 3751 } 3752 3753 // A function that has already been declared has been redeclared or 3754 // defined with a different type; show an appropriate diagnostic. 3755 3756 // If the previous declaration was an implicitly-generated builtin 3757 // declaration, then at the very least we should use a specialized note. 3758 unsigned BuiltinID; 3759 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3760 // If it's actually a library-defined builtin function like 'malloc' 3761 // or 'printf', just warn about the incompatible redeclaration. 3762 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3763 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3764 Diag(OldLocation, diag::note_previous_builtin_declaration) 3765 << Old << Old->getType(); 3766 3767 // If this is a global redeclaration, just forget hereafter 3768 // about the "builtin-ness" of the function. 3769 // 3770 // Doing this for local extern declarations is problematic. If 3771 // the builtin declaration remains visible, a second invalid 3772 // local declaration will produce a hard error; if it doesn't 3773 // remain visible, a single bogus local redeclaration (which is 3774 // actually only a warning) could break all the downstream code. 3775 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3776 New->getIdentifier()->revertBuiltin(); 3777 3778 return false; 3779 } 3780 3781 PrevDiag = diag::note_previous_builtin_declaration; 3782 } 3783 3784 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3785 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3786 return true; 3787 } 3788 3789 /// Completes the merge of two function declarations that are 3790 /// known to be compatible. 3791 /// 3792 /// This routine handles the merging of attributes and other 3793 /// properties of function declarations from the old declaration to 3794 /// the new declaration, once we know that New is in fact a 3795 /// redeclaration of Old. 3796 /// 3797 /// \returns false 3798 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3799 Scope *S, bool MergeTypeWithOld) { 3800 // Merge the attributes 3801 mergeDeclAttributes(New, Old); 3802 3803 // Merge "pure" flag. 3804 if (Old->isPure()) 3805 New->setPure(); 3806 3807 // Merge "used" flag. 3808 if (Old->getMostRecentDecl()->isUsed(false)) 3809 New->setIsUsed(); 3810 3811 // Merge attributes from the parameters. These can mismatch with K&R 3812 // declarations. 3813 if (New->getNumParams() == Old->getNumParams()) 3814 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3815 ParmVarDecl *NewParam = New->getParamDecl(i); 3816 ParmVarDecl *OldParam = Old->getParamDecl(i); 3817 mergeParamDeclAttributes(NewParam, OldParam, *this); 3818 mergeParamDeclTypes(NewParam, OldParam, *this); 3819 } 3820 3821 if (getLangOpts().CPlusPlus) 3822 return MergeCXXFunctionDecl(New, Old, S); 3823 3824 // Merge the function types so the we get the composite types for the return 3825 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3826 // was visible. 3827 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3828 if (!Merged.isNull() && MergeTypeWithOld) 3829 New->setType(Merged); 3830 3831 return false; 3832 } 3833 3834 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3835 ObjCMethodDecl *oldMethod) { 3836 // Merge the attributes, including deprecated/unavailable 3837 AvailabilityMergeKind MergeKind = 3838 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3839 ? AMK_ProtocolImplementation 3840 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3841 : AMK_Override; 3842 3843 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3844 3845 // Merge attributes from the parameters. 3846 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3847 oe = oldMethod->param_end(); 3848 for (ObjCMethodDecl::param_iterator 3849 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3850 ni != ne && oi != oe; ++ni, ++oi) 3851 mergeParamDeclAttributes(*ni, *oi, *this); 3852 3853 CheckObjCMethodOverride(newMethod, oldMethod); 3854 } 3855 3856 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3857 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3858 3859 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3860 ? diag::err_redefinition_different_type 3861 : diag::err_redeclaration_different_type) 3862 << New->getDeclName() << New->getType() << Old->getType(); 3863 3864 diag::kind PrevDiag; 3865 SourceLocation OldLocation; 3866 std::tie(PrevDiag, OldLocation) 3867 = getNoteDiagForInvalidRedeclaration(Old, New); 3868 S.Diag(OldLocation, PrevDiag); 3869 New->setInvalidDecl(); 3870 } 3871 3872 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3873 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3874 /// emitting diagnostics as appropriate. 3875 /// 3876 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3877 /// to here in AddInitializerToDecl. We can't check them before the initializer 3878 /// is attached. 3879 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3880 bool MergeTypeWithOld) { 3881 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3882 return; 3883 3884 QualType MergedT; 3885 if (getLangOpts().CPlusPlus) { 3886 if (New->getType()->isUndeducedType()) { 3887 // We don't know what the new type is until the initializer is attached. 3888 return; 3889 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3890 // These could still be something that needs exception specs checked. 3891 return MergeVarDeclExceptionSpecs(New, Old); 3892 } 3893 // C++ [basic.link]p10: 3894 // [...] the types specified by all declarations referring to a given 3895 // object or function shall be identical, except that declarations for an 3896 // array object can specify array types that differ by the presence or 3897 // absence of a major array bound (8.3.4). 3898 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3899 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3900 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3901 3902 // We are merging a variable declaration New into Old. If it has an array 3903 // bound, and that bound differs from Old's bound, we should diagnose the 3904 // mismatch. 3905 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3906 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3907 PrevVD = PrevVD->getPreviousDecl()) { 3908 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3909 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3910 continue; 3911 3912 if (!Context.hasSameType(NewArray, PrevVDTy)) 3913 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3914 } 3915 } 3916 3917 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3918 if (Context.hasSameType(OldArray->getElementType(), 3919 NewArray->getElementType())) 3920 MergedT = New->getType(); 3921 } 3922 // FIXME: Check visibility. New is hidden but has a complete type. If New 3923 // has no array bound, it should not inherit one from Old, if Old is not 3924 // visible. 3925 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3926 if (Context.hasSameType(OldArray->getElementType(), 3927 NewArray->getElementType())) 3928 MergedT = Old->getType(); 3929 } 3930 } 3931 else if (New->getType()->isObjCObjectPointerType() && 3932 Old->getType()->isObjCObjectPointerType()) { 3933 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3934 Old->getType()); 3935 } 3936 } else { 3937 // C 6.2.7p2: 3938 // All declarations that refer to the same object or function shall have 3939 // compatible type. 3940 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3941 } 3942 if (MergedT.isNull()) { 3943 // It's OK if we couldn't merge types if either type is dependent, for a 3944 // block-scope variable. In other cases (static data members of class 3945 // templates, variable templates, ...), we require the types to be 3946 // equivalent. 3947 // FIXME: The C++ standard doesn't say anything about this. 3948 if ((New->getType()->isDependentType() || 3949 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3950 // If the old type was dependent, we can't merge with it, so the new type 3951 // becomes dependent for now. We'll reproduce the original type when we 3952 // instantiate the TypeSourceInfo for the variable. 3953 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3954 New->setType(Context.DependentTy); 3955 return; 3956 } 3957 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3958 } 3959 3960 // Don't actually update the type on the new declaration if the old 3961 // declaration was an extern declaration in a different scope. 3962 if (MergeTypeWithOld) 3963 New->setType(MergedT); 3964 } 3965 3966 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3967 LookupResult &Previous) { 3968 // C11 6.2.7p4: 3969 // For an identifier with internal or external linkage declared 3970 // in a scope in which a prior declaration of that identifier is 3971 // visible, if the prior declaration specifies internal or 3972 // external linkage, the type of the identifier at the later 3973 // declaration becomes the composite type. 3974 // 3975 // If the variable isn't visible, we do not merge with its type. 3976 if (Previous.isShadowed()) 3977 return false; 3978 3979 if (S.getLangOpts().CPlusPlus) { 3980 // C++11 [dcl.array]p3: 3981 // If there is a preceding declaration of the entity in the same 3982 // scope in which the bound was specified, an omitted array bound 3983 // is taken to be the same as in that earlier declaration. 3984 return NewVD->isPreviousDeclInSameBlockScope() || 3985 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3986 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3987 } else { 3988 // If the old declaration was function-local, don't merge with its 3989 // type unless we're in the same function. 3990 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3991 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3992 } 3993 } 3994 3995 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3996 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3997 /// situation, merging decls or emitting diagnostics as appropriate. 3998 /// 3999 /// Tentative definition rules (C99 6.9.2p2) are checked by 4000 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4001 /// definitions here, since the initializer hasn't been attached. 4002 /// 4003 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4004 // If the new decl is already invalid, don't do any other checking. 4005 if (New->isInvalidDecl()) 4006 return; 4007 4008 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4009 return; 4010 4011 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4012 4013 // Verify the old decl was also a variable or variable template. 4014 VarDecl *Old = nullptr; 4015 VarTemplateDecl *OldTemplate = nullptr; 4016 if (Previous.isSingleResult()) { 4017 if (NewTemplate) { 4018 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4019 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4020 4021 if (auto *Shadow = 4022 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4023 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4024 return New->setInvalidDecl(); 4025 } else { 4026 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4027 4028 if (auto *Shadow = 4029 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4030 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4031 return New->setInvalidDecl(); 4032 } 4033 } 4034 if (!Old) { 4035 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4036 << New->getDeclName(); 4037 notePreviousDefinition(Previous.getRepresentativeDecl(), 4038 New->getLocation()); 4039 return New->setInvalidDecl(); 4040 } 4041 4042 // Ensure the template parameters are compatible. 4043 if (NewTemplate && 4044 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4045 OldTemplate->getTemplateParameters(), 4046 /*Complain=*/true, TPL_TemplateMatch)) 4047 return New->setInvalidDecl(); 4048 4049 // C++ [class.mem]p1: 4050 // A member shall not be declared twice in the member-specification [...] 4051 // 4052 // Here, we need only consider static data members. 4053 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4054 Diag(New->getLocation(), diag::err_duplicate_member) 4055 << New->getIdentifier(); 4056 Diag(Old->getLocation(), diag::note_previous_declaration); 4057 New->setInvalidDecl(); 4058 } 4059 4060 mergeDeclAttributes(New, Old); 4061 // Warn if an already-declared variable is made a weak_import in a subsequent 4062 // declaration 4063 if (New->hasAttr<WeakImportAttr>() && 4064 Old->getStorageClass() == SC_None && 4065 !Old->hasAttr<WeakImportAttr>()) { 4066 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4067 notePreviousDefinition(Old, New->getLocation()); 4068 // Remove weak_import attribute on new declaration. 4069 New->dropAttr<WeakImportAttr>(); 4070 } 4071 4072 if (New->hasAttr<InternalLinkageAttr>() && 4073 !Old->hasAttr<InternalLinkageAttr>()) { 4074 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4075 << New->getDeclName(); 4076 notePreviousDefinition(Old, New->getLocation()); 4077 New->dropAttr<InternalLinkageAttr>(); 4078 } 4079 4080 // Merge the types. 4081 VarDecl *MostRecent = Old->getMostRecentDecl(); 4082 if (MostRecent != Old) { 4083 MergeVarDeclTypes(New, MostRecent, 4084 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4085 if (New->isInvalidDecl()) 4086 return; 4087 } 4088 4089 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4090 if (New->isInvalidDecl()) 4091 return; 4092 4093 diag::kind PrevDiag; 4094 SourceLocation OldLocation; 4095 std::tie(PrevDiag, OldLocation) = 4096 getNoteDiagForInvalidRedeclaration(Old, New); 4097 4098 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4099 if (New->getStorageClass() == SC_Static && 4100 !New->isStaticDataMember() && 4101 Old->hasExternalFormalLinkage()) { 4102 if (getLangOpts().MicrosoftExt) { 4103 Diag(New->getLocation(), diag::ext_static_non_static) 4104 << New->getDeclName(); 4105 Diag(OldLocation, PrevDiag); 4106 } else { 4107 Diag(New->getLocation(), diag::err_static_non_static) 4108 << New->getDeclName(); 4109 Diag(OldLocation, PrevDiag); 4110 return New->setInvalidDecl(); 4111 } 4112 } 4113 // C99 6.2.2p4: 4114 // For an identifier declared with the storage-class specifier 4115 // extern in a scope in which a prior declaration of that 4116 // identifier is visible,23) if the prior declaration specifies 4117 // internal or external linkage, the linkage of the identifier at 4118 // the later declaration is the same as the linkage specified at 4119 // the prior declaration. If no prior declaration is visible, or 4120 // if the prior declaration specifies no linkage, then the 4121 // identifier has external linkage. 4122 if (New->hasExternalStorage() && Old->hasLinkage()) 4123 /* Okay */; 4124 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4125 !New->isStaticDataMember() && 4126 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4127 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4128 Diag(OldLocation, PrevDiag); 4129 return New->setInvalidDecl(); 4130 } 4131 4132 // Check if extern is followed by non-extern and vice-versa. 4133 if (New->hasExternalStorage() && 4134 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4135 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4136 Diag(OldLocation, PrevDiag); 4137 return New->setInvalidDecl(); 4138 } 4139 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4140 !New->hasExternalStorage()) { 4141 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4142 Diag(OldLocation, PrevDiag); 4143 return New->setInvalidDecl(); 4144 } 4145 4146 if (CheckRedeclarationModuleOwnership(New, Old)) 4147 return; 4148 4149 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4150 4151 // FIXME: The test for external storage here seems wrong? We still 4152 // need to check for mismatches. 4153 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4154 // Don't complain about out-of-line definitions of static members. 4155 !(Old->getLexicalDeclContext()->isRecord() && 4156 !New->getLexicalDeclContext()->isRecord())) { 4157 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4158 Diag(OldLocation, PrevDiag); 4159 return New->setInvalidDecl(); 4160 } 4161 4162 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4163 if (VarDecl *Def = Old->getDefinition()) { 4164 // C++1z [dcl.fcn.spec]p4: 4165 // If the definition of a variable appears in a translation unit before 4166 // its first declaration as inline, the program is ill-formed. 4167 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4168 Diag(Def->getLocation(), diag::note_previous_definition); 4169 } 4170 } 4171 4172 // If this redeclaration makes the variable inline, we may need to add it to 4173 // UndefinedButUsed. 4174 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4175 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4176 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4177 SourceLocation())); 4178 4179 if (New->getTLSKind() != Old->getTLSKind()) { 4180 if (!Old->getTLSKind()) { 4181 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4182 Diag(OldLocation, PrevDiag); 4183 } else if (!New->getTLSKind()) { 4184 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4185 Diag(OldLocation, PrevDiag); 4186 } else { 4187 // Do not allow redeclaration to change the variable between requiring 4188 // static and dynamic initialization. 4189 // FIXME: GCC allows this, but uses the TLS keyword on the first 4190 // declaration to determine the kind. Do we need to be compatible here? 4191 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4192 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4193 Diag(OldLocation, PrevDiag); 4194 } 4195 } 4196 4197 // C++ doesn't have tentative definitions, so go right ahead and check here. 4198 if (getLangOpts().CPlusPlus && 4199 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4200 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4201 Old->getCanonicalDecl()->isConstexpr()) { 4202 // This definition won't be a definition any more once it's been merged. 4203 Diag(New->getLocation(), 4204 diag::warn_deprecated_redundant_constexpr_static_def); 4205 } else if (VarDecl *Def = Old->getDefinition()) { 4206 if (checkVarDeclRedefinition(Def, New)) 4207 return; 4208 } 4209 } 4210 4211 if (haveIncompatibleLanguageLinkages(Old, New)) { 4212 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4213 Diag(OldLocation, PrevDiag); 4214 New->setInvalidDecl(); 4215 return; 4216 } 4217 4218 // Merge "used" flag. 4219 if (Old->getMostRecentDecl()->isUsed(false)) 4220 New->setIsUsed(); 4221 4222 // Keep a chain of previous declarations. 4223 New->setPreviousDecl(Old); 4224 if (NewTemplate) 4225 NewTemplate->setPreviousDecl(OldTemplate); 4226 adjustDeclContextForDeclaratorDecl(New, Old); 4227 4228 // Inherit access appropriately. 4229 New->setAccess(Old->getAccess()); 4230 if (NewTemplate) 4231 NewTemplate->setAccess(New->getAccess()); 4232 4233 if (Old->isInline()) 4234 New->setImplicitlyInline(); 4235 } 4236 4237 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4238 SourceManager &SrcMgr = getSourceManager(); 4239 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4240 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4241 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4242 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4243 auto &HSI = PP.getHeaderSearchInfo(); 4244 StringRef HdrFilename = 4245 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4246 4247 auto noteFromModuleOrInclude = [&](Module *Mod, 4248 SourceLocation IncLoc) -> bool { 4249 // Redefinition errors with modules are common with non modular mapped 4250 // headers, example: a non-modular header H in module A that also gets 4251 // included directly in a TU. Pointing twice to the same header/definition 4252 // is confusing, try to get better diagnostics when modules is on. 4253 if (IncLoc.isValid()) { 4254 if (Mod) { 4255 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4256 << HdrFilename.str() << Mod->getFullModuleName(); 4257 if (!Mod->DefinitionLoc.isInvalid()) 4258 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4259 << Mod->getFullModuleName(); 4260 } else { 4261 Diag(IncLoc, diag::note_redefinition_include_same_file) 4262 << HdrFilename.str(); 4263 } 4264 return true; 4265 } 4266 4267 return false; 4268 }; 4269 4270 // Is it the same file and same offset? Provide more information on why 4271 // this leads to a redefinition error. 4272 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4273 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4274 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4275 bool EmittedDiag = 4276 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4277 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4278 4279 // If the header has no guards, emit a note suggesting one. 4280 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4281 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4282 4283 if (EmittedDiag) 4284 return; 4285 } 4286 4287 // Redefinition coming from different files or couldn't do better above. 4288 if (Old->getLocation().isValid()) 4289 Diag(Old->getLocation(), diag::note_previous_definition); 4290 } 4291 4292 /// We've just determined that \p Old and \p New both appear to be definitions 4293 /// of the same variable. Either diagnose or fix the problem. 4294 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4295 if (!hasVisibleDefinition(Old) && 4296 (New->getFormalLinkage() == InternalLinkage || 4297 New->isInline() || 4298 New->getDescribedVarTemplate() || 4299 New->getNumTemplateParameterLists() || 4300 New->getDeclContext()->isDependentContext())) { 4301 // The previous definition is hidden, and multiple definitions are 4302 // permitted (in separate TUs). Demote this to a declaration. 4303 New->demoteThisDefinitionToDeclaration(); 4304 4305 // Make the canonical definition visible. 4306 if (auto *OldTD = Old->getDescribedVarTemplate()) 4307 makeMergedDefinitionVisible(OldTD); 4308 makeMergedDefinitionVisible(Old); 4309 return false; 4310 } else { 4311 Diag(New->getLocation(), diag::err_redefinition) << New; 4312 notePreviousDefinition(Old, New->getLocation()); 4313 New->setInvalidDecl(); 4314 return true; 4315 } 4316 } 4317 4318 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4319 /// no declarator (e.g. "struct foo;") is parsed. 4320 Decl * 4321 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4322 RecordDecl *&AnonRecord) { 4323 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4324 AnonRecord); 4325 } 4326 4327 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4328 // disambiguate entities defined in different scopes. 4329 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4330 // compatibility. 4331 // We will pick our mangling number depending on which version of MSVC is being 4332 // targeted. 4333 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4334 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4335 ? S->getMSCurManglingNumber() 4336 : S->getMSLastManglingNumber(); 4337 } 4338 4339 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4340 if (!Context.getLangOpts().CPlusPlus) 4341 return; 4342 4343 if (isa<CXXRecordDecl>(Tag->getParent())) { 4344 // If this tag is the direct child of a class, number it if 4345 // it is anonymous. 4346 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4347 return; 4348 MangleNumberingContext &MCtx = 4349 Context.getManglingNumberContext(Tag->getParent()); 4350 Context.setManglingNumber( 4351 Tag, MCtx.getManglingNumber( 4352 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4353 return; 4354 } 4355 4356 // If this tag isn't a direct child of a class, number it if it is local. 4357 MangleNumberingContext *MCtx; 4358 Decl *ManglingContextDecl; 4359 std::tie(MCtx, ManglingContextDecl) = 4360 getCurrentMangleNumberContext(Tag->getDeclContext()); 4361 if (MCtx) { 4362 Context.setManglingNumber( 4363 Tag, MCtx->getManglingNumber( 4364 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4365 } 4366 } 4367 4368 namespace { 4369 struct NonCLikeKind { 4370 enum { 4371 None, 4372 BaseClass, 4373 DefaultMemberInit, 4374 Lambda, 4375 Friend, 4376 OtherMember, 4377 Invalid, 4378 } Kind = None; 4379 SourceRange Range; 4380 4381 explicit operator bool() { return Kind != None; } 4382 }; 4383 } 4384 4385 /// Determine whether a class is C-like, according to the rules of C++ 4386 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4387 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4388 if (RD->isInvalidDecl()) 4389 return {NonCLikeKind::Invalid, {}}; 4390 4391 // C++ [dcl.typedef]p9: [P1766R1] 4392 // An unnamed class with a typedef name for linkage purposes shall not 4393 // 4394 // -- have any base classes 4395 if (RD->getNumBases()) 4396 return {NonCLikeKind::BaseClass, 4397 SourceRange(RD->bases_begin()->getBeginLoc(), 4398 RD->bases_end()[-1].getEndLoc())}; 4399 bool Invalid = false; 4400 for (Decl *D : RD->decls()) { 4401 // Don't complain about things we already diagnosed. 4402 if (D->isInvalidDecl()) { 4403 Invalid = true; 4404 continue; 4405 } 4406 4407 // -- have any [...] default member initializers 4408 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4409 if (FD->hasInClassInitializer()) { 4410 auto *Init = FD->getInClassInitializer(); 4411 return {NonCLikeKind::DefaultMemberInit, 4412 Init ? Init->getSourceRange() : D->getSourceRange()}; 4413 } 4414 continue; 4415 } 4416 4417 // FIXME: We don't allow friend declarations. This violates the wording of 4418 // P1766, but not the intent. 4419 if (isa<FriendDecl>(D)) 4420 return {NonCLikeKind::Friend, D->getSourceRange()}; 4421 4422 // -- declare any members other than non-static data members, member 4423 // enumerations, or member classes, 4424 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4425 isa<EnumDecl>(D)) 4426 continue; 4427 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4428 if (!MemberRD) 4429 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4430 4431 // -- contain a lambda-expression, 4432 if (MemberRD->isLambda()) 4433 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4434 4435 // and all member classes shall also satisfy these requirements 4436 // (recursively). 4437 if (MemberRD->isThisDeclarationADefinition()) { 4438 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4439 return Kind; 4440 } 4441 } 4442 4443 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4444 } 4445 4446 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4447 TypedefNameDecl *NewTD) { 4448 if (TagFromDeclSpec->isInvalidDecl()) 4449 return; 4450 4451 // Do nothing if the tag already has a name for linkage purposes. 4452 if (TagFromDeclSpec->hasNameForLinkage()) 4453 return; 4454 4455 // A well-formed anonymous tag must always be a TUK_Definition. 4456 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4457 4458 // The type must match the tag exactly; no qualifiers allowed. 4459 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4460 Context.getTagDeclType(TagFromDeclSpec))) { 4461 if (getLangOpts().CPlusPlus) 4462 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4463 return; 4464 } 4465 4466 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4467 // An unnamed class with a typedef name for linkage purposes shall [be 4468 // C-like]. 4469 // 4470 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4471 // shouldn't happen, but there are constructs that the language rule doesn't 4472 // disallow for which we can't reasonably avoid computing linkage early. 4473 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4474 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4475 : NonCLikeKind(); 4476 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4477 if (NonCLike || ChangesLinkage) { 4478 if (NonCLike.Kind == NonCLikeKind::Invalid) 4479 return; 4480 4481 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4482 if (ChangesLinkage) { 4483 // If the linkage changes, we can't accept this as an extension. 4484 if (NonCLike.Kind == NonCLikeKind::None) 4485 DiagID = diag::err_typedef_changes_linkage; 4486 else 4487 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4488 } 4489 4490 SourceLocation FixitLoc = 4491 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4492 llvm::SmallString<40> TextToInsert; 4493 TextToInsert += ' '; 4494 TextToInsert += NewTD->getIdentifier()->getName(); 4495 4496 Diag(FixitLoc, DiagID) 4497 << isa<TypeAliasDecl>(NewTD) 4498 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4499 if (NonCLike.Kind != NonCLikeKind::None) { 4500 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4501 << NonCLike.Kind - 1 << NonCLike.Range; 4502 } 4503 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4504 << NewTD << isa<TypeAliasDecl>(NewTD); 4505 4506 if (ChangesLinkage) 4507 return; 4508 } 4509 4510 // Otherwise, set this as the anon-decl typedef for the tag. 4511 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4512 } 4513 4514 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4515 switch (T) { 4516 case DeclSpec::TST_class: 4517 return 0; 4518 case DeclSpec::TST_struct: 4519 return 1; 4520 case DeclSpec::TST_interface: 4521 return 2; 4522 case DeclSpec::TST_union: 4523 return 3; 4524 case DeclSpec::TST_enum: 4525 return 4; 4526 default: 4527 llvm_unreachable("unexpected type specifier"); 4528 } 4529 } 4530 4531 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4532 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4533 /// parameters to cope with template friend declarations. 4534 Decl * 4535 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4536 MultiTemplateParamsArg TemplateParams, 4537 bool IsExplicitInstantiation, 4538 RecordDecl *&AnonRecord) { 4539 Decl *TagD = nullptr; 4540 TagDecl *Tag = nullptr; 4541 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4542 DS.getTypeSpecType() == DeclSpec::TST_struct || 4543 DS.getTypeSpecType() == DeclSpec::TST_interface || 4544 DS.getTypeSpecType() == DeclSpec::TST_union || 4545 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4546 TagD = DS.getRepAsDecl(); 4547 4548 if (!TagD) // We probably had an error 4549 return nullptr; 4550 4551 // Note that the above type specs guarantee that the 4552 // type rep is a Decl, whereas in many of the others 4553 // it's a Type. 4554 if (isa<TagDecl>(TagD)) 4555 Tag = cast<TagDecl>(TagD); 4556 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4557 Tag = CTD->getTemplatedDecl(); 4558 } 4559 4560 if (Tag) { 4561 handleTagNumbering(Tag, S); 4562 Tag->setFreeStanding(); 4563 if (Tag->isInvalidDecl()) 4564 return Tag; 4565 } 4566 4567 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4568 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4569 // or incomplete types shall not be restrict-qualified." 4570 if (TypeQuals & DeclSpec::TQ_restrict) 4571 Diag(DS.getRestrictSpecLoc(), 4572 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4573 << DS.getSourceRange(); 4574 } 4575 4576 if (DS.isInlineSpecified()) 4577 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4578 << getLangOpts().CPlusPlus17; 4579 4580 if (DS.hasConstexprSpecifier()) { 4581 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4582 // and definitions of functions and variables. 4583 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4584 // the declaration of a function or function template 4585 if (Tag) 4586 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4587 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4588 << DS.getConstexprSpecifier(); 4589 else 4590 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4591 << DS.getConstexprSpecifier(); 4592 // Don't emit warnings after this error. 4593 return TagD; 4594 } 4595 4596 DiagnoseFunctionSpecifiers(DS); 4597 4598 if (DS.isFriendSpecified()) { 4599 // If we're dealing with a decl but not a TagDecl, assume that 4600 // whatever routines created it handled the friendship aspect. 4601 if (TagD && !Tag) 4602 return nullptr; 4603 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4604 } 4605 4606 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4607 bool IsExplicitSpecialization = 4608 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4609 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4610 !IsExplicitInstantiation && !IsExplicitSpecialization && 4611 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4612 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4613 // nested-name-specifier unless it is an explicit instantiation 4614 // or an explicit specialization. 4615 // 4616 // FIXME: We allow class template partial specializations here too, per the 4617 // obvious intent of DR1819. 4618 // 4619 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4620 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4621 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4622 return nullptr; 4623 } 4624 4625 // Track whether this decl-specifier declares anything. 4626 bool DeclaresAnything = true; 4627 4628 // Handle anonymous struct definitions. 4629 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4630 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4631 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4632 if (getLangOpts().CPlusPlus || 4633 Record->getDeclContext()->isRecord()) { 4634 // If CurContext is a DeclContext that can contain statements, 4635 // RecursiveASTVisitor won't visit the decls that 4636 // BuildAnonymousStructOrUnion() will put into CurContext. 4637 // Also store them here so that they can be part of the 4638 // DeclStmt that gets created in this case. 4639 // FIXME: Also return the IndirectFieldDecls created by 4640 // BuildAnonymousStructOr union, for the same reason? 4641 if (CurContext->isFunctionOrMethod()) 4642 AnonRecord = Record; 4643 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4644 Context.getPrintingPolicy()); 4645 } 4646 4647 DeclaresAnything = false; 4648 } 4649 } 4650 4651 // C11 6.7.2.1p2: 4652 // A struct-declaration that does not declare an anonymous structure or 4653 // anonymous union shall contain a struct-declarator-list. 4654 // 4655 // This rule also existed in C89 and C99; the grammar for struct-declaration 4656 // did not permit a struct-declaration without a struct-declarator-list. 4657 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4658 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4659 // Check for Microsoft C extension: anonymous struct/union member. 4660 // Handle 2 kinds of anonymous struct/union: 4661 // struct STRUCT; 4662 // union UNION; 4663 // and 4664 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4665 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4666 if ((Tag && Tag->getDeclName()) || 4667 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4668 RecordDecl *Record = nullptr; 4669 if (Tag) 4670 Record = dyn_cast<RecordDecl>(Tag); 4671 else if (const RecordType *RT = 4672 DS.getRepAsType().get()->getAsStructureType()) 4673 Record = RT->getDecl(); 4674 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4675 Record = UT->getDecl(); 4676 4677 if (Record && getLangOpts().MicrosoftExt) { 4678 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4679 << Record->isUnion() << DS.getSourceRange(); 4680 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4681 } 4682 4683 DeclaresAnything = false; 4684 } 4685 } 4686 4687 // Skip all the checks below if we have a type error. 4688 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4689 (TagD && TagD->isInvalidDecl())) 4690 return TagD; 4691 4692 if (getLangOpts().CPlusPlus && 4693 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4694 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4695 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4696 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4697 DeclaresAnything = false; 4698 4699 if (!DS.isMissingDeclaratorOk()) { 4700 // Customize diagnostic for a typedef missing a name. 4701 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4702 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4703 << DS.getSourceRange(); 4704 else 4705 DeclaresAnything = false; 4706 } 4707 4708 if (DS.isModulePrivateSpecified() && 4709 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4710 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4711 << Tag->getTagKind() 4712 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4713 4714 ActOnDocumentableDecl(TagD); 4715 4716 // C 6.7/2: 4717 // A declaration [...] shall declare at least a declarator [...], a tag, 4718 // or the members of an enumeration. 4719 // C++ [dcl.dcl]p3: 4720 // [If there are no declarators], and except for the declaration of an 4721 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4722 // names into the program, or shall redeclare a name introduced by a 4723 // previous declaration. 4724 if (!DeclaresAnything) { 4725 // In C, we allow this as a (popular) extension / bug. Don't bother 4726 // producing further diagnostics for redundant qualifiers after this. 4727 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4728 return TagD; 4729 } 4730 4731 // C++ [dcl.stc]p1: 4732 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4733 // init-declarator-list of the declaration shall not be empty. 4734 // C++ [dcl.fct.spec]p1: 4735 // If a cv-qualifier appears in a decl-specifier-seq, the 4736 // init-declarator-list of the declaration shall not be empty. 4737 // 4738 // Spurious qualifiers here appear to be valid in C. 4739 unsigned DiagID = diag::warn_standalone_specifier; 4740 if (getLangOpts().CPlusPlus) 4741 DiagID = diag::ext_standalone_specifier; 4742 4743 // Note that a linkage-specification sets a storage class, but 4744 // 'extern "C" struct foo;' is actually valid and not theoretically 4745 // useless. 4746 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4747 if (SCS == DeclSpec::SCS_mutable) 4748 // Since mutable is not a viable storage class specifier in C, there is 4749 // no reason to treat it as an extension. Instead, diagnose as an error. 4750 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4751 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4752 Diag(DS.getStorageClassSpecLoc(), DiagID) 4753 << DeclSpec::getSpecifierName(SCS); 4754 } 4755 4756 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4757 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4758 << DeclSpec::getSpecifierName(TSCS); 4759 if (DS.getTypeQualifiers()) { 4760 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4761 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4762 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4763 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4764 // Restrict is covered above. 4765 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4766 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4767 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4768 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4769 } 4770 4771 // Warn about ignored type attributes, for example: 4772 // __attribute__((aligned)) struct A; 4773 // Attributes should be placed after tag to apply to type declaration. 4774 if (!DS.getAttributes().empty()) { 4775 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4776 if (TypeSpecType == DeclSpec::TST_class || 4777 TypeSpecType == DeclSpec::TST_struct || 4778 TypeSpecType == DeclSpec::TST_interface || 4779 TypeSpecType == DeclSpec::TST_union || 4780 TypeSpecType == DeclSpec::TST_enum) { 4781 for (const ParsedAttr &AL : DS.getAttributes()) 4782 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4783 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4784 } 4785 } 4786 4787 return TagD; 4788 } 4789 4790 /// We are trying to inject an anonymous member into the given scope; 4791 /// check if there's an existing declaration that can't be overloaded. 4792 /// 4793 /// \return true if this is a forbidden redeclaration 4794 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4795 Scope *S, 4796 DeclContext *Owner, 4797 DeclarationName Name, 4798 SourceLocation NameLoc, 4799 bool IsUnion) { 4800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4801 Sema::ForVisibleRedeclaration); 4802 if (!SemaRef.LookupName(R, S)) return false; 4803 4804 // Pick a representative declaration. 4805 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4806 assert(PrevDecl && "Expected a non-null Decl"); 4807 4808 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4809 return false; 4810 4811 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4812 << IsUnion << Name; 4813 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4814 4815 return true; 4816 } 4817 4818 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4819 /// anonymous struct or union AnonRecord into the owning context Owner 4820 /// and scope S. This routine will be invoked just after we realize 4821 /// that an unnamed union or struct is actually an anonymous union or 4822 /// struct, e.g., 4823 /// 4824 /// @code 4825 /// union { 4826 /// int i; 4827 /// float f; 4828 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4829 /// // f into the surrounding scope.x 4830 /// @endcode 4831 /// 4832 /// This routine is recursive, injecting the names of nested anonymous 4833 /// structs/unions into the owning context and scope as well. 4834 static bool 4835 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4836 RecordDecl *AnonRecord, AccessSpecifier AS, 4837 SmallVectorImpl<NamedDecl *> &Chaining) { 4838 bool Invalid = false; 4839 4840 // Look every FieldDecl and IndirectFieldDecl with a name. 4841 for (auto *D : AnonRecord->decls()) { 4842 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4843 cast<NamedDecl>(D)->getDeclName()) { 4844 ValueDecl *VD = cast<ValueDecl>(D); 4845 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4846 VD->getLocation(), 4847 AnonRecord->isUnion())) { 4848 // C++ [class.union]p2: 4849 // The names of the members of an anonymous union shall be 4850 // distinct from the names of any other entity in the 4851 // scope in which the anonymous union is declared. 4852 Invalid = true; 4853 } else { 4854 // C++ [class.union]p2: 4855 // For the purpose of name lookup, after the anonymous union 4856 // definition, the members of the anonymous union are 4857 // considered to have been defined in the scope in which the 4858 // anonymous union is declared. 4859 unsigned OldChainingSize = Chaining.size(); 4860 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4861 Chaining.append(IF->chain_begin(), IF->chain_end()); 4862 else 4863 Chaining.push_back(VD); 4864 4865 assert(Chaining.size() >= 2); 4866 NamedDecl **NamedChain = 4867 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4868 for (unsigned i = 0; i < Chaining.size(); i++) 4869 NamedChain[i] = Chaining[i]; 4870 4871 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4872 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4873 VD->getType(), {NamedChain, Chaining.size()}); 4874 4875 for (const auto *Attr : VD->attrs()) 4876 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4877 4878 IndirectField->setAccess(AS); 4879 IndirectField->setImplicit(); 4880 SemaRef.PushOnScopeChains(IndirectField, S); 4881 4882 // That includes picking up the appropriate access specifier. 4883 if (AS != AS_none) IndirectField->setAccess(AS); 4884 4885 Chaining.resize(OldChainingSize); 4886 } 4887 } 4888 } 4889 4890 return Invalid; 4891 } 4892 4893 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4894 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4895 /// illegal input values are mapped to SC_None. 4896 static StorageClass 4897 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4898 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4899 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4900 "Parser allowed 'typedef' as storage class VarDecl."); 4901 switch (StorageClassSpec) { 4902 case DeclSpec::SCS_unspecified: return SC_None; 4903 case DeclSpec::SCS_extern: 4904 if (DS.isExternInLinkageSpec()) 4905 return SC_None; 4906 return SC_Extern; 4907 case DeclSpec::SCS_static: return SC_Static; 4908 case DeclSpec::SCS_auto: return SC_Auto; 4909 case DeclSpec::SCS_register: return SC_Register; 4910 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4911 // Illegal SCSs map to None: error reporting is up to the caller. 4912 case DeclSpec::SCS_mutable: // Fall through. 4913 case DeclSpec::SCS_typedef: return SC_None; 4914 } 4915 llvm_unreachable("unknown storage class specifier"); 4916 } 4917 4918 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4919 assert(Record->hasInClassInitializer()); 4920 4921 for (const auto *I : Record->decls()) { 4922 const auto *FD = dyn_cast<FieldDecl>(I); 4923 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4924 FD = IFD->getAnonField(); 4925 if (FD && FD->hasInClassInitializer()) 4926 return FD->getLocation(); 4927 } 4928 4929 llvm_unreachable("couldn't find in-class initializer"); 4930 } 4931 4932 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4933 SourceLocation DefaultInitLoc) { 4934 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4935 return; 4936 4937 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4938 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4939 } 4940 4941 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4942 CXXRecordDecl *AnonUnion) { 4943 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4944 return; 4945 4946 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4947 } 4948 4949 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4950 /// anonymous structure or union. Anonymous unions are a C++ feature 4951 /// (C++ [class.union]) and a C11 feature; anonymous structures 4952 /// are a C11 feature and GNU C++ extension. 4953 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4954 AccessSpecifier AS, 4955 RecordDecl *Record, 4956 const PrintingPolicy &Policy) { 4957 DeclContext *Owner = Record->getDeclContext(); 4958 4959 // Diagnose whether this anonymous struct/union is an extension. 4960 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4961 Diag(Record->getLocation(), diag::ext_anonymous_union); 4962 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4963 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4964 else if (!Record->isUnion() && !getLangOpts().C11) 4965 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4966 4967 // C and C++ require different kinds of checks for anonymous 4968 // structs/unions. 4969 bool Invalid = false; 4970 if (getLangOpts().CPlusPlus) { 4971 const char *PrevSpec = nullptr; 4972 if (Record->isUnion()) { 4973 // C++ [class.union]p6: 4974 // C++17 [class.union.anon]p2: 4975 // Anonymous unions declared in a named namespace or in the 4976 // global namespace shall be declared static. 4977 unsigned DiagID; 4978 DeclContext *OwnerScope = Owner->getRedeclContext(); 4979 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4980 (OwnerScope->isTranslationUnit() || 4981 (OwnerScope->isNamespace() && 4982 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4983 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4984 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4985 4986 // Recover by adding 'static'. 4987 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4988 PrevSpec, DiagID, Policy); 4989 } 4990 // C++ [class.union]p6: 4991 // A storage class is not allowed in a declaration of an 4992 // anonymous union in a class scope. 4993 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4994 isa<RecordDecl>(Owner)) { 4995 Diag(DS.getStorageClassSpecLoc(), 4996 diag::err_anonymous_union_with_storage_spec) 4997 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4998 4999 // Recover by removing the storage specifier. 5000 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5001 SourceLocation(), 5002 PrevSpec, DiagID, Context.getPrintingPolicy()); 5003 } 5004 } 5005 5006 // Ignore const/volatile/restrict qualifiers. 5007 if (DS.getTypeQualifiers()) { 5008 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5009 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5010 << Record->isUnion() << "const" 5011 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5012 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5013 Diag(DS.getVolatileSpecLoc(), 5014 diag::ext_anonymous_struct_union_qualified) 5015 << Record->isUnion() << "volatile" 5016 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5017 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5018 Diag(DS.getRestrictSpecLoc(), 5019 diag::ext_anonymous_struct_union_qualified) 5020 << Record->isUnion() << "restrict" 5021 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5022 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5023 Diag(DS.getAtomicSpecLoc(), 5024 diag::ext_anonymous_struct_union_qualified) 5025 << Record->isUnion() << "_Atomic" 5026 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5027 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5028 Diag(DS.getUnalignedSpecLoc(), 5029 diag::ext_anonymous_struct_union_qualified) 5030 << Record->isUnion() << "__unaligned" 5031 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5032 5033 DS.ClearTypeQualifiers(); 5034 } 5035 5036 // C++ [class.union]p2: 5037 // The member-specification of an anonymous union shall only 5038 // define non-static data members. [Note: nested types and 5039 // functions cannot be declared within an anonymous union. ] 5040 for (auto *Mem : Record->decls()) { 5041 // Ignore invalid declarations; we already diagnosed them. 5042 if (Mem->isInvalidDecl()) 5043 continue; 5044 5045 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5046 // C++ [class.union]p3: 5047 // An anonymous union shall not have private or protected 5048 // members (clause 11). 5049 assert(FD->getAccess() != AS_none); 5050 if (FD->getAccess() != AS_public) { 5051 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5052 << Record->isUnion() << (FD->getAccess() == AS_protected); 5053 Invalid = true; 5054 } 5055 5056 // C++ [class.union]p1 5057 // An object of a class with a non-trivial constructor, a non-trivial 5058 // copy constructor, a non-trivial destructor, or a non-trivial copy 5059 // assignment operator cannot be a member of a union, nor can an 5060 // array of such objects. 5061 if (CheckNontrivialField(FD)) 5062 Invalid = true; 5063 } else if (Mem->isImplicit()) { 5064 // Any implicit members are fine. 5065 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5066 // This is a type that showed up in an 5067 // elaborated-type-specifier inside the anonymous struct or 5068 // union, but which actually declares a type outside of the 5069 // anonymous struct or union. It's okay. 5070 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5071 if (!MemRecord->isAnonymousStructOrUnion() && 5072 MemRecord->getDeclName()) { 5073 // Visual C++ allows type definition in anonymous struct or union. 5074 if (getLangOpts().MicrosoftExt) 5075 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5076 << Record->isUnion(); 5077 else { 5078 // This is a nested type declaration. 5079 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5080 << Record->isUnion(); 5081 Invalid = true; 5082 } 5083 } else { 5084 // This is an anonymous type definition within another anonymous type. 5085 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5086 // not part of standard C++. 5087 Diag(MemRecord->getLocation(), 5088 diag::ext_anonymous_record_with_anonymous_type) 5089 << Record->isUnion(); 5090 } 5091 } else if (isa<AccessSpecDecl>(Mem)) { 5092 // Any access specifier is fine. 5093 } else if (isa<StaticAssertDecl>(Mem)) { 5094 // In C++1z, static_assert declarations are also fine. 5095 } else { 5096 // We have something that isn't a non-static data 5097 // member. Complain about it. 5098 unsigned DK = diag::err_anonymous_record_bad_member; 5099 if (isa<TypeDecl>(Mem)) 5100 DK = diag::err_anonymous_record_with_type; 5101 else if (isa<FunctionDecl>(Mem)) 5102 DK = diag::err_anonymous_record_with_function; 5103 else if (isa<VarDecl>(Mem)) 5104 DK = diag::err_anonymous_record_with_static; 5105 5106 // Visual C++ allows type definition in anonymous struct or union. 5107 if (getLangOpts().MicrosoftExt && 5108 DK == diag::err_anonymous_record_with_type) 5109 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5110 << Record->isUnion(); 5111 else { 5112 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5113 Invalid = true; 5114 } 5115 } 5116 } 5117 5118 // C++11 [class.union]p8 (DR1460): 5119 // At most one variant member of a union may have a 5120 // brace-or-equal-initializer. 5121 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5122 Owner->isRecord()) 5123 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5124 cast<CXXRecordDecl>(Record)); 5125 } 5126 5127 if (!Record->isUnion() && !Owner->isRecord()) { 5128 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5129 << getLangOpts().CPlusPlus; 5130 Invalid = true; 5131 } 5132 5133 // C++ [dcl.dcl]p3: 5134 // [If there are no declarators], and except for the declaration of an 5135 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5136 // names into the program 5137 // C++ [class.mem]p2: 5138 // each such member-declaration shall either declare at least one member 5139 // name of the class or declare at least one unnamed bit-field 5140 // 5141 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5142 if (getLangOpts().CPlusPlus && Record->field_empty()) 5143 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5144 5145 // Mock up a declarator. 5146 Declarator Dc(DS, DeclaratorContext::MemberContext); 5147 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5148 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5149 5150 // Create a declaration for this anonymous struct/union. 5151 NamedDecl *Anon = nullptr; 5152 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5153 Anon = FieldDecl::Create( 5154 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5155 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5156 /*BitWidth=*/nullptr, /*Mutable=*/false, 5157 /*InitStyle=*/ICIS_NoInit); 5158 Anon->setAccess(AS); 5159 ProcessDeclAttributes(S, Anon, Dc); 5160 5161 if (getLangOpts().CPlusPlus) 5162 FieldCollector->Add(cast<FieldDecl>(Anon)); 5163 } else { 5164 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5165 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5166 if (SCSpec == DeclSpec::SCS_mutable) { 5167 // mutable can only appear on non-static class members, so it's always 5168 // an error here 5169 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5170 Invalid = true; 5171 SC = SC_None; 5172 } 5173 5174 assert(DS.getAttributes().empty() && "No attribute expected"); 5175 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5176 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5177 Context.getTypeDeclType(Record), TInfo, SC); 5178 5179 // Default-initialize the implicit variable. This initialization will be 5180 // trivial in almost all cases, except if a union member has an in-class 5181 // initializer: 5182 // union { int n = 0; }; 5183 ActOnUninitializedDecl(Anon); 5184 } 5185 Anon->setImplicit(); 5186 5187 // Mark this as an anonymous struct/union type. 5188 Record->setAnonymousStructOrUnion(true); 5189 5190 // Add the anonymous struct/union object to the current 5191 // context. We'll be referencing this object when we refer to one of 5192 // its members. 5193 Owner->addDecl(Anon); 5194 5195 // Inject the members of the anonymous struct/union into the owning 5196 // context and into the identifier resolver chain for name lookup 5197 // purposes. 5198 SmallVector<NamedDecl*, 2> Chain; 5199 Chain.push_back(Anon); 5200 5201 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5202 Invalid = true; 5203 5204 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5205 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5206 MangleNumberingContext *MCtx; 5207 Decl *ManglingContextDecl; 5208 std::tie(MCtx, ManglingContextDecl) = 5209 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5210 if (MCtx) { 5211 Context.setManglingNumber( 5212 NewVD, MCtx->getManglingNumber( 5213 NewVD, getMSManglingNumber(getLangOpts(), S))); 5214 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5215 } 5216 } 5217 } 5218 5219 if (Invalid) 5220 Anon->setInvalidDecl(); 5221 5222 return Anon; 5223 } 5224 5225 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5226 /// Microsoft C anonymous structure. 5227 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5228 /// Example: 5229 /// 5230 /// struct A { int a; }; 5231 /// struct B { struct A; int b; }; 5232 /// 5233 /// void foo() { 5234 /// B var; 5235 /// var.a = 3; 5236 /// } 5237 /// 5238 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5239 RecordDecl *Record) { 5240 assert(Record && "expected a record!"); 5241 5242 // Mock up a declarator. 5243 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5244 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5245 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5246 5247 auto *ParentDecl = cast<RecordDecl>(CurContext); 5248 QualType RecTy = Context.getTypeDeclType(Record); 5249 5250 // Create a declaration for this anonymous struct. 5251 NamedDecl *Anon = 5252 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5253 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5254 /*BitWidth=*/nullptr, /*Mutable=*/false, 5255 /*InitStyle=*/ICIS_NoInit); 5256 Anon->setImplicit(); 5257 5258 // Add the anonymous struct object to the current context. 5259 CurContext->addDecl(Anon); 5260 5261 // Inject the members of the anonymous struct into the current 5262 // context and into the identifier resolver chain for name lookup 5263 // purposes. 5264 SmallVector<NamedDecl*, 2> Chain; 5265 Chain.push_back(Anon); 5266 5267 RecordDecl *RecordDef = Record->getDefinition(); 5268 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5269 diag::err_field_incomplete_or_sizeless) || 5270 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5271 AS_none, Chain)) { 5272 Anon->setInvalidDecl(); 5273 ParentDecl->setInvalidDecl(); 5274 } 5275 5276 return Anon; 5277 } 5278 5279 /// GetNameForDeclarator - Determine the full declaration name for the 5280 /// given Declarator. 5281 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5282 return GetNameFromUnqualifiedId(D.getName()); 5283 } 5284 5285 /// Retrieves the declaration name from a parsed unqualified-id. 5286 DeclarationNameInfo 5287 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5288 DeclarationNameInfo NameInfo; 5289 NameInfo.setLoc(Name.StartLocation); 5290 5291 switch (Name.getKind()) { 5292 5293 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5294 case UnqualifiedIdKind::IK_Identifier: 5295 NameInfo.setName(Name.Identifier); 5296 return NameInfo; 5297 5298 case UnqualifiedIdKind::IK_DeductionGuideName: { 5299 // C++ [temp.deduct.guide]p3: 5300 // The simple-template-id shall name a class template specialization. 5301 // The template-name shall be the same identifier as the template-name 5302 // of the simple-template-id. 5303 // These together intend to imply that the template-name shall name a 5304 // class template. 5305 // FIXME: template<typename T> struct X {}; 5306 // template<typename T> using Y = X<T>; 5307 // Y(int) -> Y<int>; 5308 // satisfies these rules but does not name a class template. 5309 TemplateName TN = Name.TemplateName.get().get(); 5310 auto *Template = TN.getAsTemplateDecl(); 5311 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5312 Diag(Name.StartLocation, 5313 diag::err_deduction_guide_name_not_class_template) 5314 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5315 if (Template) 5316 Diag(Template->getLocation(), diag::note_template_decl_here); 5317 return DeclarationNameInfo(); 5318 } 5319 5320 NameInfo.setName( 5321 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5322 return NameInfo; 5323 } 5324 5325 case UnqualifiedIdKind::IK_OperatorFunctionId: 5326 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5327 Name.OperatorFunctionId.Operator)); 5328 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5329 = Name.OperatorFunctionId.SymbolLocations[0]; 5330 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5331 = Name.EndLocation.getRawEncoding(); 5332 return NameInfo; 5333 5334 case UnqualifiedIdKind::IK_LiteralOperatorId: 5335 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5336 Name.Identifier)); 5337 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5338 return NameInfo; 5339 5340 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5341 TypeSourceInfo *TInfo; 5342 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5343 if (Ty.isNull()) 5344 return DeclarationNameInfo(); 5345 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5346 Context.getCanonicalType(Ty))); 5347 NameInfo.setNamedTypeInfo(TInfo); 5348 return NameInfo; 5349 } 5350 5351 case UnqualifiedIdKind::IK_ConstructorName: { 5352 TypeSourceInfo *TInfo; 5353 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5354 if (Ty.isNull()) 5355 return DeclarationNameInfo(); 5356 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5357 Context.getCanonicalType(Ty))); 5358 NameInfo.setNamedTypeInfo(TInfo); 5359 return NameInfo; 5360 } 5361 5362 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5363 // In well-formed code, we can only have a constructor 5364 // template-id that refers to the current context, so go there 5365 // to find the actual type being constructed. 5366 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5367 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5368 return DeclarationNameInfo(); 5369 5370 // Determine the type of the class being constructed. 5371 QualType CurClassType = Context.getTypeDeclType(CurClass); 5372 5373 // FIXME: Check two things: that the template-id names the same type as 5374 // CurClassType, and that the template-id does not occur when the name 5375 // was qualified. 5376 5377 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5378 Context.getCanonicalType(CurClassType))); 5379 // FIXME: should we retrieve TypeSourceInfo? 5380 NameInfo.setNamedTypeInfo(nullptr); 5381 return NameInfo; 5382 } 5383 5384 case UnqualifiedIdKind::IK_DestructorName: { 5385 TypeSourceInfo *TInfo; 5386 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5387 if (Ty.isNull()) 5388 return DeclarationNameInfo(); 5389 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5390 Context.getCanonicalType(Ty))); 5391 NameInfo.setNamedTypeInfo(TInfo); 5392 return NameInfo; 5393 } 5394 5395 case UnqualifiedIdKind::IK_TemplateId: { 5396 TemplateName TName = Name.TemplateId->Template.get(); 5397 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5398 return Context.getNameForTemplate(TName, TNameLoc); 5399 } 5400 5401 } // switch (Name.getKind()) 5402 5403 llvm_unreachable("Unknown name kind"); 5404 } 5405 5406 static QualType getCoreType(QualType Ty) { 5407 do { 5408 if (Ty->isPointerType() || Ty->isReferenceType()) 5409 Ty = Ty->getPointeeType(); 5410 else if (Ty->isArrayType()) 5411 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5412 else 5413 return Ty.withoutLocalFastQualifiers(); 5414 } while (true); 5415 } 5416 5417 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5418 /// and Definition have "nearly" matching parameters. This heuristic is 5419 /// used to improve diagnostics in the case where an out-of-line function 5420 /// definition doesn't match any declaration within the class or namespace. 5421 /// Also sets Params to the list of indices to the parameters that differ 5422 /// between the declaration and the definition. If hasSimilarParameters 5423 /// returns true and Params is empty, then all of the parameters match. 5424 static bool hasSimilarParameters(ASTContext &Context, 5425 FunctionDecl *Declaration, 5426 FunctionDecl *Definition, 5427 SmallVectorImpl<unsigned> &Params) { 5428 Params.clear(); 5429 if (Declaration->param_size() != Definition->param_size()) 5430 return false; 5431 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5432 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5433 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5434 5435 // The parameter types are identical 5436 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5437 continue; 5438 5439 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5440 QualType DefParamBaseTy = getCoreType(DefParamTy); 5441 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5442 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5443 5444 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5445 (DeclTyName && DeclTyName == DefTyName)) 5446 Params.push_back(Idx); 5447 else // The two parameters aren't even close 5448 return false; 5449 } 5450 5451 return true; 5452 } 5453 5454 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5455 /// declarator needs to be rebuilt in the current instantiation. 5456 /// Any bits of declarator which appear before the name are valid for 5457 /// consideration here. That's specifically the type in the decl spec 5458 /// and the base type in any member-pointer chunks. 5459 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5460 DeclarationName Name) { 5461 // The types we specifically need to rebuild are: 5462 // - typenames, typeofs, and decltypes 5463 // - types which will become injected class names 5464 // Of course, we also need to rebuild any type referencing such a 5465 // type. It's safest to just say "dependent", but we call out a 5466 // few cases here. 5467 5468 DeclSpec &DS = D.getMutableDeclSpec(); 5469 switch (DS.getTypeSpecType()) { 5470 case DeclSpec::TST_typename: 5471 case DeclSpec::TST_typeofType: 5472 case DeclSpec::TST_underlyingType: 5473 case DeclSpec::TST_atomic: { 5474 // Grab the type from the parser. 5475 TypeSourceInfo *TSI = nullptr; 5476 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5477 if (T.isNull() || !T->isDependentType()) break; 5478 5479 // Make sure there's a type source info. This isn't really much 5480 // of a waste; most dependent types should have type source info 5481 // attached already. 5482 if (!TSI) 5483 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5484 5485 // Rebuild the type in the current instantiation. 5486 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5487 if (!TSI) return true; 5488 5489 // Store the new type back in the decl spec. 5490 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5491 DS.UpdateTypeRep(LocType); 5492 break; 5493 } 5494 5495 case DeclSpec::TST_decltype: 5496 case DeclSpec::TST_typeofExpr: { 5497 Expr *E = DS.getRepAsExpr(); 5498 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5499 if (Result.isInvalid()) return true; 5500 DS.UpdateExprRep(Result.get()); 5501 break; 5502 } 5503 5504 default: 5505 // Nothing to do for these decl specs. 5506 break; 5507 } 5508 5509 // It doesn't matter what order we do this in. 5510 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5511 DeclaratorChunk &Chunk = D.getTypeObject(I); 5512 5513 // The only type information in the declarator which can come 5514 // before the declaration name is the base type of a member 5515 // pointer. 5516 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5517 continue; 5518 5519 // Rebuild the scope specifier in-place. 5520 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5521 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5522 return true; 5523 } 5524 5525 return false; 5526 } 5527 5528 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5529 D.setFunctionDefinitionKind(FDK_Declaration); 5530 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5531 5532 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5533 Dcl && Dcl->getDeclContext()->isFileContext()) 5534 Dcl->setTopLevelDeclInObjCContainer(); 5535 5536 if (getLangOpts().OpenCL) 5537 setCurrentOpenCLExtensionForDecl(Dcl); 5538 5539 return Dcl; 5540 } 5541 5542 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5543 /// If T is the name of a class, then each of the following shall have a 5544 /// name different from T: 5545 /// - every static data member of class T; 5546 /// - every member function of class T 5547 /// - every member of class T that is itself a type; 5548 /// \returns true if the declaration name violates these rules. 5549 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5550 DeclarationNameInfo NameInfo) { 5551 DeclarationName Name = NameInfo.getName(); 5552 5553 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5554 while (Record && Record->isAnonymousStructOrUnion()) 5555 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5556 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5557 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5558 return true; 5559 } 5560 5561 return false; 5562 } 5563 5564 /// Diagnose a declaration whose declarator-id has the given 5565 /// nested-name-specifier. 5566 /// 5567 /// \param SS The nested-name-specifier of the declarator-id. 5568 /// 5569 /// \param DC The declaration context to which the nested-name-specifier 5570 /// resolves. 5571 /// 5572 /// \param Name The name of the entity being declared. 5573 /// 5574 /// \param Loc The location of the name of the entity being declared. 5575 /// 5576 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5577 /// we're declaring an explicit / partial specialization / instantiation. 5578 /// 5579 /// \returns true if we cannot safely recover from this error, false otherwise. 5580 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5581 DeclarationName Name, 5582 SourceLocation Loc, bool IsTemplateId) { 5583 DeclContext *Cur = CurContext; 5584 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5585 Cur = Cur->getParent(); 5586 5587 // If the user provided a superfluous scope specifier that refers back to the 5588 // class in which the entity is already declared, diagnose and ignore it. 5589 // 5590 // class X { 5591 // void X::f(); 5592 // }; 5593 // 5594 // Note, it was once ill-formed to give redundant qualification in all 5595 // contexts, but that rule was removed by DR482. 5596 if (Cur->Equals(DC)) { 5597 if (Cur->isRecord()) { 5598 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5599 : diag::err_member_extra_qualification) 5600 << Name << FixItHint::CreateRemoval(SS.getRange()); 5601 SS.clear(); 5602 } else { 5603 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5604 } 5605 return false; 5606 } 5607 5608 // Check whether the qualifying scope encloses the scope of the original 5609 // declaration. For a template-id, we perform the checks in 5610 // CheckTemplateSpecializationScope. 5611 if (!Cur->Encloses(DC) && !IsTemplateId) { 5612 if (Cur->isRecord()) 5613 Diag(Loc, diag::err_member_qualification) 5614 << Name << SS.getRange(); 5615 else if (isa<TranslationUnitDecl>(DC)) 5616 Diag(Loc, diag::err_invalid_declarator_global_scope) 5617 << Name << SS.getRange(); 5618 else if (isa<FunctionDecl>(Cur)) 5619 Diag(Loc, diag::err_invalid_declarator_in_function) 5620 << Name << SS.getRange(); 5621 else if (isa<BlockDecl>(Cur)) 5622 Diag(Loc, diag::err_invalid_declarator_in_block) 5623 << Name << SS.getRange(); 5624 else 5625 Diag(Loc, diag::err_invalid_declarator_scope) 5626 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5627 5628 return true; 5629 } 5630 5631 if (Cur->isRecord()) { 5632 // Cannot qualify members within a class. 5633 Diag(Loc, diag::err_member_qualification) 5634 << Name << SS.getRange(); 5635 SS.clear(); 5636 5637 // C++ constructors and destructors with incorrect scopes can break 5638 // our AST invariants by having the wrong underlying types. If 5639 // that's the case, then drop this declaration entirely. 5640 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5641 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5642 !Context.hasSameType(Name.getCXXNameType(), 5643 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5644 return true; 5645 5646 return false; 5647 } 5648 5649 // C++11 [dcl.meaning]p1: 5650 // [...] "The nested-name-specifier of the qualified declarator-id shall 5651 // not begin with a decltype-specifer" 5652 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5653 while (SpecLoc.getPrefix()) 5654 SpecLoc = SpecLoc.getPrefix(); 5655 if (dyn_cast_or_null<DecltypeType>( 5656 SpecLoc.getNestedNameSpecifier()->getAsType())) 5657 Diag(Loc, diag::err_decltype_in_declarator) 5658 << SpecLoc.getTypeLoc().getSourceRange(); 5659 5660 return false; 5661 } 5662 5663 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5664 MultiTemplateParamsArg TemplateParamLists) { 5665 // TODO: consider using NameInfo for diagnostic. 5666 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5667 DeclarationName Name = NameInfo.getName(); 5668 5669 // All of these full declarators require an identifier. If it doesn't have 5670 // one, the ParsedFreeStandingDeclSpec action should be used. 5671 if (D.isDecompositionDeclarator()) { 5672 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5673 } else if (!Name) { 5674 if (!D.isInvalidType()) // Reject this if we think it is valid. 5675 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5676 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5677 return nullptr; 5678 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5679 return nullptr; 5680 5681 // The scope passed in may not be a decl scope. Zip up the scope tree until 5682 // we find one that is. 5683 while ((S->getFlags() & Scope::DeclScope) == 0 || 5684 (S->getFlags() & Scope::TemplateParamScope) != 0) 5685 S = S->getParent(); 5686 5687 DeclContext *DC = CurContext; 5688 if (D.getCXXScopeSpec().isInvalid()) 5689 D.setInvalidType(); 5690 else if (D.getCXXScopeSpec().isSet()) { 5691 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5692 UPPC_DeclarationQualifier)) 5693 return nullptr; 5694 5695 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5696 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5697 if (!DC || isa<EnumDecl>(DC)) { 5698 // If we could not compute the declaration context, it's because the 5699 // declaration context is dependent but does not refer to a class, 5700 // class template, or class template partial specialization. Complain 5701 // and return early, to avoid the coming semantic disaster. 5702 Diag(D.getIdentifierLoc(), 5703 diag::err_template_qualified_declarator_no_match) 5704 << D.getCXXScopeSpec().getScopeRep() 5705 << D.getCXXScopeSpec().getRange(); 5706 return nullptr; 5707 } 5708 bool IsDependentContext = DC->isDependentContext(); 5709 5710 if (!IsDependentContext && 5711 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5712 return nullptr; 5713 5714 // If a class is incomplete, do not parse entities inside it. 5715 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5716 Diag(D.getIdentifierLoc(), 5717 diag::err_member_def_undefined_record) 5718 << Name << DC << D.getCXXScopeSpec().getRange(); 5719 return nullptr; 5720 } 5721 if (!D.getDeclSpec().isFriendSpecified()) { 5722 if (diagnoseQualifiedDeclaration( 5723 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5724 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5725 if (DC->isRecord()) 5726 return nullptr; 5727 5728 D.setInvalidType(); 5729 } 5730 } 5731 5732 // Check whether we need to rebuild the type of the given 5733 // declaration in the current instantiation. 5734 if (EnteringContext && IsDependentContext && 5735 TemplateParamLists.size() != 0) { 5736 ContextRAII SavedContext(*this, DC); 5737 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5738 D.setInvalidType(); 5739 } 5740 } 5741 5742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5743 QualType R = TInfo->getType(); 5744 5745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5746 UPPC_DeclarationType)) 5747 D.setInvalidType(); 5748 5749 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5750 forRedeclarationInCurContext()); 5751 5752 // See if this is a redefinition of a variable in the same scope. 5753 if (!D.getCXXScopeSpec().isSet()) { 5754 bool IsLinkageLookup = false; 5755 bool CreateBuiltins = false; 5756 5757 // If the declaration we're planning to build will be a function 5758 // or object with linkage, then look for another declaration with 5759 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5760 // 5761 // If the declaration we're planning to build will be declared with 5762 // external linkage in the translation unit, create any builtin with 5763 // the same name. 5764 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5765 /* Do nothing*/; 5766 else if (CurContext->isFunctionOrMethod() && 5767 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5768 R->isFunctionType())) { 5769 IsLinkageLookup = true; 5770 CreateBuiltins = 5771 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5772 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5773 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5774 CreateBuiltins = true; 5775 5776 if (IsLinkageLookup) { 5777 Previous.clear(LookupRedeclarationWithLinkage); 5778 Previous.setRedeclarationKind(ForExternalRedeclaration); 5779 } 5780 5781 LookupName(Previous, S, CreateBuiltins); 5782 } else { // Something like "int foo::x;" 5783 LookupQualifiedName(Previous, DC); 5784 5785 // C++ [dcl.meaning]p1: 5786 // When the declarator-id is qualified, the declaration shall refer to a 5787 // previously declared member of the class or namespace to which the 5788 // qualifier refers (or, in the case of a namespace, of an element of the 5789 // inline namespace set of that namespace (7.3.1)) or to a specialization 5790 // thereof; [...] 5791 // 5792 // Note that we already checked the context above, and that we do not have 5793 // enough information to make sure that Previous contains the declaration 5794 // we want to match. For example, given: 5795 // 5796 // class X { 5797 // void f(); 5798 // void f(float); 5799 // }; 5800 // 5801 // void X::f(int) { } // ill-formed 5802 // 5803 // In this case, Previous will point to the overload set 5804 // containing the two f's declared in X, but neither of them 5805 // matches. 5806 5807 // C++ [dcl.meaning]p1: 5808 // [...] the member shall not merely have been introduced by a 5809 // using-declaration in the scope of the class or namespace nominated by 5810 // the nested-name-specifier of the declarator-id. 5811 RemoveUsingDecls(Previous); 5812 } 5813 5814 if (Previous.isSingleResult() && 5815 Previous.getFoundDecl()->isTemplateParameter()) { 5816 // Maybe we will complain about the shadowed template parameter. 5817 if (!D.isInvalidType()) 5818 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5819 Previous.getFoundDecl()); 5820 5821 // Just pretend that we didn't see the previous declaration. 5822 Previous.clear(); 5823 } 5824 5825 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5826 // Forget that the previous declaration is the injected-class-name. 5827 Previous.clear(); 5828 5829 // In C++, the previous declaration we find might be a tag type 5830 // (class or enum). In this case, the new declaration will hide the 5831 // tag type. Note that this applies to functions, function templates, and 5832 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5833 if (Previous.isSingleTagDecl() && 5834 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5835 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5836 Previous.clear(); 5837 5838 // Check that there are no default arguments other than in the parameters 5839 // of a function declaration (C++ only). 5840 if (getLangOpts().CPlusPlus) 5841 CheckExtraCXXDefaultArguments(D); 5842 5843 NamedDecl *New; 5844 5845 bool AddToScope = true; 5846 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5847 if (TemplateParamLists.size()) { 5848 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5849 return nullptr; 5850 } 5851 5852 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5853 } else if (R->isFunctionType()) { 5854 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5855 TemplateParamLists, 5856 AddToScope); 5857 } else { 5858 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5859 AddToScope); 5860 } 5861 5862 if (!New) 5863 return nullptr; 5864 5865 // If this has an identifier and is not a function template specialization, 5866 // add it to the scope stack. 5867 if (New->getDeclName() && AddToScope) 5868 PushOnScopeChains(New, S); 5869 5870 if (isInOpenMPDeclareTargetContext()) 5871 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5872 5873 return New; 5874 } 5875 5876 /// Helper method to turn variable array types into constant array 5877 /// types in certain situations which would otherwise be errors (for 5878 /// GCC compatibility). 5879 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5880 ASTContext &Context, 5881 bool &SizeIsNegative, 5882 llvm::APSInt &Oversized) { 5883 // This method tries to turn a variable array into a constant 5884 // array even when the size isn't an ICE. This is necessary 5885 // for compatibility with code that depends on gcc's buggy 5886 // constant expression folding, like struct {char x[(int)(char*)2];} 5887 SizeIsNegative = false; 5888 Oversized = 0; 5889 5890 if (T->isDependentType()) 5891 return QualType(); 5892 5893 QualifierCollector Qs; 5894 const Type *Ty = Qs.strip(T); 5895 5896 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5897 QualType Pointee = PTy->getPointeeType(); 5898 QualType FixedType = 5899 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5900 Oversized); 5901 if (FixedType.isNull()) return FixedType; 5902 FixedType = Context.getPointerType(FixedType); 5903 return Qs.apply(Context, FixedType); 5904 } 5905 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5906 QualType Inner = PTy->getInnerType(); 5907 QualType FixedType = 5908 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5909 Oversized); 5910 if (FixedType.isNull()) return FixedType; 5911 FixedType = Context.getParenType(FixedType); 5912 return Qs.apply(Context, FixedType); 5913 } 5914 5915 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5916 if (!VLATy) 5917 return QualType(); 5918 // FIXME: We should probably handle this case 5919 if (VLATy->getElementType()->isVariablyModifiedType()) 5920 return QualType(); 5921 5922 Expr::EvalResult Result; 5923 if (!VLATy->getSizeExpr() || 5924 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5925 return QualType(); 5926 5927 llvm::APSInt Res = Result.Val.getInt(); 5928 5929 // Check whether the array size is negative. 5930 if (Res.isSigned() && Res.isNegative()) { 5931 SizeIsNegative = true; 5932 return QualType(); 5933 } 5934 5935 // Check whether the array is too large to be addressed. 5936 unsigned ActiveSizeBits 5937 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5938 Res); 5939 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5940 Oversized = Res; 5941 return QualType(); 5942 } 5943 5944 return Context.getConstantArrayType( 5945 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5946 } 5947 5948 static void 5949 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5950 SrcTL = SrcTL.getUnqualifiedLoc(); 5951 DstTL = DstTL.getUnqualifiedLoc(); 5952 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5953 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5954 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5955 DstPTL.getPointeeLoc()); 5956 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5957 return; 5958 } 5959 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5960 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5961 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5962 DstPTL.getInnerLoc()); 5963 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5964 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5965 return; 5966 } 5967 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5968 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5969 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5970 TypeLoc DstElemTL = DstATL.getElementLoc(); 5971 DstElemTL.initializeFullCopy(SrcElemTL); 5972 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5973 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5974 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5975 } 5976 5977 /// Helper method to turn variable array types into constant array 5978 /// types in certain situations which would otherwise be errors (for 5979 /// GCC compatibility). 5980 static TypeSourceInfo* 5981 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5982 ASTContext &Context, 5983 bool &SizeIsNegative, 5984 llvm::APSInt &Oversized) { 5985 QualType FixedTy 5986 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5987 SizeIsNegative, Oversized); 5988 if (FixedTy.isNull()) 5989 return nullptr; 5990 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5991 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5992 FixedTInfo->getTypeLoc()); 5993 return FixedTInfo; 5994 } 5995 5996 /// Register the given locally-scoped extern "C" declaration so 5997 /// that it can be found later for redeclarations. We include any extern "C" 5998 /// declaration that is not visible in the translation unit here, not just 5999 /// function-scope declarations. 6000 void 6001 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6002 if (!getLangOpts().CPlusPlus && 6003 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6004 // Don't need to track declarations in the TU in C. 6005 return; 6006 6007 // Note that we have a locally-scoped external with this name. 6008 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6009 } 6010 6011 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6012 // FIXME: We can have multiple results via __attribute__((overloadable)). 6013 auto Result = Context.getExternCContextDecl()->lookup(Name); 6014 return Result.empty() ? nullptr : *Result.begin(); 6015 } 6016 6017 /// Diagnose function specifiers on a declaration of an identifier that 6018 /// does not identify a function. 6019 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6020 // FIXME: We should probably indicate the identifier in question to avoid 6021 // confusion for constructs like "virtual int a(), b;" 6022 if (DS.isVirtualSpecified()) 6023 Diag(DS.getVirtualSpecLoc(), 6024 diag::err_virtual_non_function); 6025 6026 if (DS.hasExplicitSpecifier()) 6027 Diag(DS.getExplicitSpecLoc(), 6028 diag::err_explicit_non_function); 6029 6030 if (DS.isNoreturnSpecified()) 6031 Diag(DS.getNoreturnSpecLoc(), 6032 diag::err_noreturn_non_function); 6033 } 6034 6035 NamedDecl* 6036 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6037 TypeSourceInfo *TInfo, LookupResult &Previous) { 6038 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6039 if (D.getCXXScopeSpec().isSet()) { 6040 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6041 << D.getCXXScopeSpec().getRange(); 6042 D.setInvalidType(); 6043 // Pretend we didn't see the scope specifier. 6044 DC = CurContext; 6045 Previous.clear(); 6046 } 6047 6048 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6049 6050 if (D.getDeclSpec().isInlineSpecified()) 6051 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6052 << getLangOpts().CPlusPlus17; 6053 if (D.getDeclSpec().hasConstexprSpecifier()) 6054 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6055 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6056 6057 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6058 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6059 Diag(D.getName().StartLocation, 6060 diag::err_deduction_guide_invalid_specifier) 6061 << "typedef"; 6062 else 6063 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6064 << D.getName().getSourceRange(); 6065 return nullptr; 6066 } 6067 6068 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6069 if (!NewTD) return nullptr; 6070 6071 // Handle attributes prior to checking for duplicates in MergeVarDecl 6072 ProcessDeclAttributes(S, NewTD, D); 6073 6074 CheckTypedefForVariablyModifiedType(S, NewTD); 6075 6076 bool Redeclaration = D.isRedeclaration(); 6077 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6078 D.setRedeclaration(Redeclaration); 6079 return ND; 6080 } 6081 6082 void 6083 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6084 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6085 // then it shall have block scope. 6086 // Note that variably modified types must be fixed before merging the decl so 6087 // that redeclarations will match. 6088 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6089 QualType T = TInfo->getType(); 6090 if (T->isVariablyModifiedType()) { 6091 setFunctionHasBranchProtectedScope(); 6092 6093 if (S->getFnParent() == nullptr) { 6094 bool SizeIsNegative; 6095 llvm::APSInt Oversized; 6096 TypeSourceInfo *FixedTInfo = 6097 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6098 SizeIsNegative, 6099 Oversized); 6100 if (FixedTInfo) { 6101 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6102 NewTD->setTypeSourceInfo(FixedTInfo); 6103 } else { 6104 if (SizeIsNegative) 6105 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6106 else if (T->isVariableArrayType()) 6107 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6108 else if (Oversized.getBoolValue()) 6109 Diag(NewTD->getLocation(), diag::err_array_too_large) 6110 << Oversized.toString(10); 6111 else 6112 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6113 NewTD->setInvalidDecl(); 6114 } 6115 } 6116 } 6117 } 6118 6119 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6120 /// declares a typedef-name, either using the 'typedef' type specifier or via 6121 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6122 NamedDecl* 6123 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6124 LookupResult &Previous, bool &Redeclaration) { 6125 6126 // Find the shadowed declaration before filtering for scope. 6127 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6128 6129 // Merge the decl with the existing one if appropriate. If the decl is 6130 // in an outer scope, it isn't the same thing. 6131 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6132 /*AllowInlineNamespace*/false); 6133 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6134 if (!Previous.empty()) { 6135 Redeclaration = true; 6136 MergeTypedefNameDecl(S, NewTD, Previous); 6137 } else { 6138 inferGslPointerAttribute(NewTD); 6139 } 6140 6141 if (ShadowedDecl && !Redeclaration) 6142 CheckShadow(NewTD, ShadowedDecl, Previous); 6143 6144 // If this is the C FILE type, notify the AST context. 6145 if (IdentifierInfo *II = NewTD->getIdentifier()) 6146 if (!NewTD->isInvalidDecl() && 6147 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6148 if (II->isStr("FILE")) 6149 Context.setFILEDecl(NewTD); 6150 else if (II->isStr("jmp_buf")) 6151 Context.setjmp_bufDecl(NewTD); 6152 else if (II->isStr("sigjmp_buf")) 6153 Context.setsigjmp_bufDecl(NewTD); 6154 else if (II->isStr("ucontext_t")) 6155 Context.setucontext_tDecl(NewTD); 6156 } 6157 6158 return NewTD; 6159 } 6160 6161 /// Determines whether the given declaration is an out-of-scope 6162 /// previous declaration. 6163 /// 6164 /// This routine should be invoked when name lookup has found a 6165 /// previous declaration (PrevDecl) that is not in the scope where a 6166 /// new declaration by the same name is being introduced. If the new 6167 /// declaration occurs in a local scope, previous declarations with 6168 /// linkage may still be considered previous declarations (C99 6169 /// 6.2.2p4-5, C++ [basic.link]p6). 6170 /// 6171 /// \param PrevDecl the previous declaration found by name 6172 /// lookup 6173 /// 6174 /// \param DC the context in which the new declaration is being 6175 /// declared. 6176 /// 6177 /// \returns true if PrevDecl is an out-of-scope previous declaration 6178 /// for a new delcaration with the same name. 6179 static bool 6180 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6181 ASTContext &Context) { 6182 if (!PrevDecl) 6183 return false; 6184 6185 if (!PrevDecl->hasLinkage()) 6186 return false; 6187 6188 if (Context.getLangOpts().CPlusPlus) { 6189 // C++ [basic.link]p6: 6190 // If there is a visible declaration of an entity with linkage 6191 // having the same name and type, ignoring entities declared 6192 // outside the innermost enclosing namespace scope, the block 6193 // scope declaration declares that same entity and receives the 6194 // linkage of the previous declaration. 6195 DeclContext *OuterContext = DC->getRedeclContext(); 6196 if (!OuterContext->isFunctionOrMethod()) 6197 // This rule only applies to block-scope declarations. 6198 return false; 6199 6200 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6201 if (PrevOuterContext->isRecord()) 6202 // We found a member function: ignore it. 6203 return false; 6204 6205 // Find the innermost enclosing namespace for the new and 6206 // previous declarations. 6207 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6208 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6209 6210 // The previous declaration is in a different namespace, so it 6211 // isn't the same function. 6212 if (!OuterContext->Equals(PrevOuterContext)) 6213 return false; 6214 } 6215 6216 return true; 6217 } 6218 6219 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6220 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6221 if (!SS.isSet()) return; 6222 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6223 } 6224 6225 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6226 QualType type = decl->getType(); 6227 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6228 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6229 // Various kinds of declaration aren't allowed to be __autoreleasing. 6230 unsigned kind = -1U; 6231 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6232 if (var->hasAttr<BlocksAttr>()) 6233 kind = 0; // __block 6234 else if (!var->hasLocalStorage()) 6235 kind = 1; // global 6236 } else if (isa<ObjCIvarDecl>(decl)) { 6237 kind = 3; // ivar 6238 } else if (isa<FieldDecl>(decl)) { 6239 kind = 2; // field 6240 } 6241 6242 if (kind != -1U) { 6243 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6244 << kind; 6245 } 6246 } else if (lifetime == Qualifiers::OCL_None) { 6247 // Try to infer lifetime. 6248 if (!type->isObjCLifetimeType()) 6249 return false; 6250 6251 lifetime = type->getObjCARCImplicitLifetime(); 6252 type = Context.getLifetimeQualifiedType(type, lifetime); 6253 decl->setType(type); 6254 } 6255 6256 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6257 // Thread-local variables cannot have lifetime. 6258 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6259 var->getTLSKind()) { 6260 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6261 << var->getType(); 6262 return true; 6263 } 6264 } 6265 6266 return false; 6267 } 6268 6269 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6270 if (Decl->getType().hasAddressSpace()) 6271 return; 6272 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6273 QualType Type = Var->getType(); 6274 if (Type->isSamplerT() || Type->isVoidType()) 6275 return; 6276 LangAS ImplAS = LangAS::opencl_private; 6277 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6278 Var->hasGlobalStorage()) 6279 ImplAS = LangAS::opencl_global; 6280 // If the original type from a decayed type is an array type and that array 6281 // type has no address space yet, deduce it now. 6282 if (auto DT = dyn_cast<DecayedType>(Type)) { 6283 auto OrigTy = DT->getOriginalType(); 6284 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6285 // Add the address space to the original array type and then propagate 6286 // that to the element type through `getAsArrayType`. 6287 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6288 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6289 // Re-generate the decayed type. 6290 Type = Context.getDecayedType(OrigTy); 6291 } 6292 } 6293 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6294 // Apply any qualifiers (including address space) from the array type to 6295 // the element type. This implements C99 6.7.3p8: "If the specification of 6296 // an array type includes any type qualifiers, the element type is so 6297 // qualified, not the array type." 6298 if (Type->isArrayType()) 6299 Type = QualType(Context.getAsArrayType(Type), 0); 6300 Decl->setType(Type); 6301 } 6302 } 6303 6304 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6305 // Ensure that an auto decl is deduced otherwise the checks below might cache 6306 // the wrong linkage. 6307 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6308 6309 // 'weak' only applies to declarations with external linkage. 6310 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6311 if (!ND.isExternallyVisible()) { 6312 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6313 ND.dropAttr<WeakAttr>(); 6314 } 6315 } 6316 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6317 if (ND.isExternallyVisible()) { 6318 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6319 ND.dropAttr<WeakRefAttr>(); 6320 ND.dropAttr<AliasAttr>(); 6321 } 6322 } 6323 6324 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6325 if (VD->hasInit()) { 6326 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6327 assert(VD->isThisDeclarationADefinition() && 6328 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6329 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6330 VD->dropAttr<AliasAttr>(); 6331 } 6332 } 6333 } 6334 6335 // 'selectany' only applies to externally visible variable declarations. 6336 // It does not apply to functions. 6337 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6338 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6339 S.Diag(Attr->getLocation(), 6340 diag::err_attribute_selectany_non_extern_data); 6341 ND.dropAttr<SelectAnyAttr>(); 6342 } 6343 } 6344 6345 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6346 auto *VD = dyn_cast<VarDecl>(&ND); 6347 bool IsAnonymousNS = false; 6348 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6349 if (VD) { 6350 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6351 while (NS && !IsAnonymousNS) { 6352 IsAnonymousNS = NS->isAnonymousNamespace(); 6353 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6354 } 6355 } 6356 // dll attributes require external linkage. Static locals may have external 6357 // linkage but still cannot be explicitly imported or exported. 6358 // In Microsoft mode, a variable defined in anonymous namespace must have 6359 // external linkage in order to be exported. 6360 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6361 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6362 (!AnonNSInMicrosoftMode && 6363 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6364 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6365 << &ND << Attr; 6366 ND.setInvalidDecl(); 6367 } 6368 } 6369 6370 // Virtual functions cannot be marked as 'notail'. 6371 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6372 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6373 if (MD->isVirtual()) { 6374 S.Diag(ND.getLocation(), 6375 diag::err_invalid_attribute_on_virtual_function) 6376 << Attr; 6377 ND.dropAttr<NotTailCalledAttr>(); 6378 } 6379 6380 // Check the attributes on the function type, if any. 6381 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6382 // Don't declare this variable in the second operand of the for-statement; 6383 // GCC miscompiles that by ending its lifetime before evaluating the 6384 // third operand. See gcc.gnu.org/PR86769. 6385 AttributedTypeLoc ATL; 6386 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6387 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6388 TL = ATL.getModifiedLoc()) { 6389 // The [[lifetimebound]] attribute can be applied to the implicit object 6390 // parameter of a non-static member function (other than a ctor or dtor) 6391 // by applying it to the function type. 6392 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6393 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6394 if (!MD || MD->isStatic()) { 6395 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6396 << !MD << A->getRange(); 6397 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6398 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6399 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6400 } 6401 } 6402 } 6403 } 6404 } 6405 6406 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6407 NamedDecl *NewDecl, 6408 bool IsSpecialization, 6409 bool IsDefinition) { 6410 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6411 return; 6412 6413 bool IsTemplate = false; 6414 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6415 OldDecl = OldTD->getTemplatedDecl(); 6416 IsTemplate = true; 6417 if (!IsSpecialization) 6418 IsDefinition = false; 6419 } 6420 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6421 NewDecl = NewTD->getTemplatedDecl(); 6422 IsTemplate = true; 6423 } 6424 6425 if (!OldDecl || !NewDecl) 6426 return; 6427 6428 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6429 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6430 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6431 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6432 6433 // dllimport and dllexport are inheritable attributes so we have to exclude 6434 // inherited attribute instances. 6435 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6436 (NewExportAttr && !NewExportAttr->isInherited()); 6437 6438 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6439 // the only exception being explicit specializations. 6440 // Implicitly generated declarations are also excluded for now because there 6441 // is no other way to switch these to use dllimport or dllexport. 6442 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6443 6444 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6445 // Allow with a warning for free functions and global variables. 6446 bool JustWarn = false; 6447 if (!OldDecl->isCXXClassMember()) { 6448 auto *VD = dyn_cast<VarDecl>(OldDecl); 6449 if (VD && !VD->getDescribedVarTemplate()) 6450 JustWarn = true; 6451 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6452 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6453 JustWarn = true; 6454 } 6455 6456 // We cannot change a declaration that's been used because IR has already 6457 // been emitted. Dllimported functions will still work though (modulo 6458 // address equality) as they can use the thunk. 6459 if (OldDecl->isUsed()) 6460 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6461 JustWarn = false; 6462 6463 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6464 : diag::err_attribute_dll_redeclaration; 6465 S.Diag(NewDecl->getLocation(), DiagID) 6466 << NewDecl 6467 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6468 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6469 if (!JustWarn) { 6470 NewDecl->setInvalidDecl(); 6471 return; 6472 } 6473 } 6474 6475 // A redeclaration is not allowed to drop a dllimport attribute, the only 6476 // exceptions being inline function definitions (except for function 6477 // templates), local extern declarations, qualified friend declarations or 6478 // special MSVC extension: in the last case, the declaration is treated as if 6479 // it were marked dllexport. 6480 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6481 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6482 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6483 // Ignore static data because out-of-line definitions are diagnosed 6484 // separately. 6485 IsStaticDataMember = VD->isStaticDataMember(); 6486 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6487 VarDecl::DeclarationOnly; 6488 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6489 IsInline = FD->isInlined(); 6490 IsQualifiedFriend = FD->getQualifier() && 6491 FD->getFriendObjectKind() == Decl::FOK_Declared; 6492 } 6493 6494 if (OldImportAttr && !HasNewAttr && 6495 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6496 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6497 if (IsMicrosoft && IsDefinition) { 6498 S.Diag(NewDecl->getLocation(), 6499 diag::warn_redeclaration_without_import_attribute) 6500 << NewDecl; 6501 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6502 NewDecl->dropAttr<DLLImportAttr>(); 6503 NewDecl->addAttr( 6504 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6505 } else { 6506 S.Diag(NewDecl->getLocation(), 6507 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6508 << NewDecl << OldImportAttr; 6509 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6510 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6511 OldDecl->dropAttr<DLLImportAttr>(); 6512 NewDecl->dropAttr<DLLImportAttr>(); 6513 } 6514 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6515 // In MinGW, seeing a function declared inline drops the dllimport 6516 // attribute. 6517 OldDecl->dropAttr<DLLImportAttr>(); 6518 NewDecl->dropAttr<DLLImportAttr>(); 6519 S.Diag(NewDecl->getLocation(), 6520 diag::warn_dllimport_dropped_from_inline_function) 6521 << NewDecl << OldImportAttr; 6522 } 6523 6524 // A specialization of a class template member function is processed here 6525 // since it's a redeclaration. If the parent class is dllexport, the 6526 // specialization inherits that attribute. This doesn't happen automatically 6527 // since the parent class isn't instantiated until later. 6528 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6529 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6530 !NewImportAttr && !NewExportAttr) { 6531 if (const DLLExportAttr *ParentExportAttr = 6532 MD->getParent()->getAttr<DLLExportAttr>()) { 6533 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6534 NewAttr->setInherited(true); 6535 NewDecl->addAttr(NewAttr); 6536 } 6537 } 6538 } 6539 } 6540 6541 /// Given that we are within the definition of the given function, 6542 /// will that definition behave like C99's 'inline', where the 6543 /// definition is discarded except for optimization purposes? 6544 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6545 // Try to avoid calling GetGVALinkageForFunction. 6546 6547 // All cases of this require the 'inline' keyword. 6548 if (!FD->isInlined()) return false; 6549 6550 // This is only possible in C++ with the gnu_inline attribute. 6551 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6552 return false; 6553 6554 // Okay, go ahead and call the relatively-more-expensive function. 6555 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6556 } 6557 6558 /// Determine whether a variable is extern "C" prior to attaching 6559 /// an initializer. We can't just call isExternC() here, because that 6560 /// will also compute and cache whether the declaration is externally 6561 /// visible, which might change when we attach the initializer. 6562 /// 6563 /// This can only be used if the declaration is known to not be a 6564 /// redeclaration of an internal linkage declaration. 6565 /// 6566 /// For instance: 6567 /// 6568 /// auto x = []{}; 6569 /// 6570 /// Attaching the initializer here makes this declaration not externally 6571 /// visible, because its type has internal linkage. 6572 /// 6573 /// FIXME: This is a hack. 6574 template<typename T> 6575 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6576 if (S.getLangOpts().CPlusPlus) { 6577 // In C++, the overloadable attribute negates the effects of extern "C". 6578 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6579 return false; 6580 6581 // So do CUDA's host/device attributes. 6582 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6583 D->template hasAttr<CUDAHostAttr>())) 6584 return false; 6585 } 6586 return D->isExternC(); 6587 } 6588 6589 static bool shouldConsiderLinkage(const VarDecl *VD) { 6590 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6591 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6592 isa<OMPDeclareMapperDecl>(DC)) 6593 return VD->hasExternalStorage(); 6594 if (DC->isFileContext()) 6595 return true; 6596 if (DC->isRecord()) 6597 return false; 6598 if (isa<RequiresExprBodyDecl>(DC)) 6599 return false; 6600 llvm_unreachable("Unexpected context"); 6601 } 6602 6603 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6604 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6605 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6606 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6607 return true; 6608 if (DC->isRecord()) 6609 return false; 6610 llvm_unreachable("Unexpected context"); 6611 } 6612 6613 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6614 ParsedAttr::Kind Kind) { 6615 // Check decl attributes on the DeclSpec. 6616 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6617 return true; 6618 6619 // Walk the declarator structure, checking decl attributes that were in a type 6620 // position to the decl itself. 6621 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6622 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6623 return true; 6624 } 6625 6626 // Finally, check attributes on the decl itself. 6627 return PD.getAttributes().hasAttribute(Kind); 6628 } 6629 6630 /// Adjust the \c DeclContext for a function or variable that might be a 6631 /// function-local external declaration. 6632 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6633 if (!DC->isFunctionOrMethod()) 6634 return false; 6635 6636 // If this is a local extern function or variable declared within a function 6637 // template, don't add it into the enclosing namespace scope until it is 6638 // instantiated; it might have a dependent type right now. 6639 if (DC->isDependentContext()) 6640 return true; 6641 6642 // C++11 [basic.link]p7: 6643 // When a block scope declaration of an entity with linkage is not found to 6644 // refer to some other declaration, then that entity is a member of the 6645 // innermost enclosing namespace. 6646 // 6647 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6648 // semantically-enclosing namespace, not a lexically-enclosing one. 6649 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6650 DC = DC->getParent(); 6651 return true; 6652 } 6653 6654 /// Returns true if given declaration has external C language linkage. 6655 static bool isDeclExternC(const Decl *D) { 6656 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6657 return FD->isExternC(); 6658 if (const auto *VD = dyn_cast<VarDecl>(D)) 6659 return VD->isExternC(); 6660 6661 llvm_unreachable("Unknown type of decl!"); 6662 } 6663 /// Returns true if there hasn't been any invalid type diagnosed. 6664 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6665 DeclContext *DC, QualType R) { 6666 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6667 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6668 // argument. 6669 if (R->isImageType() || R->isPipeType()) { 6670 Se.Diag(D.getIdentifierLoc(), 6671 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6672 << R; 6673 D.setInvalidType(); 6674 return false; 6675 } 6676 6677 // OpenCL v1.2 s6.9.r: 6678 // The event type cannot be used to declare a program scope variable. 6679 // OpenCL v2.0 s6.9.q: 6680 // The clk_event_t and reserve_id_t types cannot be declared in program 6681 // scope. 6682 if (NULL == S->getParent()) { 6683 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6684 Se.Diag(D.getIdentifierLoc(), 6685 diag::err_invalid_type_for_program_scope_var) 6686 << R; 6687 D.setInvalidType(); 6688 return false; 6689 } 6690 } 6691 6692 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6693 QualType NR = R; 6694 while (NR->isPointerType()) { 6695 if (NR->isFunctionPointerType()) { 6696 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6697 D.setInvalidType(); 6698 return false; 6699 } 6700 NR = NR->getPointeeType(); 6701 } 6702 6703 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6704 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6705 // half array type (unless the cl_khr_fp16 extension is enabled). 6706 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6707 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6708 D.setInvalidType(); 6709 return false; 6710 } 6711 } 6712 6713 // OpenCL v1.2 s6.9.r: 6714 // The event type cannot be used with the __local, __constant and __global 6715 // address space qualifiers. 6716 if (R->isEventT()) { 6717 if (R.getAddressSpace() != LangAS::opencl_private) { 6718 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6719 D.setInvalidType(); 6720 return false; 6721 } 6722 } 6723 6724 // C++ for OpenCL does not allow the thread_local storage qualifier. 6725 // OpenCL C does not support thread_local either, and 6726 // also reject all other thread storage class specifiers. 6727 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6728 if (TSC != TSCS_unspecified) { 6729 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6730 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6731 diag::err_opencl_unknown_type_specifier) 6732 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6733 << DeclSpec::getSpecifierName(TSC) << 1; 6734 D.setInvalidType(); 6735 return false; 6736 } 6737 6738 if (R->isSamplerT()) { 6739 // OpenCL v1.2 s6.9.b p4: 6740 // The sampler type cannot be used with the __local and __global address 6741 // space qualifiers. 6742 if (R.getAddressSpace() == LangAS::opencl_local || 6743 R.getAddressSpace() == LangAS::opencl_global) { 6744 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6745 D.setInvalidType(); 6746 } 6747 6748 // OpenCL v1.2 s6.12.14.1: 6749 // A global sampler must be declared with either the constant address 6750 // space qualifier or with the const qualifier. 6751 if (DC->isTranslationUnit() && 6752 !(R.getAddressSpace() == LangAS::opencl_constant || 6753 R.isConstQualified())) { 6754 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6755 D.setInvalidType(); 6756 } 6757 if (D.isInvalidType()) 6758 return false; 6759 } 6760 return true; 6761 } 6762 6763 NamedDecl *Sema::ActOnVariableDeclarator( 6764 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6765 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6766 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6767 QualType R = TInfo->getType(); 6768 DeclarationName Name = GetNameForDeclarator(D).getName(); 6769 6770 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6771 6772 if (D.isDecompositionDeclarator()) { 6773 // Take the name of the first declarator as our name for diagnostic 6774 // purposes. 6775 auto &Decomp = D.getDecompositionDeclarator(); 6776 if (!Decomp.bindings().empty()) { 6777 II = Decomp.bindings()[0].Name; 6778 Name = II; 6779 } 6780 } else if (!II) { 6781 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6782 return nullptr; 6783 } 6784 6785 6786 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6787 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6788 6789 // dllimport globals without explicit storage class are treated as extern. We 6790 // have to change the storage class this early to get the right DeclContext. 6791 if (SC == SC_None && !DC->isRecord() && 6792 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6793 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6794 SC = SC_Extern; 6795 6796 DeclContext *OriginalDC = DC; 6797 bool IsLocalExternDecl = SC == SC_Extern && 6798 adjustContextForLocalExternDecl(DC); 6799 6800 if (SCSpec == DeclSpec::SCS_mutable) { 6801 // mutable can only appear on non-static class members, so it's always 6802 // an error here 6803 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6804 D.setInvalidType(); 6805 SC = SC_None; 6806 } 6807 6808 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6809 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6810 D.getDeclSpec().getStorageClassSpecLoc())) { 6811 // In C++11, the 'register' storage class specifier is deprecated. 6812 // Suppress the warning in system macros, it's used in macros in some 6813 // popular C system headers, such as in glibc's htonl() macro. 6814 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6815 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6816 : diag::warn_deprecated_register) 6817 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6818 } 6819 6820 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6821 6822 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6823 // C99 6.9p2: The storage-class specifiers auto and register shall not 6824 // appear in the declaration specifiers in an external declaration. 6825 // Global Register+Asm is a GNU extension we support. 6826 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6827 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6828 D.setInvalidType(); 6829 } 6830 } 6831 6832 bool IsMemberSpecialization = false; 6833 bool IsVariableTemplateSpecialization = false; 6834 bool IsPartialSpecialization = false; 6835 bool IsVariableTemplate = false; 6836 VarDecl *NewVD = nullptr; 6837 VarTemplateDecl *NewTemplate = nullptr; 6838 TemplateParameterList *TemplateParams = nullptr; 6839 if (!getLangOpts().CPlusPlus) { 6840 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6841 II, R, TInfo, SC); 6842 6843 if (R->getContainedDeducedType()) 6844 ParsingInitForAutoVars.insert(NewVD); 6845 6846 if (D.isInvalidType()) 6847 NewVD->setInvalidDecl(); 6848 6849 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6850 NewVD->hasLocalStorage()) 6851 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6852 NTCUC_AutoVar, NTCUK_Destruct); 6853 } else { 6854 bool Invalid = false; 6855 6856 if (DC->isRecord() && !CurContext->isRecord()) { 6857 // This is an out-of-line definition of a static data member. 6858 switch (SC) { 6859 case SC_None: 6860 break; 6861 case SC_Static: 6862 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6863 diag::err_static_out_of_line) 6864 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6865 break; 6866 case SC_Auto: 6867 case SC_Register: 6868 case SC_Extern: 6869 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6870 // to names of variables declared in a block or to function parameters. 6871 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6872 // of class members 6873 6874 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6875 diag::err_storage_class_for_static_member) 6876 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6877 break; 6878 case SC_PrivateExtern: 6879 llvm_unreachable("C storage class in c++!"); 6880 } 6881 } 6882 6883 if (SC == SC_Static && CurContext->isRecord()) { 6884 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6885 // C++ [class.static.data]p2: 6886 // A static data member shall not be a direct member of an unnamed 6887 // or local class 6888 // FIXME: or of a (possibly indirectly) nested class thereof. 6889 if (RD->isLocalClass()) { 6890 Diag(D.getIdentifierLoc(), 6891 diag::err_static_data_member_not_allowed_in_local_class) 6892 << Name << RD->getDeclName() << RD->getTagKind(); 6893 } else if (!RD->getDeclName()) { 6894 Diag(D.getIdentifierLoc(), 6895 diag::err_static_data_member_not_allowed_in_anon_struct) 6896 << Name << RD->getTagKind(); 6897 Invalid = true; 6898 } else if (RD->isUnion()) { 6899 // C++98 [class.union]p1: If a union contains a static data member, 6900 // the program is ill-formed. C++11 drops this restriction. 6901 Diag(D.getIdentifierLoc(), 6902 getLangOpts().CPlusPlus11 6903 ? diag::warn_cxx98_compat_static_data_member_in_union 6904 : diag::ext_static_data_member_in_union) << Name; 6905 } 6906 } 6907 } 6908 6909 // Match up the template parameter lists with the scope specifier, then 6910 // determine whether we have a template or a template specialization. 6911 bool InvalidScope = false; 6912 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6913 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6914 D.getCXXScopeSpec(), 6915 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6916 ? D.getName().TemplateId 6917 : nullptr, 6918 TemplateParamLists, 6919 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6920 Invalid |= InvalidScope; 6921 6922 if (TemplateParams) { 6923 if (!TemplateParams->size() && 6924 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6925 // There is an extraneous 'template<>' for this variable. Complain 6926 // about it, but allow the declaration of the variable. 6927 Diag(TemplateParams->getTemplateLoc(), 6928 diag::err_template_variable_noparams) 6929 << II 6930 << SourceRange(TemplateParams->getTemplateLoc(), 6931 TemplateParams->getRAngleLoc()); 6932 TemplateParams = nullptr; 6933 } else { 6934 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6935 // This is an explicit specialization or a partial specialization. 6936 // FIXME: Check that we can declare a specialization here. 6937 IsVariableTemplateSpecialization = true; 6938 IsPartialSpecialization = TemplateParams->size() > 0; 6939 } else { // if (TemplateParams->size() > 0) 6940 // This is a template declaration. 6941 IsVariableTemplate = true; 6942 6943 // Check that we can declare a template here. 6944 if (CheckTemplateDeclScope(S, TemplateParams)) 6945 return nullptr; 6946 6947 // Only C++1y supports variable templates (N3651). 6948 Diag(D.getIdentifierLoc(), 6949 getLangOpts().CPlusPlus14 6950 ? diag::warn_cxx11_compat_variable_template 6951 : diag::ext_variable_template); 6952 } 6953 } 6954 } else { 6955 assert((Invalid || 6956 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6957 "should have a 'template<>' for this decl"); 6958 } 6959 6960 if (IsVariableTemplateSpecialization) { 6961 SourceLocation TemplateKWLoc = 6962 TemplateParamLists.size() > 0 6963 ? TemplateParamLists[0]->getTemplateLoc() 6964 : SourceLocation(); 6965 DeclResult Res = ActOnVarTemplateSpecialization( 6966 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6967 IsPartialSpecialization); 6968 if (Res.isInvalid()) 6969 return nullptr; 6970 NewVD = cast<VarDecl>(Res.get()); 6971 AddToScope = false; 6972 } else if (D.isDecompositionDeclarator()) { 6973 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6974 D.getIdentifierLoc(), R, TInfo, SC, 6975 Bindings); 6976 } else 6977 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6978 D.getIdentifierLoc(), II, R, TInfo, SC); 6979 6980 // If this is supposed to be a variable template, create it as such. 6981 if (IsVariableTemplate) { 6982 NewTemplate = 6983 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6984 TemplateParams, NewVD); 6985 NewVD->setDescribedVarTemplate(NewTemplate); 6986 } 6987 6988 // If this decl has an auto type in need of deduction, make a note of the 6989 // Decl so we can diagnose uses of it in its own initializer. 6990 if (R->getContainedDeducedType()) 6991 ParsingInitForAutoVars.insert(NewVD); 6992 6993 if (D.isInvalidType() || Invalid) { 6994 NewVD->setInvalidDecl(); 6995 if (NewTemplate) 6996 NewTemplate->setInvalidDecl(); 6997 } 6998 6999 SetNestedNameSpecifier(*this, NewVD, D); 7000 7001 // If we have any template parameter lists that don't directly belong to 7002 // the variable (matching the scope specifier), store them. 7003 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7004 if (TemplateParamLists.size() > VDTemplateParamLists) 7005 NewVD->setTemplateParameterListsInfo( 7006 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7007 } 7008 7009 if (D.getDeclSpec().isInlineSpecified()) { 7010 if (!getLangOpts().CPlusPlus) { 7011 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7012 << 0; 7013 } else if (CurContext->isFunctionOrMethod()) { 7014 // 'inline' is not allowed on block scope variable declaration. 7015 Diag(D.getDeclSpec().getInlineSpecLoc(), 7016 diag::err_inline_declaration_block_scope) << Name 7017 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7018 } else { 7019 Diag(D.getDeclSpec().getInlineSpecLoc(), 7020 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7021 : diag::ext_inline_variable); 7022 NewVD->setInlineSpecified(); 7023 } 7024 } 7025 7026 // Set the lexical context. If the declarator has a C++ scope specifier, the 7027 // lexical context will be different from the semantic context. 7028 NewVD->setLexicalDeclContext(CurContext); 7029 if (NewTemplate) 7030 NewTemplate->setLexicalDeclContext(CurContext); 7031 7032 if (IsLocalExternDecl) { 7033 if (D.isDecompositionDeclarator()) 7034 for (auto *B : Bindings) 7035 B->setLocalExternDecl(); 7036 else 7037 NewVD->setLocalExternDecl(); 7038 } 7039 7040 bool EmitTLSUnsupportedError = false; 7041 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7042 // C++11 [dcl.stc]p4: 7043 // When thread_local is applied to a variable of block scope the 7044 // storage-class-specifier static is implied if it does not appear 7045 // explicitly. 7046 // Core issue: 'static' is not implied if the variable is declared 7047 // 'extern'. 7048 if (NewVD->hasLocalStorage() && 7049 (SCSpec != DeclSpec::SCS_unspecified || 7050 TSCS != DeclSpec::TSCS_thread_local || 7051 !DC->isFunctionOrMethod())) 7052 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7053 diag::err_thread_non_global) 7054 << DeclSpec::getSpecifierName(TSCS); 7055 else if (!Context.getTargetInfo().isTLSSupported()) { 7056 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7057 // Postpone error emission until we've collected attributes required to 7058 // figure out whether it's a host or device variable and whether the 7059 // error should be ignored. 7060 EmitTLSUnsupportedError = true; 7061 // We still need to mark the variable as TLS so it shows up in AST with 7062 // proper storage class for other tools to use even if we're not going 7063 // to emit any code for it. 7064 NewVD->setTSCSpec(TSCS); 7065 } else 7066 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7067 diag::err_thread_unsupported); 7068 } else 7069 NewVD->setTSCSpec(TSCS); 7070 } 7071 7072 switch (D.getDeclSpec().getConstexprSpecifier()) { 7073 case CSK_unspecified: 7074 break; 7075 7076 case CSK_consteval: 7077 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7078 diag::err_constexpr_wrong_decl_kind) 7079 << D.getDeclSpec().getConstexprSpecifier(); 7080 LLVM_FALLTHROUGH; 7081 7082 case CSK_constexpr: 7083 NewVD->setConstexpr(true); 7084 // C++1z [dcl.spec.constexpr]p1: 7085 // A static data member declared with the constexpr specifier is 7086 // implicitly an inline variable. 7087 if (NewVD->isStaticDataMember() && 7088 (getLangOpts().CPlusPlus17 || 7089 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7090 NewVD->setImplicitlyInline(); 7091 break; 7092 7093 case CSK_constinit: 7094 if (!NewVD->hasGlobalStorage()) 7095 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7096 diag::err_constinit_local_variable); 7097 else 7098 NewVD->addAttr(ConstInitAttr::Create( 7099 Context, D.getDeclSpec().getConstexprSpecLoc(), 7100 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7101 break; 7102 } 7103 7104 // C99 6.7.4p3 7105 // An inline definition of a function with external linkage shall 7106 // not contain a definition of a modifiable object with static or 7107 // thread storage duration... 7108 // We only apply this when the function is required to be defined 7109 // elsewhere, i.e. when the function is not 'extern inline'. Note 7110 // that a local variable with thread storage duration still has to 7111 // be marked 'static'. Also note that it's possible to get these 7112 // semantics in C++ using __attribute__((gnu_inline)). 7113 if (SC == SC_Static && S->getFnParent() != nullptr && 7114 !NewVD->getType().isConstQualified()) { 7115 FunctionDecl *CurFD = getCurFunctionDecl(); 7116 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7117 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7118 diag::warn_static_local_in_extern_inline); 7119 MaybeSuggestAddingStaticToDecl(CurFD); 7120 } 7121 } 7122 7123 if (D.getDeclSpec().isModulePrivateSpecified()) { 7124 if (IsVariableTemplateSpecialization) 7125 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7126 << (IsPartialSpecialization ? 1 : 0) 7127 << FixItHint::CreateRemoval( 7128 D.getDeclSpec().getModulePrivateSpecLoc()); 7129 else if (IsMemberSpecialization) 7130 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7131 << 2 7132 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7133 else if (NewVD->hasLocalStorage()) 7134 Diag(NewVD->getLocation(), diag::err_module_private_local) 7135 << 0 << NewVD->getDeclName() 7136 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7137 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7138 else { 7139 NewVD->setModulePrivate(); 7140 if (NewTemplate) 7141 NewTemplate->setModulePrivate(); 7142 for (auto *B : Bindings) 7143 B->setModulePrivate(); 7144 } 7145 } 7146 7147 if (getLangOpts().OpenCL) { 7148 7149 deduceOpenCLAddressSpace(NewVD); 7150 7151 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7152 } 7153 7154 // Handle attributes prior to checking for duplicates in MergeVarDecl 7155 ProcessDeclAttributes(S, NewVD, D); 7156 7157 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7158 if (EmitTLSUnsupportedError && 7159 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7160 (getLangOpts().OpenMPIsDevice && 7161 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7162 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7163 diag::err_thread_unsupported); 7164 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7165 // storage [duration]." 7166 if (SC == SC_None && S->getFnParent() != nullptr && 7167 (NewVD->hasAttr<CUDASharedAttr>() || 7168 NewVD->hasAttr<CUDAConstantAttr>())) { 7169 NewVD->setStorageClass(SC_Static); 7170 } 7171 } 7172 7173 // Ensure that dllimport globals without explicit storage class are treated as 7174 // extern. The storage class is set above using parsed attributes. Now we can 7175 // check the VarDecl itself. 7176 assert(!NewVD->hasAttr<DLLImportAttr>() || 7177 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7178 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7179 7180 // In auto-retain/release, infer strong retension for variables of 7181 // retainable type. 7182 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7183 NewVD->setInvalidDecl(); 7184 7185 // Handle GNU asm-label extension (encoded as an attribute). 7186 if (Expr *E = (Expr*)D.getAsmLabel()) { 7187 // The parser guarantees this is a string. 7188 StringLiteral *SE = cast<StringLiteral>(E); 7189 StringRef Label = SE->getString(); 7190 if (S->getFnParent() != nullptr) { 7191 switch (SC) { 7192 case SC_None: 7193 case SC_Auto: 7194 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7195 break; 7196 case SC_Register: 7197 // Local Named register 7198 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7199 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7200 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7201 break; 7202 case SC_Static: 7203 case SC_Extern: 7204 case SC_PrivateExtern: 7205 break; 7206 } 7207 } else if (SC == SC_Register) { 7208 // Global Named register 7209 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7210 const auto &TI = Context.getTargetInfo(); 7211 bool HasSizeMismatch; 7212 7213 if (!TI.isValidGCCRegisterName(Label)) 7214 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7215 else if (!TI.validateGlobalRegisterVariable(Label, 7216 Context.getTypeSize(R), 7217 HasSizeMismatch)) 7218 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7219 else if (HasSizeMismatch) 7220 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7221 } 7222 7223 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7224 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7225 NewVD->setInvalidDecl(true); 7226 } 7227 } 7228 7229 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7230 /*IsLiteralLabel=*/true, 7231 SE->getStrTokenLoc(0))); 7232 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7233 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7234 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7235 if (I != ExtnameUndeclaredIdentifiers.end()) { 7236 if (isDeclExternC(NewVD)) { 7237 NewVD->addAttr(I->second); 7238 ExtnameUndeclaredIdentifiers.erase(I); 7239 } else 7240 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7241 << /*Variable*/1 << NewVD; 7242 } 7243 } 7244 7245 // Find the shadowed declaration before filtering for scope. 7246 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7247 ? getShadowedDeclaration(NewVD, Previous) 7248 : nullptr; 7249 7250 // Don't consider existing declarations that are in a different 7251 // scope and are out-of-semantic-context declarations (if the new 7252 // declaration has linkage). 7253 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7254 D.getCXXScopeSpec().isNotEmpty() || 7255 IsMemberSpecialization || 7256 IsVariableTemplateSpecialization); 7257 7258 // Check whether the previous declaration is in the same block scope. This 7259 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7260 if (getLangOpts().CPlusPlus && 7261 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7262 NewVD->setPreviousDeclInSameBlockScope( 7263 Previous.isSingleResult() && !Previous.isShadowed() && 7264 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7265 7266 if (!getLangOpts().CPlusPlus) { 7267 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7268 } else { 7269 // If this is an explicit specialization of a static data member, check it. 7270 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7271 CheckMemberSpecialization(NewVD, Previous)) 7272 NewVD->setInvalidDecl(); 7273 7274 // Merge the decl with the existing one if appropriate. 7275 if (!Previous.empty()) { 7276 if (Previous.isSingleResult() && 7277 isa<FieldDecl>(Previous.getFoundDecl()) && 7278 D.getCXXScopeSpec().isSet()) { 7279 // The user tried to define a non-static data member 7280 // out-of-line (C++ [dcl.meaning]p1). 7281 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7282 << D.getCXXScopeSpec().getRange(); 7283 Previous.clear(); 7284 NewVD->setInvalidDecl(); 7285 } 7286 } else if (D.getCXXScopeSpec().isSet()) { 7287 // No previous declaration in the qualifying scope. 7288 Diag(D.getIdentifierLoc(), diag::err_no_member) 7289 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7290 << D.getCXXScopeSpec().getRange(); 7291 NewVD->setInvalidDecl(); 7292 } 7293 7294 if (!IsVariableTemplateSpecialization) 7295 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7296 7297 if (NewTemplate) { 7298 VarTemplateDecl *PrevVarTemplate = 7299 NewVD->getPreviousDecl() 7300 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7301 : nullptr; 7302 7303 // Check the template parameter list of this declaration, possibly 7304 // merging in the template parameter list from the previous variable 7305 // template declaration. 7306 if (CheckTemplateParameterList( 7307 TemplateParams, 7308 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7309 : nullptr, 7310 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7311 DC->isDependentContext()) 7312 ? TPC_ClassTemplateMember 7313 : TPC_VarTemplate)) 7314 NewVD->setInvalidDecl(); 7315 7316 // If we are providing an explicit specialization of a static variable 7317 // template, make a note of that. 7318 if (PrevVarTemplate && 7319 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7320 PrevVarTemplate->setMemberSpecialization(); 7321 } 7322 } 7323 7324 // Diagnose shadowed variables iff this isn't a redeclaration. 7325 if (ShadowedDecl && !D.isRedeclaration()) 7326 CheckShadow(NewVD, ShadowedDecl, Previous); 7327 7328 ProcessPragmaWeak(S, NewVD); 7329 7330 // If this is the first declaration of an extern C variable, update 7331 // the map of such variables. 7332 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7333 isIncompleteDeclExternC(*this, NewVD)) 7334 RegisterLocallyScopedExternCDecl(NewVD, S); 7335 7336 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7337 MangleNumberingContext *MCtx; 7338 Decl *ManglingContextDecl; 7339 std::tie(MCtx, ManglingContextDecl) = 7340 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7341 if (MCtx) { 7342 Context.setManglingNumber( 7343 NewVD, MCtx->getManglingNumber( 7344 NewVD, getMSManglingNumber(getLangOpts(), S))); 7345 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7346 } 7347 } 7348 7349 // Special handling of variable named 'main'. 7350 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7351 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7352 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7353 7354 // C++ [basic.start.main]p3 7355 // A program that declares a variable main at global scope is ill-formed. 7356 if (getLangOpts().CPlusPlus) 7357 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7358 7359 // In C, and external-linkage variable named main results in undefined 7360 // behavior. 7361 else if (NewVD->hasExternalFormalLinkage()) 7362 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7363 } 7364 7365 if (D.isRedeclaration() && !Previous.empty()) { 7366 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7367 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7368 D.isFunctionDefinition()); 7369 } 7370 7371 if (NewTemplate) { 7372 if (NewVD->isInvalidDecl()) 7373 NewTemplate->setInvalidDecl(); 7374 ActOnDocumentableDecl(NewTemplate); 7375 return NewTemplate; 7376 } 7377 7378 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7379 CompleteMemberSpecialization(NewVD, Previous); 7380 7381 return NewVD; 7382 } 7383 7384 /// Enum describing the %select options in diag::warn_decl_shadow. 7385 enum ShadowedDeclKind { 7386 SDK_Local, 7387 SDK_Global, 7388 SDK_StaticMember, 7389 SDK_Field, 7390 SDK_Typedef, 7391 SDK_Using 7392 }; 7393 7394 /// Determine what kind of declaration we're shadowing. 7395 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7396 const DeclContext *OldDC) { 7397 if (isa<TypeAliasDecl>(ShadowedDecl)) 7398 return SDK_Using; 7399 else if (isa<TypedefDecl>(ShadowedDecl)) 7400 return SDK_Typedef; 7401 else if (isa<RecordDecl>(OldDC)) 7402 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7403 7404 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7405 } 7406 7407 /// Return the location of the capture if the given lambda captures the given 7408 /// variable \p VD, or an invalid source location otherwise. 7409 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7410 const VarDecl *VD) { 7411 for (const Capture &Capture : LSI->Captures) { 7412 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7413 return Capture.getLocation(); 7414 } 7415 return SourceLocation(); 7416 } 7417 7418 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7419 const LookupResult &R) { 7420 // Only diagnose if we're shadowing an unambiguous field or variable. 7421 if (R.getResultKind() != LookupResult::Found) 7422 return false; 7423 7424 // Return false if warning is ignored. 7425 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7426 } 7427 7428 /// Return the declaration shadowed by the given variable \p D, or null 7429 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7430 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7431 const LookupResult &R) { 7432 if (!shouldWarnIfShadowedDecl(Diags, R)) 7433 return nullptr; 7434 7435 // Don't diagnose declarations at file scope. 7436 if (D->hasGlobalStorage()) 7437 return nullptr; 7438 7439 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7440 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7441 ? ShadowedDecl 7442 : nullptr; 7443 } 7444 7445 /// Return the declaration shadowed by the given typedef \p D, or null 7446 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7447 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7448 const LookupResult &R) { 7449 // Don't warn if typedef declaration is part of a class 7450 if (D->getDeclContext()->isRecord()) 7451 return nullptr; 7452 7453 if (!shouldWarnIfShadowedDecl(Diags, R)) 7454 return nullptr; 7455 7456 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7457 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7458 } 7459 7460 /// Diagnose variable or built-in function shadowing. Implements 7461 /// -Wshadow. 7462 /// 7463 /// This method is called whenever a VarDecl is added to a "useful" 7464 /// scope. 7465 /// 7466 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7467 /// \param R the lookup of the name 7468 /// 7469 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7470 const LookupResult &R) { 7471 DeclContext *NewDC = D->getDeclContext(); 7472 7473 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7474 // Fields are not shadowed by variables in C++ static methods. 7475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7476 if (MD->isStatic()) 7477 return; 7478 7479 // Fields shadowed by constructor parameters are a special case. Usually 7480 // the constructor initializes the field with the parameter. 7481 if (isa<CXXConstructorDecl>(NewDC)) 7482 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7483 // Remember that this was shadowed so we can either warn about its 7484 // modification or its existence depending on warning settings. 7485 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7486 return; 7487 } 7488 } 7489 7490 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7491 if (shadowedVar->isExternC()) { 7492 // For shadowing external vars, make sure that we point to the global 7493 // declaration, not a locally scoped extern declaration. 7494 for (auto I : shadowedVar->redecls()) 7495 if (I->isFileVarDecl()) { 7496 ShadowedDecl = I; 7497 break; 7498 } 7499 } 7500 7501 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7502 7503 unsigned WarningDiag = diag::warn_decl_shadow; 7504 SourceLocation CaptureLoc; 7505 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7506 isa<CXXMethodDecl>(NewDC)) { 7507 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7508 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7509 if (RD->getLambdaCaptureDefault() == LCD_None) { 7510 // Try to avoid warnings for lambdas with an explicit capture list. 7511 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7512 // Warn only when the lambda captures the shadowed decl explicitly. 7513 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7514 if (CaptureLoc.isInvalid()) 7515 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7516 } else { 7517 // Remember that this was shadowed so we can avoid the warning if the 7518 // shadowed decl isn't captured and the warning settings allow it. 7519 cast<LambdaScopeInfo>(getCurFunction()) 7520 ->ShadowingDecls.push_back( 7521 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7522 return; 7523 } 7524 } 7525 7526 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7527 // A variable can't shadow a local variable in an enclosing scope, if 7528 // they are separated by a non-capturing declaration context. 7529 for (DeclContext *ParentDC = NewDC; 7530 ParentDC && !ParentDC->Equals(OldDC); 7531 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7532 // Only block literals, captured statements, and lambda expressions 7533 // can capture; other scopes don't. 7534 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7535 !isLambdaCallOperator(ParentDC)) { 7536 return; 7537 } 7538 } 7539 } 7540 } 7541 } 7542 7543 // Only warn about certain kinds of shadowing for class members. 7544 if (NewDC && NewDC->isRecord()) { 7545 // In particular, don't warn about shadowing non-class members. 7546 if (!OldDC->isRecord()) 7547 return; 7548 7549 // TODO: should we warn about static data members shadowing 7550 // static data members from base classes? 7551 7552 // TODO: don't diagnose for inaccessible shadowed members. 7553 // This is hard to do perfectly because we might friend the 7554 // shadowing context, but that's just a false negative. 7555 } 7556 7557 7558 DeclarationName Name = R.getLookupName(); 7559 7560 // Emit warning and note. 7561 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7562 return; 7563 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7564 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7565 if (!CaptureLoc.isInvalid()) 7566 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7567 << Name << /*explicitly*/ 1; 7568 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7569 } 7570 7571 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7572 /// when these variables are captured by the lambda. 7573 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7574 for (const auto &Shadow : LSI->ShadowingDecls) { 7575 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7576 // Try to avoid the warning when the shadowed decl isn't captured. 7577 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7578 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7579 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7580 ? diag::warn_decl_shadow_uncaptured_local 7581 : diag::warn_decl_shadow) 7582 << Shadow.VD->getDeclName() 7583 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7584 if (!CaptureLoc.isInvalid()) 7585 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7586 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7587 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7588 } 7589 } 7590 7591 /// Check -Wshadow without the advantage of a previous lookup. 7592 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7593 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7594 return; 7595 7596 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7597 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7598 LookupName(R, S); 7599 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7600 CheckShadow(D, ShadowedDecl, R); 7601 } 7602 7603 /// Check if 'E', which is an expression that is about to be modified, refers 7604 /// to a constructor parameter that shadows a field. 7605 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7606 // Quickly ignore expressions that can't be shadowing ctor parameters. 7607 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7608 return; 7609 E = E->IgnoreParenImpCasts(); 7610 auto *DRE = dyn_cast<DeclRefExpr>(E); 7611 if (!DRE) 7612 return; 7613 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7614 auto I = ShadowingDecls.find(D); 7615 if (I == ShadowingDecls.end()) 7616 return; 7617 const NamedDecl *ShadowedDecl = I->second; 7618 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7619 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7620 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7621 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7622 7623 // Avoid issuing multiple warnings about the same decl. 7624 ShadowingDecls.erase(I); 7625 } 7626 7627 /// Check for conflict between this global or extern "C" declaration and 7628 /// previous global or extern "C" declarations. This is only used in C++. 7629 template<typename T> 7630 static bool checkGlobalOrExternCConflict( 7631 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7632 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7633 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7634 7635 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7636 // The common case: this global doesn't conflict with any extern "C" 7637 // declaration. 7638 return false; 7639 } 7640 7641 if (Prev) { 7642 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7643 // Both the old and new declarations have C language linkage. This is a 7644 // redeclaration. 7645 Previous.clear(); 7646 Previous.addDecl(Prev); 7647 return true; 7648 } 7649 7650 // This is a global, non-extern "C" declaration, and there is a previous 7651 // non-global extern "C" declaration. Diagnose if this is a variable 7652 // declaration. 7653 if (!isa<VarDecl>(ND)) 7654 return false; 7655 } else { 7656 // The declaration is extern "C". Check for any declaration in the 7657 // translation unit which might conflict. 7658 if (IsGlobal) { 7659 // We have already performed the lookup into the translation unit. 7660 IsGlobal = false; 7661 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7662 I != E; ++I) { 7663 if (isa<VarDecl>(*I)) { 7664 Prev = *I; 7665 break; 7666 } 7667 } 7668 } else { 7669 DeclContext::lookup_result R = 7670 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7671 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7672 I != E; ++I) { 7673 if (isa<VarDecl>(*I)) { 7674 Prev = *I; 7675 break; 7676 } 7677 // FIXME: If we have any other entity with this name in global scope, 7678 // the declaration is ill-formed, but that is a defect: it breaks the 7679 // 'stat' hack, for instance. Only variables can have mangled name 7680 // clashes with extern "C" declarations, so only they deserve a 7681 // diagnostic. 7682 } 7683 } 7684 7685 if (!Prev) 7686 return false; 7687 } 7688 7689 // Use the first declaration's location to ensure we point at something which 7690 // is lexically inside an extern "C" linkage-spec. 7691 assert(Prev && "should have found a previous declaration to diagnose"); 7692 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7693 Prev = FD->getFirstDecl(); 7694 else 7695 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7696 7697 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7698 << IsGlobal << ND; 7699 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7700 << IsGlobal; 7701 return false; 7702 } 7703 7704 /// Apply special rules for handling extern "C" declarations. Returns \c true 7705 /// if we have found that this is a redeclaration of some prior entity. 7706 /// 7707 /// Per C++ [dcl.link]p6: 7708 /// Two declarations [for a function or variable] with C language linkage 7709 /// with the same name that appear in different scopes refer to the same 7710 /// [entity]. An entity with C language linkage shall not be declared with 7711 /// the same name as an entity in global scope. 7712 template<typename T> 7713 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7714 LookupResult &Previous) { 7715 if (!S.getLangOpts().CPlusPlus) { 7716 // In C, when declaring a global variable, look for a corresponding 'extern' 7717 // variable declared in function scope. We don't need this in C++, because 7718 // we find local extern decls in the surrounding file-scope DeclContext. 7719 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7720 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7721 Previous.clear(); 7722 Previous.addDecl(Prev); 7723 return true; 7724 } 7725 } 7726 return false; 7727 } 7728 7729 // A declaration in the translation unit can conflict with an extern "C" 7730 // declaration. 7731 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7732 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7733 7734 // An extern "C" declaration can conflict with a declaration in the 7735 // translation unit or can be a redeclaration of an extern "C" declaration 7736 // in another scope. 7737 if (isIncompleteDeclExternC(S,ND)) 7738 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7739 7740 // Neither global nor extern "C": nothing to do. 7741 return false; 7742 } 7743 7744 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7745 // If the decl is already known invalid, don't check it. 7746 if (NewVD->isInvalidDecl()) 7747 return; 7748 7749 QualType T = NewVD->getType(); 7750 7751 // Defer checking an 'auto' type until its initializer is attached. 7752 if (T->isUndeducedType()) 7753 return; 7754 7755 if (NewVD->hasAttrs()) 7756 CheckAlignasUnderalignment(NewVD); 7757 7758 if (T->isObjCObjectType()) { 7759 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7760 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7761 T = Context.getObjCObjectPointerType(T); 7762 NewVD->setType(T); 7763 } 7764 7765 // Emit an error if an address space was applied to decl with local storage. 7766 // This includes arrays of objects with address space qualifiers, but not 7767 // automatic variables that point to other address spaces. 7768 // ISO/IEC TR 18037 S5.1.2 7769 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7770 T.getAddressSpace() != LangAS::Default) { 7771 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7772 NewVD->setInvalidDecl(); 7773 return; 7774 } 7775 7776 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7777 // scope. 7778 if (getLangOpts().OpenCLVersion == 120 && 7779 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7780 NewVD->isStaticLocal()) { 7781 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7782 NewVD->setInvalidDecl(); 7783 return; 7784 } 7785 7786 if (getLangOpts().OpenCL) { 7787 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7788 if (NewVD->hasAttr<BlocksAttr>()) { 7789 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7790 return; 7791 } 7792 7793 if (T->isBlockPointerType()) { 7794 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7795 // can't use 'extern' storage class. 7796 if (!T.isConstQualified()) { 7797 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7798 << 0 /*const*/; 7799 NewVD->setInvalidDecl(); 7800 return; 7801 } 7802 if (NewVD->hasExternalStorage()) { 7803 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7804 NewVD->setInvalidDecl(); 7805 return; 7806 } 7807 } 7808 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7809 // __constant address space. 7810 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7811 // variables inside a function can also be declared in the global 7812 // address space. 7813 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7814 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7815 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7816 NewVD->hasExternalStorage()) { 7817 if (!T->isSamplerT() && 7818 !(T.getAddressSpace() == LangAS::opencl_constant || 7819 (T.getAddressSpace() == LangAS::opencl_global && 7820 (getLangOpts().OpenCLVersion == 200 || 7821 getLangOpts().OpenCLCPlusPlus)))) { 7822 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7823 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7824 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7825 << Scope << "global or constant"; 7826 else 7827 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7828 << Scope << "constant"; 7829 NewVD->setInvalidDecl(); 7830 return; 7831 } 7832 } else { 7833 if (T.getAddressSpace() == LangAS::opencl_global) { 7834 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7835 << 1 /*is any function*/ << "global"; 7836 NewVD->setInvalidDecl(); 7837 return; 7838 } 7839 if (T.getAddressSpace() == LangAS::opencl_constant || 7840 T.getAddressSpace() == LangAS::opencl_local) { 7841 FunctionDecl *FD = getCurFunctionDecl(); 7842 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7843 // in functions. 7844 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7845 if (T.getAddressSpace() == LangAS::opencl_constant) 7846 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7847 << 0 /*non-kernel only*/ << "constant"; 7848 else 7849 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7850 << 0 /*non-kernel only*/ << "local"; 7851 NewVD->setInvalidDecl(); 7852 return; 7853 } 7854 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7855 // in the outermost scope of a kernel function. 7856 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7857 if (!getCurScope()->isFunctionScope()) { 7858 if (T.getAddressSpace() == LangAS::opencl_constant) 7859 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7860 << "constant"; 7861 else 7862 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7863 << "local"; 7864 NewVD->setInvalidDecl(); 7865 return; 7866 } 7867 } 7868 } else if (T.getAddressSpace() != LangAS::opencl_private && 7869 // If we are parsing a template we didn't deduce an addr 7870 // space yet. 7871 T.getAddressSpace() != LangAS::Default) { 7872 // Do not allow other address spaces on automatic variable. 7873 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7874 NewVD->setInvalidDecl(); 7875 return; 7876 } 7877 } 7878 } 7879 7880 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7881 && !NewVD->hasAttr<BlocksAttr>()) { 7882 if (getLangOpts().getGC() != LangOptions::NonGC) 7883 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7884 else { 7885 assert(!getLangOpts().ObjCAutoRefCount); 7886 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7887 } 7888 } 7889 7890 bool isVM = T->isVariablyModifiedType(); 7891 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7892 NewVD->hasAttr<BlocksAttr>()) 7893 setFunctionHasBranchProtectedScope(); 7894 7895 if ((isVM && NewVD->hasLinkage()) || 7896 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7897 bool SizeIsNegative; 7898 llvm::APSInt Oversized; 7899 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7900 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7901 QualType FixedT; 7902 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7903 FixedT = FixedTInfo->getType(); 7904 else if (FixedTInfo) { 7905 // Type and type-as-written are canonically different. We need to fix up 7906 // both types separately. 7907 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7908 Oversized); 7909 } 7910 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7911 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7912 // FIXME: This won't give the correct result for 7913 // int a[10][n]; 7914 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7915 7916 if (NewVD->isFileVarDecl()) 7917 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7918 << SizeRange; 7919 else if (NewVD->isStaticLocal()) 7920 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7921 << SizeRange; 7922 else 7923 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7924 << SizeRange; 7925 NewVD->setInvalidDecl(); 7926 return; 7927 } 7928 7929 if (!FixedTInfo) { 7930 if (NewVD->isFileVarDecl()) 7931 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7932 else 7933 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7934 NewVD->setInvalidDecl(); 7935 return; 7936 } 7937 7938 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7939 NewVD->setType(FixedT); 7940 NewVD->setTypeSourceInfo(FixedTInfo); 7941 } 7942 7943 if (T->isVoidType()) { 7944 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7945 // of objects and functions. 7946 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7947 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7948 << T; 7949 NewVD->setInvalidDecl(); 7950 return; 7951 } 7952 } 7953 7954 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7955 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7956 NewVD->setInvalidDecl(); 7957 return; 7958 } 7959 7960 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 7961 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 7962 NewVD->setInvalidDecl(); 7963 return; 7964 } 7965 7966 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7967 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7968 NewVD->setInvalidDecl(); 7969 return; 7970 } 7971 7972 if (NewVD->isConstexpr() && !T->isDependentType() && 7973 RequireLiteralType(NewVD->getLocation(), T, 7974 diag::err_constexpr_var_non_literal)) { 7975 NewVD->setInvalidDecl(); 7976 return; 7977 } 7978 } 7979 7980 /// Perform semantic checking on a newly-created variable 7981 /// declaration. 7982 /// 7983 /// This routine performs all of the type-checking required for a 7984 /// variable declaration once it has been built. It is used both to 7985 /// check variables after they have been parsed and their declarators 7986 /// have been translated into a declaration, and to check variables 7987 /// that have been instantiated from a template. 7988 /// 7989 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7990 /// 7991 /// Returns true if the variable declaration is a redeclaration. 7992 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7993 CheckVariableDeclarationType(NewVD); 7994 7995 // If the decl is already known invalid, don't check it. 7996 if (NewVD->isInvalidDecl()) 7997 return false; 7998 7999 // If we did not find anything by this name, look for a non-visible 8000 // extern "C" declaration with the same name. 8001 if (Previous.empty() && 8002 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8003 Previous.setShadowed(); 8004 8005 if (!Previous.empty()) { 8006 MergeVarDecl(NewVD, Previous); 8007 return true; 8008 } 8009 return false; 8010 } 8011 8012 namespace { 8013 struct FindOverriddenMethod { 8014 Sema *S; 8015 CXXMethodDecl *Method; 8016 8017 /// Member lookup function that determines whether a given C++ 8018 /// method overrides a method in a base class, to be used with 8019 /// CXXRecordDecl::lookupInBases(). 8020 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8021 RecordDecl *BaseRecord = 8022 Specifier->getType()->castAs<RecordType>()->getDecl(); 8023 8024 DeclarationName Name = Method->getDeclName(); 8025 8026 // FIXME: Do we care about other names here too? 8027 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8028 // We really want to find the base class destructor here. 8029 QualType T = S->Context.getTypeDeclType(BaseRecord); 8030 CanQualType CT = S->Context.getCanonicalType(T); 8031 8032 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8033 } 8034 8035 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8036 Path.Decls = Path.Decls.slice(1)) { 8037 NamedDecl *D = Path.Decls.front(); 8038 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8039 if (MD->isVirtual() && 8040 !S->IsOverload( 8041 Method, MD, /*UseMemberUsingDeclRules=*/false, 8042 /*ConsiderCudaAttrs=*/true, 8043 // C++2a [class.virtual]p2 does not consider requires clauses 8044 // when overriding. 8045 /*ConsiderRequiresClauses=*/false)) 8046 return true; 8047 } 8048 } 8049 8050 return false; 8051 } 8052 }; 8053 } // end anonymous namespace 8054 8055 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8056 /// and if so, check that it's a valid override and remember it. 8057 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8058 // Look for methods in base classes that this method might override. 8059 CXXBasePaths Paths; 8060 FindOverriddenMethod FOM; 8061 FOM.Method = MD; 8062 FOM.S = this; 8063 bool AddedAny = false; 8064 if (DC->lookupInBases(FOM, Paths)) { 8065 for (auto *I : Paths.found_decls()) { 8066 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8067 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8068 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8069 !CheckOverridingFunctionAttributes(MD, OldMD) && 8070 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8071 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8072 AddedAny = true; 8073 } 8074 } 8075 } 8076 } 8077 8078 return AddedAny; 8079 } 8080 8081 namespace { 8082 // Struct for holding all of the extra arguments needed by 8083 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8084 struct ActOnFDArgs { 8085 Scope *S; 8086 Declarator &D; 8087 MultiTemplateParamsArg TemplateParamLists; 8088 bool AddToScope; 8089 }; 8090 } // end anonymous namespace 8091 8092 namespace { 8093 8094 // Callback to only accept typo corrections that have a non-zero edit distance. 8095 // Also only accept corrections that have the same parent decl. 8096 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8097 public: 8098 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8099 CXXRecordDecl *Parent) 8100 : Context(Context), OriginalFD(TypoFD), 8101 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8102 8103 bool ValidateCandidate(const TypoCorrection &candidate) override { 8104 if (candidate.getEditDistance() == 0) 8105 return false; 8106 8107 SmallVector<unsigned, 1> MismatchedParams; 8108 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8109 CDeclEnd = candidate.end(); 8110 CDecl != CDeclEnd; ++CDecl) { 8111 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8112 8113 if (FD && !FD->hasBody() && 8114 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8115 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8116 CXXRecordDecl *Parent = MD->getParent(); 8117 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8118 return true; 8119 } else if (!ExpectedParent) { 8120 return true; 8121 } 8122 } 8123 } 8124 8125 return false; 8126 } 8127 8128 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8129 return std::make_unique<DifferentNameValidatorCCC>(*this); 8130 } 8131 8132 private: 8133 ASTContext &Context; 8134 FunctionDecl *OriginalFD; 8135 CXXRecordDecl *ExpectedParent; 8136 }; 8137 8138 } // end anonymous namespace 8139 8140 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8141 TypoCorrectedFunctionDefinitions.insert(F); 8142 } 8143 8144 /// Generate diagnostics for an invalid function redeclaration. 8145 /// 8146 /// This routine handles generating the diagnostic messages for an invalid 8147 /// function redeclaration, including finding possible similar declarations 8148 /// or performing typo correction if there are no previous declarations with 8149 /// the same name. 8150 /// 8151 /// Returns a NamedDecl iff typo correction was performed and substituting in 8152 /// the new declaration name does not cause new errors. 8153 static NamedDecl *DiagnoseInvalidRedeclaration( 8154 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8155 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8156 DeclarationName Name = NewFD->getDeclName(); 8157 DeclContext *NewDC = NewFD->getDeclContext(); 8158 SmallVector<unsigned, 1> MismatchedParams; 8159 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8160 TypoCorrection Correction; 8161 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8162 unsigned DiagMsg = 8163 IsLocalFriend ? diag::err_no_matching_local_friend : 8164 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8165 diag::err_member_decl_does_not_match; 8166 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8167 IsLocalFriend ? Sema::LookupLocalFriendName 8168 : Sema::LookupOrdinaryName, 8169 Sema::ForVisibleRedeclaration); 8170 8171 NewFD->setInvalidDecl(); 8172 if (IsLocalFriend) 8173 SemaRef.LookupName(Prev, S); 8174 else 8175 SemaRef.LookupQualifiedName(Prev, NewDC); 8176 assert(!Prev.isAmbiguous() && 8177 "Cannot have an ambiguity in previous-declaration lookup"); 8178 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8179 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8180 MD ? MD->getParent() : nullptr); 8181 if (!Prev.empty()) { 8182 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8183 Func != FuncEnd; ++Func) { 8184 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8185 if (FD && 8186 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8187 // Add 1 to the index so that 0 can mean the mismatch didn't 8188 // involve a parameter 8189 unsigned ParamNum = 8190 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8191 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8192 } 8193 } 8194 // If the qualified name lookup yielded nothing, try typo correction 8195 } else if ((Correction = SemaRef.CorrectTypo( 8196 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8197 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8198 IsLocalFriend ? nullptr : NewDC))) { 8199 // Set up everything for the call to ActOnFunctionDeclarator 8200 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8201 ExtraArgs.D.getIdentifierLoc()); 8202 Previous.clear(); 8203 Previous.setLookupName(Correction.getCorrection()); 8204 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8205 CDeclEnd = Correction.end(); 8206 CDecl != CDeclEnd; ++CDecl) { 8207 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8208 if (FD && !FD->hasBody() && 8209 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8210 Previous.addDecl(FD); 8211 } 8212 } 8213 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8214 8215 NamedDecl *Result; 8216 // Retry building the function declaration with the new previous 8217 // declarations, and with errors suppressed. 8218 { 8219 // Trap errors. 8220 Sema::SFINAETrap Trap(SemaRef); 8221 8222 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8223 // pieces need to verify the typo-corrected C++ declaration and hopefully 8224 // eliminate the need for the parameter pack ExtraArgs. 8225 Result = SemaRef.ActOnFunctionDeclarator( 8226 ExtraArgs.S, ExtraArgs.D, 8227 Correction.getCorrectionDecl()->getDeclContext(), 8228 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8229 ExtraArgs.AddToScope); 8230 8231 if (Trap.hasErrorOccurred()) 8232 Result = nullptr; 8233 } 8234 8235 if (Result) { 8236 // Determine which correction we picked. 8237 Decl *Canonical = Result->getCanonicalDecl(); 8238 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8239 I != E; ++I) 8240 if ((*I)->getCanonicalDecl() == Canonical) 8241 Correction.setCorrectionDecl(*I); 8242 8243 // Let Sema know about the correction. 8244 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8245 SemaRef.diagnoseTypo( 8246 Correction, 8247 SemaRef.PDiag(IsLocalFriend 8248 ? diag::err_no_matching_local_friend_suggest 8249 : diag::err_member_decl_does_not_match_suggest) 8250 << Name << NewDC << IsDefinition); 8251 return Result; 8252 } 8253 8254 // Pretend the typo correction never occurred 8255 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8256 ExtraArgs.D.getIdentifierLoc()); 8257 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8258 Previous.clear(); 8259 Previous.setLookupName(Name); 8260 } 8261 8262 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8263 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8264 8265 bool NewFDisConst = false; 8266 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8267 NewFDisConst = NewMD->isConst(); 8268 8269 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8270 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8271 NearMatch != NearMatchEnd; ++NearMatch) { 8272 FunctionDecl *FD = NearMatch->first; 8273 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8274 bool FDisConst = MD && MD->isConst(); 8275 bool IsMember = MD || !IsLocalFriend; 8276 8277 // FIXME: These notes are poorly worded for the local friend case. 8278 if (unsigned Idx = NearMatch->second) { 8279 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8280 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8281 if (Loc.isInvalid()) Loc = FD->getLocation(); 8282 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8283 : diag::note_local_decl_close_param_match) 8284 << Idx << FDParam->getType() 8285 << NewFD->getParamDecl(Idx - 1)->getType(); 8286 } else if (FDisConst != NewFDisConst) { 8287 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8288 << NewFDisConst << FD->getSourceRange().getEnd(); 8289 } else 8290 SemaRef.Diag(FD->getLocation(), 8291 IsMember ? diag::note_member_def_close_match 8292 : diag::note_local_decl_close_match); 8293 } 8294 return nullptr; 8295 } 8296 8297 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8298 switch (D.getDeclSpec().getStorageClassSpec()) { 8299 default: llvm_unreachable("Unknown storage class!"); 8300 case DeclSpec::SCS_auto: 8301 case DeclSpec::SCS_register: 8302 case DeclSpec::SCS_mutable: 8303 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8304 diag::err_typecheck_sclass_func); 8305 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8306 D.setInvalidType(); 8307 break; 8308 case DeclSpec::SCS_unspecified: break; 8309 case DeclSpec::SCS_extern: 8310 if (D.getDeclSpec().isExternInLinkageSpec()) 8311 return SC_None; 8312 return SC_Extern; 8313 case DeclSpec::SCS_static: { 8314 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8315 // C99 6.7.1p5: 8316 // The declaration of an identifier for a function that has 8317 // block scope shall have no explicit storage-class specifier 8318 // other than extern 8319 // See also (C++ [dcl.stc]p4). 8320 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8321 diag::err_static_block_func); 8322 break; 8323 } else 8324 return SC_Static; 8325 } 8326 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8327 } 8328 8329 // No explicit storage class has already been returned 8330 return SC_None; 8331 } 8332 8333 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8334 DeclContext *DC, QualType &R, 8335 TypeSourceInfo *TInfo, 8336 StorageClass SC, 8337 bool &IsVirtualOkay) { 8338 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8339 DeclarationName Name = NameInfo.getName(); 8340 8341 FunctionDecl *NewFD = nullptr; 8342 bool isInline = D.getDeclSpec().isInlineSpecified(); 8343 8344 if (!SemaRef.getLangOpts().CPlusPlus) { 8345 // Determine whether the function was written with a 8346 // prototype. This true when: 8347 // - there is a prototype in the declarator, or 8348 // - the type R of the function is some kind of typedef or other non- 8349 // attributed reference to a type name (which eventually refers to a 8350 // function type). 8351 bool HasPrototype = 8352 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8353 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8354 8355 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8356 R, TInfo, SC, isInline, HasPrototype, 8357 CSK_unspecified, 8358 /*TrailingRequiresClause=*/nullptr); 8359 if (D.isInvalidType()) 8360 NewFD->setInvalidDecl(); 8361 8362 return NewFD; 8363 } 8364 8365 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8366 8367 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8368 if (ConstexprKind == CSK_constinit) { 8369 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8370 diag::err_constexpr_wrong_decl_kind) 8371 << ConstexprKind; 8372 ConstexprKind = CSK_unspecified; 8373 D.getMutableDeclSpec().ClearConstexprSpec(); 8374 } 8375 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8376 8377 // Check that the return type is not an abstract class type. 8378 // For record types, this is done by the AbstractClassUsageDiagnoser once 8379 // the class has been completely parsed. 8380 if (!DC->isRecord() && 8381 SemaRef.RequireNonAbstractType( 8382 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8383 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8384 D.setInvalidType(); 8385 8386 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8387 // This is a C++ constructor declaration. 8388 assert(DC->isRecord() && 8389 "Constructors can only be declared in a member context"); 8390 8391 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8392 return CXXConstructorDecl::Create( 8393 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8394 TInfo, ExplicitSpecifier, isInline, 8395 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8396 TrailingRequiresClause); 8397 8398 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8399 // This is a C++ destructor declaration. 8400 if (DC->isRecord()) { 8401 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8402 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8403 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8404 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8405 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8406 TrailingRequiresClause); 8407 8408 // If the destructor needs an implicit exception specification, set it 8409 // now. FIXME: It'd be nice to be able to create the right type to start 8410 // with, but the type needs to reference the destructor declaration. 8411 if (SemaRef.getLangOpts().CPlusPlus11) 8412 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8413 8414 IsVirtualOkay = true; 8415 return NewDD; 8416 8417 } else { 8418 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8419 D.setInvalidType(); 8420 8421 // Create a FunctionDecl to satisfy the function definition parsing 8422 // code path. 8423 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8424 D.getIdentifierLoc(), Name, R, TInfo, SC, 8425 isInline, 8426 /*hasPrototype=*/true, ConstexprKind, 8427 TrailingRequiresClause); 8428 } 8429 8430 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8431 if (!DC->isRecord()) { 8432 SemaRef.Diag(D.getIdentifierLoc(), 8433 diag::err_conv_function_not_member); 8434 return nullptr; 8435 } 8436 8437 SemaRef.CheckConversionDeclarator(D, R, SC); 8438 if (D.isInvalidType()) 8439 return nullptr; 8440 8441 IsVirtualOkay = true; 8442 return CXXConversionDecl::Create( 8443 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8444 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8445 TrailingRequiresClause); 8446 8447 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8448 if (TrailingRequiresClause) 8449 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8450 diag::err_trailing_requires_clause_on_deduction_guide) 8451 << TrailingRequiresClause->getSourceRange(); 8452 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8453 8454 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8455 ExplicitSpecifier, NameInfo, R, TInfo, 8456 D.getEndLoc()); 8457 } else if (DC->isRecord()) { 8458 // If the name of the function is the same as the name of the record, 8459 // then this must be an invalid constructor that has a return type. 8460 // (The parser checks for a return type and makes the declarator a 8461 // constructor if it has no return type). 8462 if (Name.getAsIdentifierInfo() && 8463 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8464 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8465 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8466 << SourceRange(D.getIdentifierLoc()); 8467 return nullptr; 8468 } 8469 8470 // This is a C++ method declaration. 8471 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8472 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8473 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8474 TrailingRequiresClause); 8475 IsVirtualOkay = !Ret->isStatic(); 8476 return Ret; 8477 } else { 8478 bool isFriend = 8479 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8480 if (!isFriend && SemaRef.CurContext->isRecord()) 8481 return nullptr; 8482 8483 // Determine whether the function was written with a 8484 // prototype. This true when: 8485 // - we're in C++ (where every function has a prototype), 8486 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8487 R, TInfo, SC, isInline, true /*HasPrototype*/, 8488 ConstexprKind, TrailingRequiresClause); 8489 } 8490 } 8491 8492 enum OpenCLParamType { 8493 ValidKernelParam, 8494 PtrPtrKernelParam, 8495 PtrKernelParam, 8496 InvalidAddrSpacePtrKernelParam, 8497 InvalidKernelParam, 8498 RecordKernelParam 8499 }; 8500 8501 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8502 // Size dependent types are just typedefs to normal integer types 8503 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8504 // integers other than by their names. 8505 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8506 8507 // Remove typedefs one by one until we reach a typedef 8508 // for a size dependent type. 8509 QualType DesugaredTy = Ty; 8510 do { 8511 ArrayRef<StringRef> Names(SizeTypeNames); 8512 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8513 if (Names.end() != Match) 8514 return true; 8515 8516 Ty = DesugaredTy; 8517 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8518 } while (DesugaredTy != Ty); 8519 8520 return false; 8521 } 8522 8523 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8524 if (PT->isPointerType()) { 8525 QualType PointeeType = PT->getPointeeType(); 8526 if (PointeeType->isPointerType()) 8527 return PtrPtrKernelParam; 8528 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8529 PointeeType.getAddressSpace() == LangAS::opencl_private || 8530 PointeeType.getAddressSpace() == LangAS::Default) 8531 return InvalidAddrSpacePtrKernelParam; 8532 return PtrKernelParam; 8533 } 8534 8535 // OpenCL v1.2 s6.9.k: 8536 // Arguments to kernel functions in a program cannot be declared with the 8537 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8538 // uintptr_t or a struct and/or union that contain fields declared to be one 8539 // of these built-in scalar types. 8540 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8541 return InvalidKernelParam; 8542 8543 if (PT->isImageType()) 8544 return PtrKernelParam; 8545 8546 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8547 return InvalidKernelParam; 8548 8549 // OpenCL extension spec v1.2 s9.5: 8550 // This extension adds support for half scalar and vector types as built-in 8551 // types that can be used for arithmetic operations, conversions etc. 8552 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8553 return InvalidKernelParam; 8554 8555 if (PT->isRecordType()) 8556 return RecordKernelParam; 8557 8558 // Look into an array argument to check if it has a forbidden type. 8559 if (PT->isArrayType()) { 8560 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8561 // Call ourself to check an underlying type of an array. Since the 8562 // getPointeeOrArrayElementType returns an innermost type which is not an 8563 // array, this recursive call only happens once. 8564 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8565 } 8566 8567 return ValidKernelParam; 8568 } 8569 8570 static void checkIsValidOpenCLKernelParameter( 8571 Sema &S, 8572 Declarator &D, 8573 ParmVarDecl *Param, 8574 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8575 QualType PT = Param->getType(); 8576 8577 // Cache the valid types we encounter to avoid rechecking structs that are 8578 // used again 8579 if (ValidTypes.count(PT.getTypePtr())) 8580 return; 8581 8582 switch (getOpenCLKernelParameterType(S, PT)) { 8583 case PtrPtrKernelParam: 8584 // OpenCL v1.2 s6.9.a: 8585 // A kernel function argument cannot be declared as a 8586 // pointer to a pointer type. 8587 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8588 D.setInvalidType(); 8589 return; 8590 8591 case InvalidAddrSpacePtrKernelParam: 8592 // OpenCL v1.0 s6.5: 8593 // __kernel function arguments declared to be a pointer of a type can point 8594 // to one of the following address spaces only : __global, __local or 8595 // __constant. 8596 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8597 D.setInvalidType(); 8598 return; 8599 8600 // OpenCL v1.2 s6.9.k: 8601 // Arguments to kernel functions in a program cannot be declared with the 8602 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8603 // uintptr_t or a struct and/or union that contain fields declared to be 8604 // one of these built-in scalar types. 8605 8606 case InvalidKernelParam: 8607 // OpenCL v1.2 s6.8 n: 8608 // A kernel function argument cannot be declared 8609 // of event_t type. 8610 // Do not diagnose half type since it is diagnosed as invalid argument 8611 // type for any function elsewhere. 8612 if (!PT->isHalfType()) { 8613 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8614 8615 // Explain what typedefs are involved. 8616 const TypedefType *Typedef = nullptr; 8617 while ((Typedef = PT->getAs<TypedefType>())) { 8618 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8619 // SourceLocation may be invalid for a built-in type. 8620 if (Loc.isValid()) 8621 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8622 PT = Typedef->desugar(); 8623 } 8624 } 8625 8626 D.setInvalidType(); 8627 return; 8628 8629 case PtrKernelParam: 8630 case ValidKernelParam: 8631 ValidTypes.insert(PT.getTypePtr()); 8632 return; 8633 8634 case RecordKernelParam: 8635 break; 8636 } 8637 8638 // Track nested structs we will inspect 8639 SmallVector<const Decl *, 4> VisitStack; 8640 8641 // Track where we are in the nested structs. Items will migrate from 8642 // VisitStack to HistoryStack as we do the DFS for bad field. 8643 SmallVector<const FieldDecl *, 4> HistoryStack; 8644 HistoryStack.push_back(nullptr); 8645 8646 // At this point we already handled everything except of a RecordType or 8647 // an ArrayType of a RecordType. 8648 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8649 const RecordType *RecTy = 8650 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8651 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8652 8653 VisitStack.push_back(RecTy->getDecl()); 8654 assert(VisitStack.back() && "First decl null?"); 8655 8656 do { 8657 const Decl *Next = VisitStack.pop_back_val(); 8658 if (!Next) { 8659 assert(!HistoryStack.empty()); 8660 // Found a marker, we have gone up a level 8661 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8662 ValidTypes.insert(Hist->getType().getTypePtr()); 8663 8664 continue; 8665 } 8666 8667 // Adds everything except the original parameter declaration (which is not a 8668 // field itself) to the history stack. 8669 const RecordDecl *RD; 8670 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8671 HistoryStack.push_back(Field); 8672 8673 QualType FieldTy = Field->getType(); 8674 // Other field types (known to be valid or invalid) are handled while we 8675 // walk around RecordDecl::fields(). 8676 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8677 "Unexpected type."); 8678 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8679 8680 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8681 } else { 8682 RD = cast<RecordDecl>(Next); 8683 } 8684 8685 // Add a null marker so we know when we've gone back up a level 8686 VisitStack.push_back(nullptr); 8687 8688 for (const auto *FD : RD->fields()) { 8689 QualType QT = FD->getType(); 8690 8691 if (ValidTypes.count(QT.getTypePtr())) 8692 continue; 8693 8694 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8695 if (ParamType == ValidKernelParam) 8696 continue; 8697 8698 if (ParamType == RecordKernelParam) { 8699 VisitStack.push_back(FD); 8700 continue; 8701 } 8702 8703 // OpenCL v1.2 s6.9.p: 8704 // Arguments to kernel functions that are declared to be a struct or union 8705 // do not allow OpenCL objects to be passed as elements of the struct or 8706 // union. 8707 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8708 ParamType == InvalidAddrSpacePtrKernelParam) { 8709 S.Diag(Param->getLocation(), 8710 diag::err_record_with_pointers_kernel_param) 8711 << PT->isUnionType() 8712 << PT; 8713 } else { 8714 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8715 } 8716 8717 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8718 << OrigRecDecl->getDeclName(); 8719 8720 // We have an error, now let's go back up through history and show where 8721 // the offending field came from 8722 for (ArrayRef<const FieldDecl *>::const_iterator 8723 I = HistoryStack.begin() + 1, 8724 E = HistoryStack.end(); 8725 I != E; ++I) { 8726 const FieldDecl *OuterField = *I; 8727 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8728 << OuterField->getType(); 8729 } 8730 8731 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8732 << QT->isPointerType() 8733 << QT; 8734 D.setInvalidType(); 8735 return; 8736 } 8737 } while (!VisitStack.empty()); 8738 } 8739 8740 /// Find the DeclContext in which a tag is implicitly declared if we see an 8741 /// elaborated type specifier in the specified context, and lookup finds 8742 /// nothing. 8743 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8744 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8745 DC = DC->getParent(); 8746 return DC; 8747 } 8748 8749 /// Find the Scope in which a tag is implicitly declared if we see an 8750 /// elaborated type specifier in the specified context, and lookup finds 8751 /// nothing. 8752 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8753 while (S->isClassScope() || 8754 (LangOpts.CPlusPlus && 8755 S->isFunctionPrototypeScope()) || 8756 ((S->getFlags() & Scope::DeclScope) == 0) || 8757 (S->getEntity() && S->getEntity()->isTransparentContext())) 8758 S = S->getParent(); 8759 return S; 8760 } 8761 8762 NamedDecl* 8763 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8764 TypeSourceInfo *TInfo, LookupResult &Previous, 8765 MultiTemplateParamsArg TemplateParamListsRef, 8766 bool &AddToScope) { 8767 QualType R = TInfo->getType(); 8768 8769 assert(R->isFunctionType()); 8770 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8771 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8772 8773 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8774 for (TemplateParameterList *TPL : TemplateParamListsRef) 8775 TemplateParamLists.push_back(TPL); 8776 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8777 if (!TemplateParamLists.empty() && 8778 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8779 TemplateParamLists.back() = Invented; 8780 else 8781 TemplateParamLists.push_back(Invented); 8782 } 8783 8784 // TODO: consider using NameInfo for diagnostic. 8785 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8786 DeclarationName Name = NameInfo.getName(); 8787 StorageClass SC = getFunctionStorageClass(*this, D); 8788 8789 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8790 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8791 diag::err_invalid_thread) 8792 << DeclSpec::getSpecifierName(TSCS); 8793 8794 if (D.isFirstDeclarationOfMember()) 8795 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8796 D.getIdentifierLoc()); 8797 8798 bool isFriend = false; 8799 FunctionTemplateDecl *FunctionTemplate = nullptr; 8800 bool isMemberSpecialization = false; 8801 bool isFunctionTemplateSpecialization = false; 8802 8803 bool isDependentClassScopeExplicitSpecialization = false; 8804 bool HasExplicitTemplateArgs = false; 8805 TemplateArgumentListInfo TemplateArgs; 8806 8807 bool isVirtualOkay = false; 8808 8809 DeclContext *OriginalDC = DC; 8810 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8811 8812 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8813 isVirtualOkay); 8814 if (!NewFD) return nullptr; 8815 8816 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8817 NewFD->setTopLevelDeclInObjCContainer(); 8818 8819 // Set the lexical context. If this is a function-scope declaration, or has a 8820 // C++ scope specifier, or is the object of a friend declaration, the lexical 8821 // context will be different from the semantic context. 8822 NewFD->setLexicalDeclContext(CurContext); 8823 8824 if (IsLocalExternDecl) 8825 NewFD->setLocalExternDecl(); 8826 8827 if (getLangOpts().CPlusPlus) { 8828 bool isInline = D.getDeclSpec().isInlineSpecified(); 8829 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8830 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8831 isFriend = D.getDeclSpec().isFriendSpecified(); 8832 if (isFriend && !isInline && D.isFunctionDefinition()) { 8833 // C++ [class.friend]p5 8834 // A function can be defined in a friend declaration of a 8835 // class . . . . Such a function is implicitly inline. 8836 NewFD->setImplicitlyInline(); 8837 } 8838 8839 // If this is a method defined in an __interface, and is not a constructor 8840 // or an overloaded operator, then set the pure flag (isVirtual will already 8841 // return true). 8842 if (const CXXRecordDecl *Parent = 8843 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8844 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8845 NewFD->setPure(true); 8846 8847 // C++ [class.union]p2 8848 // A union can have member functions, but not virtual functions. 8849 if (isVirtual && Parent->isUnion()) 8850 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8851 } 8852 8853 SetNestedNameSpecifier(*this, NewFD, D); 8854 isMemberSpecialization = false; 8855 isFunctionTemplateSpecialization = false; 8856 if (D.isInvalidType()) 8857 NewFD->setInvalidDecl(); 8858 8859 // Match up the template parameter lists with the scope specifier, then 8860 // determine whether we have a template or a template specialization. 8861 bool Invalid = false; 8862 TemplateParameterList *TemplateParams = 8863 MatchTemplateParametersToScopeSpecifier( 8864 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8865 D.getCXXScopeSpec(), 8866 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8867 ? D.getName().TemplateId 8868 : nullptr, 8869 TemplateParamLists, isFriend, isMemberSpecialization, 8870 Invalid); 8871 if (TemplateParams) { 8872 if (TemplateParams->size() > 0) { 8873 // This is a function template 8874 8875 // Check that we can declare a template here. 8876 if (CheckTemplateDeclScope(S, TemplateParams)) 8877 NewFD->setInvalidDecl(); 8878 8879 // A destructor cannot be a template. 8880 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8881 Diag(NewFD->getLocation(), diag::err_destructor_template); 8882 NewFD->setInvalidDecl(); 8883 } 8884 8885 // If we're adding a template to a dependent context, we may need to 8886 // rebuilding some of the types used within the template parameter list, 8887 // now that we know what the current instantiation is. 8888 if (DC->isDependentContext()) { 8889 ContextRAII SavedContext(*this, DC); 8890 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8891 Invalid = true; 8892 } 8893 8894 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8895 NewFD->getLocation(), 8896 Name, TemplateParams, 8897 NewFD); 8898 FunctionTemplate->setLexicalDeclContext(CurContext); 8899 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8900 8901 // For source fidelity, store the other template param lists. 8902 if (TemplateParamLists.size() > 1) { 8903 NewFD->setTemplateParameterListsInfo(Context, 8904 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8905 .drop_back(1)); 8906 } 8907 } else { 8908 // This is a function template specialization. 8909 isFunctionTemplateSpecialization = true; 8910 // For source fidelity, store all the template param lists. 8911 if (TemplateParamLists.size() > 0) 8912 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8913 8914 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8915 if (isFriend) { 8916 // We want to remove the "template<>", found here. 8917 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8918 8919 // If we remove the template<> and the name is not a 8920 // template-id, we're actually silently creating a problem: 8921 // the friend declaration will refer to an untemplated decl, 8922 // and clearly the user wants a template specialization. So 8923 // we need to insert '<>' after the name. 8924 SourceLocation InsertLoc; 8925 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8926 InsertLoc = D.getName().getSourceRange().getEnd(); 8927 InsertLoc = getLocForEndOfToken(InsertLoc); 8928 } 8929 8930 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8931 << Name << RemoveRange 8932 << FixItHint::CreateRemoval(RemoveRange) 8933 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8934 } 8935 } 8936 } else { 8937 // All template param lists were matched against the scope specifier: 8938 // this is NOT (an explicit specialization of) a template. 8939 if (TemplateParamLists.size() > 0) 8940 // For source fidelity, store all the template param lists. 8941 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8942 } 8943 8944 if (Invalid) { 8945 NewFD->setInvalidDecl(); 8946 if (FunctionTemplate) 8947 FunctionTemplate->setInvalidDecl(); 8948 } 8949 8950 // C++ [dcl.fct.spec]p5: 8951 // The virtual specifier shall only be used in declarations of 8952 // nonstatic class member functions that appear within a 8953 // member-specification of a class declaration; see 10.3. 8954 // 8955 if (isVirtual && !NewFD->isInvalidDecl()) { 8956 if (!isVirtualOkay) { 8957 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8958 diag::err_virtual_non_function); 8959 } else if (!CurContext->isRecord()) { 8960 // 'virtual' was specified outside of the class. 8961 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8962 diag::err_virtual_out_of_class) 8963 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8964 } else if (NewFD->getDescribedFunctionTemplate()) { 8965 // C++ [temp.mem]p3: 8966 // A member function template shall not be virtual. 8967 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8968 diag::err_virtual_member_function_template) 8969 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8970 } else { 8971 // Okay: Add virtual to the method. 8972 NewFD->setVirtualAsWritten(true); 8973 } 8974 8975 if (getLangOpts().CPlusPlus14 && 8976 NewFD->getReturnType()->isUndeducedType()) 8977 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8978 } 8979 8980 if (getLangOpts().CPlusPlus14 && 8981 (NewFD->isDependentContext() || 8982 (isFriend && CurContext->isDependentContext())) && 8983 NewFD->getReturnType()->isUndeducedType()) { 8984 // If the function template is referenced directly (for instance, as a 8985 // member of the current instantiation), pretend it has a dependent type. 8986 // This is not really justified by the standard, but is the only sane 8987 // thing to do. 8988 // FIXME: For a friend function, we have not marked the function as being 8989 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8990 const FunctionProtoType *FPT = 8991 NewFD->getType()->castAs<FunctionProtoType>(); 8992 QualType Result = 8993 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8994 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8995 FPT->getExtProtoInfo())); 8996 } 8997 8998 // C++ [dcl.fct.spec]p3: 8999 // The inline specifier shall not appear on a block scope function 9000 // declaration. 9001 if (isInline && !NewFD->isInvalidDecl()) { 9002 if (CurContext->isFunctionOrMethod()) { 9003 // 'inline' is not allowed on block scope function declaration. 9004 Diag(D.getDeclSpec().getInlineSpecLoc(), 9005 diag::err_inline_declaration_block_scope) << Name 9006 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9007 } 9008 } 9009 9010 // C++ [dcl.fct.spec]p6: 9011 // The explicit specifier shall be used only in the declaration of a 9012 // constructor or conversion function within its class definition; 9013 // see 12.3.1 and 12.3.2. 9014 if (hasExplicit && !NewFD->isInvalidDecl() && 9015 !isa<CXXDeductionGuideDecl>(NewFD)) { 9016 if (!CurContext->isRecord()) { 9017 // 'explicit' was specified outside of the class. 9018 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9019 diag::err_explicit_out_of_class) 9020 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9021 } else if (!isa<CXXConstructorDecl>(NewFD) && 9022 !isa<CXXConversionDecl>(NewFD)) { 9023 // 'explicit' was specified on a function that wasn't a constructor 9024 // or conversion function. 9025 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9026 diag::err_explicit_non_ctor_or_conv_function) 9027 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9028 } 9029 } 9030 9031 if (ConstexprSpecKind ConstexprKind = 9032 D.getDeclSpec().getConstexprSpecifier()) { 9033 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9034 // are implicitly inline. 9035 NewFD->setImplicitlyInline(); 9036 9037 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9038 // be either constructors or to return a literal type. Therefore, 9039 // destructors cannot be declared constexpr. 9040 if (isa<CXXDestructorDecl>(NewFD) && 9041 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9042 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9043 << ConstexprKind; 9044 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9045 } 9046 // C++20 [dcl.constexpr]p2: An allocation function, or a 9047 // deallocation function shall not be declared with the consteval 9048 // specifier. 9049 if (ConstexprKind == CSK_consteval && 9050 (NewFD->getOverloadedOperator() == OO_New || 9051 NewFD->getOverloadedOperator() == OO_Array_New || 9052 NewFD->getOverloadedOperator() == OO_Delete || 9053 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9054 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9055 diag::err_invalid_consteval_decl_kind) 9056 << NewFD; 9057 NewFD->setConstexprKind(CSK_constexpr); 9058 } 9059 } 9060 9061 // If __module_private__ was specified, mark the function accordingly. 9062 if (D.getDeclSpec().isModulePrivateSpecified()) { 9063 if (isFunctionTemplateSpecialization) { 9064 SourceLocation ModulePrivateLoc 9065 = D.getDeclSpec().getModulePrivateSpecLoc(); 9066 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9067 << 0 9068 << FixItHint::CreateRemoval(ModulePrivateLoc); 9069 } else { 9070 NewFD->setModulePrivate(); 9071 if (FunctionTemplate) 9072 FunctionTemplate->setModulePrivate(); 9073 } 9074 } 9075 9076 if (isFriend) { 9077 if (FunctionTemplate) { 9078 FunctionTemplate->setObjectOfFriendDecl(); 9079 FunctionTemplate->setAccess(AS_public); 9080 } 9081 NewFD->setObjectOfFriendDecl(); 9082 NewFD->setAccess(AS_public); 9083 } 9084 9085 // If a function is defined as defaulted or deleted, mark it as such now. 9086 // We'll do the relevant checks on defaulted / deleted functions later. 9087 switch (D.getFunctionDefinitionKind()) { 9088 case FDK_Declaration: 9089 case FDK_Definition: 9090 break; 9091 9092 case FDK_Defaulted: 9093 NewFD->setDefaulted(); 9094 break; 9095 9096 case FDK_Deleted: 9097 NewFD->setDeletedAsWritten(); 9098 break; 9099 } 9100 9101 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9102 D.isFunctionDefinition()) { 9103 // C++ [class.mfct]p2: 9104 // A member function may be defined (8.4) in its class definition, in 9105 // which case it is an inline member function (7.1.2) 9106 NewFD->setImplicitlyInline(); 9107 } 9108 9109 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9110 !CurContext->isRecord()) { 9111 // C++ [class.static]p1: 9112 // A data or function member of a class may be declared static 9113 // in a class definition, in which case it is a static member of 9114 // the class. 9115 9116 // Complain about the 'static' specifier if it's on an out-of-line 9117 // member function definition. 9118 9119 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9120 // member function template declaration and class member template 9121 // declaration (MSVC versions before 2015), warn about this. 9122 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9123 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9124 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9125 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9126 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9127 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9128 } 9129 9130 // C++11 [except.spec]p15: 9131 // A deallocation function with no exception-specification is treated 9132 // as if it were specified with noexcept(true). 9133 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9134 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9135 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9136 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9137 NewFD->setType(Context.getFunctionType( 9138 FPT->getReturnType(), FPT->getParamTypes(), 9139 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9140 } 9141 9142 // Filter out previous declarations that don't match the scope. 9143 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9144 D.getCXXScopeSpec().isNotEmpty() || 9145 isMemberSpecialization || 9146 isFunctionTemplateSpecialization); 9147 9148 // Handle GNU asm-label extension (encoded as an attribute). 9149 if (Expr *E = (Expr*) D.getAsmLabel()) { 9150 // The parser guarantees this is a string. 9151 StringLiteral *SE = cast<StringLiteral>(E); 9152 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9153 /*IsLiteralLabel=*/true, 9154 SE->getStrTokenLoc(0))); 9155 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9156 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9157 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9158 if (I != ExtnameUndeclaredIdentifiers.end()) { 9159 if (isDeclExternC(NewFD)) { 9160 NewFD->addAttr(I->second); 9161 ExtnameUndeclaredIdentifiers.erase(I); 9162 } else 9163 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9164 << /*Variable*/0 << NewFD; 9165 } 9166 } 9167 9168 // Copy the parameter declarations from the declarator D to the function 9169 // declaration NewFD, if they are available. First scavenge them into Params. 9170 SmallVector<ParmVarDecl*, 16> Params; 9171 unsigned FTIIdx; 9172 if (D.isFunctionDeclarator(FTIIdx)) { 9173 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9174 9175 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9176 // function that takes no arguments, not a function that takes a 9177 // single void argument. 9178 // We let through "const void" here because Sema::GetTypeForDeclarator 9179 // already checks for that case. 9180 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9181 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9182 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9183 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9184 Param->setDeclContext(NewFD); 9185 Params.push_back(Param); 9186 9187 if (Param->isInvalidDecl()) 9188 NewFD->setInvalidDecl(); 9189 } 9190 } 9191 9192 if (!getLangOpts().CPlusPlus) { 9193 // In C, find all the tag declarations from the prototype and move them 9194 // into the function DeclContext. Remove them from the surrounding tag 9195 // injection context of the function, which is typically but not always 9196 // the TU. 9197 DeclContext *PrototypeTagContext = 9198 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9199 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9200 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9201 9202 // We don't want to reparent enumerators. Look at their parent enum 9203 // instead. 9204 if (!TD) { 9205 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9206 TD = cast<EnumDecl>(ECD->getDeclContext()); 9207 } 9208 if (!TD) 9209 continue; 9210 DeclContext *TagDC = TD->getLexicalDeclContext(); 9211 if (!TagDC->containsDecl(TD)) 9212 continue; 9213 TagDC->removeDecl(TD); 9214 TD->setDeclContext(NewFD); 9215 NewFD->addDecl(TD); 9216 9217 // Preserve the lexical DeclContext if it is not the surrounding tag 9218 // injection context of the FD. In this example, the semantic context of 9219 // E will be f and the lexical context will be S, while both the 9220 // semantic and lexical contexts of S will be f: 9221 // void f(struct S { enum E { a } f; } s); 9222 if (TagDC != PrototypeTagContext) 9223 TD->setLexicalDeclContext(TagDC); 9224 } 9225 } 9226 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9227 // When we're declaring a function with a typedef, typeof, etc as in the 9228 // following example, we'll need to synthesize (unnamed) 9229 // parameters for use in the declaration. 9230 // 9231 // @code 9232 // typedef void fn(int); 9233 // fn f; 9234 // @endcode 9235 9236 // Synthesize a parameter for each argument type. 9237 for (const auto &AI : FT->param_types()) { 9238 ParmVarDecl *Param = 9239 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9240 Param->setScopeInfo(0, Params.size()); 9241 Params.push_back(Param); 9242 } 9243 } else { 9244 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9245 "Should not need args for typedef of non-prototype fn"); 9246 } 9247 9248 // Finally, we know we have the right number of parameters, install them. 9249 NewFD->setParams(Params); 9250 9251 if (D.getDeclSpec().isNoreturnSpecified()) 9252 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9253 D.getDeclSpec().getNoreturnSpecLoc(), 9254 AttributeCommonInfo::AS_Keyword)); 9255 9256 // Functions returning a variably modified type violate C99 6.7.5.2p2 9257 // because all functions have linkage. 9258 if (!NewFD->isInvalidDecl() && 9259 NewFD->getReturnType()->isVariablyModifiedType()) { 9260 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9261 NewFD->setInvalidDecl(); 9262 } 9263 9264 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9265 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9266 !NewFD->hasAttr<SectionAttr>()) 9267 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9268 Context, PragmaClangTextSection.SectionName, 9269 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9270 9271 // Apply an implicit SectionAttr if #pragma code_seg is active. 9272 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9273 !NewFD->hasAttr<SectionAttr>()) { 9274 NewFD->addAttr(SectionAttr::CreateImplicit( 9275 Context, CodeSegStack.CurrentValue->getString(), 9276 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9277 SectionAttr::Declspec_allocate)); 9278 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9279 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9280 ASTContext::PSF_Read, 9281 NewFD)) 9282 NewFD->dropAttr<SectionAttr>(); 9283 } 9284 9285 // Apply an implicit CodeSegAttr from class declspec or 9286 // apply an implicit SectionAttr from #pragma code_seg if active. 9287 if (!NewFD->hasAttr<CodeSegAttr>()) { 9288 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9289 D.isFunctionDefinition())) { 9290 NewFD->addAttr(SAttr); 9291 } 9292 } 9293 9294 // Handle attributes. 9295 ProcessDeclAttributes(S, NewFD, D); 9296 9297 if (getLangOpts().OpenCL) { 9298 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9299 // type declaration will generate a compilation error. 9300 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9301 if (AddressSpace != LangAS::Default) { 9302 Diag(NewFD->getLocation(), 9303 diag::err_opencl_return_value_with_address_space); 9304 NewFD->setInvalidDecl(); 9305 } 9306 } 9307 9308 if (!getLangOpts().CPlusPlus) { 9309 // Perform semantic checking on the function declaration. 9310 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9311 CheckMain(NewFD, D.getDeclSpec()); 9312 9313 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9314 CheckMSVCRTEntryPoint(NewFD); 9315 9316 if (!NewFD->isInvalidDecl()) 9317 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9318 isMemberSpecialization)); 9319 else if (!Previous.empty()) 9320 // Recover gracefully from an invalid redeclaration. 9321 D.setRedeclaration(true); 9322 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9323 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9324 "previous declaration set still overloaded"); 9325 9326 // Diagnose no-prototype function declarations with calling conventions that 9327 // don't support variadic calls. Only do this in C and do it after merging 9328 // possibly prototyped redeclarations. 9329 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9330 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9331 CallingConv CC = FT->getExtInfo().getCC(); 9332 if (!supportsVariadicCall(CC)) { 9333 // Windows system headers sometimes accidentally use stdcall without 9334 // (void) parameters, so we relax this to a warning. 9335 int DiagID = 9336 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9337 Diag(NewFD->getLocation(), DiagID) 9338 << FunctionType::getNameForCallConv(CC); 9339 } 9340 } 9341 9342 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9343 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9344 checkNonTrivialCUnion(NewFD->getReturnType(), 9345 NewFD->getReturnTypeSourceRange().getBegin(), 9346 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9347 } else { 9348 // C++11 [replacement.functions]p3: 9349 // The program's definitions shall not be specified as inline. 9350 // 9351 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9352 // 9353 // Suppress the diagnostic if the function is __attribute__((used)), since 9354 // that forces an external definition to be emitted. 9355 if (D.getDeclSpec().isInlineSpecified() && 9356 NewFD->isReplaceableGlobalAllocationFunction() && 9357 !NewFD->hasAttr<UsedAttr>()) 9358 Diag(D.getDeclSpec().getInlineSpecLoc(), 9359 diag::ext_operator_new_delete_declared_inline) 9360 << NewFD->getDeclName(); 9361 9362 // If the declarator is a template-id, translate the parser's template 9363 // argument list into our AST format. 9364 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9365 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9366 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9367 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9368 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9369 TemplateId->NumArgs); 9370 translateTemplateArguments(TemplateArgsPtr, 9371 TemplateArgs); 9372 9373 HasExplicitTemplateArgs = true; 9374 9375 if (NewFD->isInvalidDecl()) { 9376 HasExplicitTemplateArgs = false; 9377 } else if (FunctionTemplate) { 9378 // Function template with explicit template arguments. 9379 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9380 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9381 9382 HasExplicitTemplateArgs = false; 9383 } else { 9384 assert((isFunctionTemplateSpecialization || 9385 D.getDeclSpec().isFriendSpecified()) && 9386 "should have a 'template<>' for this decl"); 9387 // "friend void foo<>(int);" is an implicit specialization decl. 9388 isFunctionTemplateSpecialization = true; 9389 } 9390 } else if (isFriend && isFunctionTemplateSpecialization) { 9391 // This combination is only possible in a recovery case; the user 9392 // wrote something like: 9393 // template <> friend void foo(int); 9394 // which we're recovering from as if the user had written: 9395 // friend void foo<>(int); 9396 // Go ahead and fake up a template id. 9397 HasExplicitTemplateArgs = true; 9398 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9399 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9400 } 9401 9402 // We do not add HD attributes to specializations here because 9403 // they may have different constexpr-ness compared to their 9404 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9405 // may end up with different effective targets. Instead, a 9406 // specialization inherits its target attributes from its template 9407 // in the CheckFunctionTemplateSpecialization() call below. 9408 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9409 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9410 9411 // If it's a friend (and only if it's a friend), it's possible 9412 // that either the specialized function type or the specialized 9413 // template is dependent, and therefore matching will fail. In 9414 // this case, don't check the specialization yet. 9415 bool InstantiationDependent = false; 9416 if (isFunctionTemplateSpecialization && isFriend && 9417 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9418 TemplateSpecializationType::anyDependentTemplateArguments( 9419 TemplateArgs, 9420 InstantiationDependent))) { 9421 assert(HasExplicitTemplateArgs && 9422 "friend function specialization without template args"); 9423 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9424 Previous)) 9425 NewFD->setInvalidDecl(); 9426 } else if (isFunctionTemplateSpecialization) { 9427 if (CurContext->isDependentContext() && CurContext->isRecord() 9428 && !isFriend) { 9429 isDependentClassScopeExplicitSpecialization = true; 9430 } else if (!NewFD->isInvalidDecl() && 9431 CheckFunctionTemplateSpecialization( 9432 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9433 Previous)) 9434 NewFD->setInvalidDecl(); 9435 9436 // C++ [dcl.stc]p1: 9437 // A storage-class-specifier shall not be specified in an explicit 9438 // specialization (14.7.3) 9439 FunctionTemplateSpecializationInfo *Info = 9440 NewFD->getTemplateSpecializationInfo(); 9441 if (Info && SC != SC_None) { 9442 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9443 Diag(NewFD->getLocation(), 9444 diag::err_explicit_specialization_inconsistent_storage_class) 9445 << SC 9446 << FixItHint::CreateRemoval( 9447 D.getDeclSpec().getStorageClassSpecLoc()); 9448 9449 else 9450 Diag(NewFD->getLocation(), 9451 diag::ext_explicit_specialization_storage_class) 9452 << FixItHint::CreateRemoval( 9453 D.getDeclSpec().getStorageClassSpecLoc()); 9454 } 9455 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9456 if (CheckMemberSpecialization(NewFD, Previous)) 9457 NewFD->setInvalidDecl(); 9458 } 9459 9460 // Perform semantic checking on the function declaration. 9461 if (!isDependentClassScopeExplicitSpecialization) { 9462 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9463 CheckMain(NewFD, D.getDeclSpec()); 9464 9465 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9466 CheckMSVCRTEntryPoint(NewFD); 9467 9468 if (!NewFD->isInvalidDecl()) 9469 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9470 isMemberSpecialization)); 9471 else if (!Previous.empty()) 9472 // Recover gracefully from an invalid redeclaration. 9473 D.setRedeclaration(true); 9474 } 9475 9476 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9477 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9478 "previous declaration set still overloaded"); 9479 9480 NamedDecl *PrincipalDecl = (FunctionTemplate 9481 ? cast<NamedDecl>(FunctionTemplate) 9482 : NewFD); 9483 9484 if (isFriend && NewFD->getPreviousDecl()) { 9485 AccessSpecifier Access = AS_public; 9486 if (!NewFD->isInvalidDecl()) 9487 Access = NewFD->getPreviousDecl()->getAccess(); 9488 9489 NewFD->setAccess(Access); 9490 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9491 } 9492 9493 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9494 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9495 PrincipalDecl->setNonMemberOperator(); 9496 9497 // If we have a function template, check the template parameter 9498 // list. This will check and merge default template arguments. 9499 if (FunctionTemplate) { 9500 FunctionTemplateDecl *PrevTemplate = 9501 FunctionTemplate->getPreviousDecl(); 9502 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9503 PrevTemplate ? PrevTemplate->getTemplateParameters() 9504 : nullptr, 9505 D.getDeclSpec().isFriendSpecified() 9506 ? (D.isFunctionDefinition() 9507 ? TPC_FriendFunctionTemplateDefinition 9508 : TPC_FriendFunctionTemplate) 9509 : (D.getCXXScopeSpec().isSet() && 9510 DC && DC->isRecord() && 9511 DC->isDependentContext()) 9512 ? TPC_ClassTemplateMember 9513 : TPC_FunctionTemplate); 9514 } 9515 9516 if (NewFD->isInvalidDecl()) { 9517 // Ignore all the rest of this. 9518 } else if (!D.isRedeclaration()) { 9519 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9520 AddToScope }; 9521 // Fake up an access specifier if it's supposed to be a class member. 9522 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9523 NewFD->setAccess(AS_public); 9524 9525 // Qualified decls generally require a previous declaration. 9526 if (D.getCXXScopeSpec().isSet()) { 9527 // ...with the major exception of templated-scope or 9528 // dependent-scope friend declarations. 9529 9530 // TODO: we currently also suppress this check in dependent 9531 // contexts because (1) the parameter depth will be off when 9532 // matching friend templates and (2) we might actually be 9533 // selecting a friend based on a dependent factor. But there 9534 // are situations where these conditions don't apply and we 9535 // can actually do this check immediately. 9536 // 9537 // Unless the scope is dependent, it's always an error if qualified 9538 // redeclaration lookup found nothing at all. Diagnose that now; 9539 // nothing will diagnose that error later. 9540 if (isFriend && 9541 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9542 (!Previous.empty() && CurContext->isDependentContext()))) { 9543 // ignore these 9544 } else { 9545 // The user tried to provide an out-of-line definition for a 9546 // function that is a member of a class or namespace, but there 9547 // was no such member function declared (C++ [class.mfct]p2, 9548 // C++ [namespace.memdef]p2). For example: 9549 // 9550 // class X { 9551 // void f() const; 9552 // }; 9553 // 9554 // void X::f() { } // ill-formed 9555 // 9556 // Complain about this problem, and attempt to suggest close 9557 // matches (e.g., those that differ only in cv-qualifiers and 9558 // whether the parameter types are references). 9559 9560 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9561 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9562 AddToScope = ExtraArgs.AddToScope; 9563 return Result; 9564 } 9565 } 9566 9567 // Unqualified local friend declarations are required to resolve 9568 // to something. 9569 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9570 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9571 *this, Previous, NewFD, ExtraArgs, true, S)) { 9572 AddToScope = ExtraArgs.AddToScope; 9573 return Result; 9574 } 9575 } 9576 } else if (!D.isFunctionDefinition() && 9577 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9578 !isFriend && !isFunctionTemplateSpecialization && 9579 !isMemberSpecialization) { 9580 // An out-of-line member function declaration must also be a 9581 // definition (C++ [class.mfct]p2). 9582 // Note that this is not the case for explicit specializations of 9583 // function templates or member functions of class templates, per 9584 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9585 // extension for compatibility with old SWIG code which likes to 9586 // generate them. 9587 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9588 << D.getCXXScopeSpec().getRange(); 9589 } 9590 } 9591 9592 ProcessPragmaWeak(S, NewFD); 9593 checkAttributesAfterMerging(*this, *NewFD); 9594 9595 AddKnownFunctionAttributes(NewFD); 9596 9597 if (NewFD->hasAttr<OverloadableAttr>() && 9598 !NewFD->getType()->getAs<FunctionProtoType>()) { 9599 Diag(NewFD->getLocation(), 9600 diag::err_attribute_overloadable_no_prototype) 9601 << NewFD; 9602 9603 // Turn this into a variadic function with no parameters. 9604 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9605 FunctionProtoType::ExtProtoInfo EPI( 9606 Context.getDefaultCallingConvention(true, false)); 9607 EPI.Variadic = true; 9608 EPI.ExtInfo = FT->getExtInfo(); 9609 9610 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9611 NewFD->setType(R); 9612 } 9613 9614 // If there's a #pragma GCC visibility in scope, and this isn't a class 9615 // member, set the visibility of this function. 9616 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9617 AddPushedVisibilityAttribute(NewFD); 9618 9619 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9620 // marking the function. 9621 AddCFAuditedAttribute(NewFD); 9622 9623 // If this is a function definition, check if we have to apply optnone due to 9624 // a pragma. 9625 if(D.isFunctionDefinition()) 9626 AddRangeBasedOptnone(NewFD); 9627 9628 // If this is the first declaration of an extern C variable, update 9629 // the map of such variables. 9630 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9631 isIncompleteDeclExternC(*this, NewFD)) 9632 RegisterLocallyScopedExternCDecl(NewFD, S); 9633 9634 // Set this FunctionDecl's range up to the right paren. 9635 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9636 9637 if (D.isRedeclaration() && !Previous.empty()) { 9638 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9639 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9640 isMemberSpecialization || 9641 isFunctionTemplateSpecialization, 9642 D.isFunctionDefinition()); 9643 } 9644 9645 if (getLangOpts().CUDA) { 9646 IdentifierInfo *II = NewFD->getIdentifier(); 9647 if (II && II->isStr(getCudaConfigureFuncName()) && 9648 !NewFD->isInvalidDecl() && 9649 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9650 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9651 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9652 << getCudaConfigureFuncName(); 9653 Context.setcudaConfigureCallDecl(NewFD); 9654 } 9655 9656 // Variadic functions, other than a *declaration* of printf, are not allowed 9657 // in device-side CUDA code, unless someone passed 9658 // -fcuda-allow-variadic-functions. 9659 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9660 (NewFD->hasAttr<CUDADeviceAttr>() || 9661 NewFD->hasAttr<CUDAGlobalAttr>()) && 9662 !(II && II->isStr("printf") && NewFD->isExternC() && 9663 !D.isFunctionDefinition())) { 9664 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9665 } 9666 } 9667 9668 MarkUnusedFileScopedDecl(NewFD); 9669 9670 9671 9672 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9673 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9674 if ((getLangOpts().OpenCLVersion >= 120) 9675 && (SC == SC_Static)) { 9676 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9677 D.setInvalidType(); 9678 } 9679 9680 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9681 if (!NewFD->getReturnType()->isVoidType()) { 9682 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9683 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9684 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9685 : FixItHint()); 9686 D.setInvalidType(); 9687 } 9688 9689 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9690 for (auto Param : NewFD->parameters()) 9691 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9692 9693 if (getLangOpts().OpenCLCPlusPlus) { 9694 if (DC->isRecord()) { 9695 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9696 D.setInvalidType(); 9697 } 9698 if (FunctionTemplate) { 9699 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9700 D.setInvalidType(); 9701 } 9702 } 9703 } 9704 9705 if (getLangOpts().CPlusPlus) { 9706 if (FunctionTemplate) { 9707 if (NewFD->isInvalidDecl()) 9708 FunctionTemplate->setInvalidDecl(); 9709 return FunctionTemplate; 9710 } 9711 9712 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9713 CompleteMemberSpecialization(NewFD, Previous); 9714 } 9715 9716 for (const ParmVarDecl *Param : NewFD->parameters()) { 9717 QualType PT = Param->getType(); 9718 9719 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9720 // types. 9721 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9722 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9723 QualType ElemTy = PipeTy->getElementType(); 9724 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9725 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9726 D.setInvalidType(); 9727 } 9728 } 9729 } 9730 } 9731 9732 // Here we have an function template explicit specialization at class scope. 9733 // The actual specialization will be postponed to template instatiation 9734 // time via the ClassScopeFunctionSpecializationDecl node. 9735 if (isDependentClassScopeExplicitSpecialization) { 9736 ClassScopeFunctionSpecializationDecl *NewSpec = 9737 ClassScopeFunctionSpecializationDecl::Create( 9738 Context, CurContext, NewFD->getLocation(), 9739 cast<CXXMethodDecl>(NewFD), 9740 HasExplicitTemplateArgs, TemplateArgs); 9741 CurContext->addDecl(NewSpec); 9742 AddToScope = false; 9743 } 9744 9745 // Diagnose availability attributes. Availability cannot be used on functions 9746 // that are run during load/unload. 9747 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9748 if (NewFD->hasAttr<ConstructorAttr>()) { 9749 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9750 << 1; 9751 NewFD->dropAttr<AvailabilityAttr>(); 9752 } 9753 if (NewFD->hasAttr<DestructorAttr>()) { 9754 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9755 << 2; 9756 NewFD->dropAttr<AvailabilityAttr>(); 9757 } 9758 } 9759 9760 // Diagnose no_builtin attribute on function declaration that are not a 9761 // definition. 9762 // FIXME: We should really be doing this in 9763 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9764 // the FunctionDecl and at this point of the code 9765 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9766 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9767 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9768 switch (D.getFunctionDefinitionKind()) { 9769 case FDK_Defaulted: 9770 case FDK_Deleted: 9771 Diag(NBA->getLocation(), 9772 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9773 << NBA->getSpelling(); 9774 break; 9775 case FDK_Declaration: 9776 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9777 << NBA->getSpelling(); 9778 break; 9779 case FDK_Definition: 9780 break; 9781 } 9782 9783 return NewFD; 9784 } 9785 9786 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9787 /// when __declspec(code_seg) "is applied to a class, all member functions of 9788 /// the class and nested classes -- this includes compiler-generated special 9789 /// member functions -- are put in the specified segment." 9790 /// The actual behavior is a little more complicated. The Microsoft compiler 9791 /// won't check outer classes if there is an active value from #pragma code_seg. 9792 /// The CodeSeg is always applied from the direct parent but only from outer 9793 /// classes when the #pragma code_seg stack is empty. See: 9794 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9795 /// available since MS has removed the page. 9796 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9797 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9798 if (!Method) 9799 return nullptr; 9800 const CXXRecordDecl *Parent = Method->getParent(); 9801 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9802 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9803 NewAttr->setImplicit(true); 9804 return NewAttr; 9805 } 9806 9807 // The Microsoft compiler won't check outer classes for the CodeSeg 9808 // when the #pragma code_seg stack is active. 9809 if (S.CodeSegStack.CurrentValue) 9810 return nullptr; 9811 9812 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9813 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9814 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9815 NewAttr->setImplicit(true); 9816 return NewAttr; 9817 } 9818 } 9819 return nullptr; 9820 } 9821 9822 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9823 /// containing class. Otherwise it will return implicit SectionAttr if the 9824 /// function is a definition and there is an active value on CodeSegStack 9825 /// (from the current #pragma code-seg value). 9826 /// 9827 /// \param FD Function being declared. 9828 /// \param IsDefinition Whether it is a definition or just a declarartion. 9829 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9830 /// nullptr if no attribute should be added. 9831 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9832 bool IsDefinition) { 9833 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9834 return A; 9835 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9836 CodeSegStack.CurrentValue) 9837 return SectionAttr::CreateImplicit( 9838 getASTContext(), CodeSegStack.CurrentValue->getString(), 9839 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9840 SectionAttr::Declspec_allocate); 9841 return nullptr; 9842 } 9843 9844 /// Determines if we can perform a correct type check for \p D as a 9845 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9846 /// best-effort check. 9847 /// 9848 /// \param NewD The new declaration. 9849 /// \param OldD The old declaration. 9850 /// \param NewT The portion of the type of the new declaration to check. 9851 /// \param OldT The portion of the type of the old declaration to check. 9852 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9853 QualType NewT, QualType OldT) { 9854 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9855 return true; 9856 9857 // For dependently-typed local extern declarations and friends, we can't 9858 // perform a correct type check in general until instantiation: 9859 // 9860 // int f(); 9861 // template<typename T> void g() { T f(); } 9862 // 9863 // (valid if g() is only instantiated with T = int). 9864 if (NewT->isDependentType() && 9865 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9866 return false; 9867 9868 // Similarly, if the previous declaration was a dependent local extern 9869 // declaration, we don't really know its type yet. 9870 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9871 return false; 9872 9873 return true; 9874 } 9875 9876 /// Checks if the new declaration declared in dependent context must be 9877 /// put in the same redeclaration chain as the specified declaration. 9878 /// 9879 /// \param D Declaration that is checked. 9880 /// \param PrevDecl Previous declaration found with proper lookup method for the 9881 /// same declaration name. 9882 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9883 /// belongs to. 9884 /// 9885 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9886 if (!D->getLexicalDeclContext()->isDependentContext()) 9887 return true; 9888 9889 // Don't chain dependent friend function definitions until instantiation, to 9890 // permit cases like 9891 // 9892 // void func(); 9893 // template<typename T> class C1 { friend void func() {} }; 9894 // template<typename T> class C2 { friend void func() {} }; 9895 // 9896 // ... which is valid if only one of C1 and C2 is ever instantiated. 9897 // 9898 // FIXME: This need only apply to function definitions. For now, we proxy 9899 // this by checking for a file-scope function. We do not want this to apply 9900 // to friend declarations nominating member functions, because that gets in 9901 // the way of access checks. 9902 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9903 return false; 9904 9905 auto *VD = dyn_cast<ValueDecl>(D); 9906 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9907 return !VD || !PrevVD || 9908 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9909 PrevVD->getType()); 9910 } 9911 9912 /// Check the target attribute of the function for MultiVersion 9913 /// validity. 9914 /// 9915 /// Returns true if there was an error, false otherwise. 9916 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9917 const auto *TA = FD->getAttr<TargetAttr>(); 9918 assert(TA && "MultiVersion Candidate requires a target attribute"); 9919 ParsedTargetAttr ParseInfo = TA->parse(); 9920 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9921 enum ErrType { Feature = 0, Architecture = 1 }; 9922 9923 if (!ParseInfo.Architecture.empty() && 9924 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9925 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9926 << Architecture << ParseInfo.Architecture; 9927 return true; 9928 } 9929 9930 for (const auto &Feat : ParseInfo.Features) { 9931 auto BareFeat = StringRef{Feat}.substr(1); 9932 if (Feat[0] == '-') { 9933 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9934 << Feature << ("no-" + BareFeat).str(); 9935 return true; 9936 } 9937 9938 if (!TargetInfo.validateCpuSupports(BareFeat) || 9939 !TargetInfo.isValidFeatureName(BareFeat)) { 9940 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9941 << Feature << BareFeat; 9942 return true; 9943 } 9944 } 9945 return false; 9946 } 9947 9948 // Provide a white-list of attributes that are allowed to be combined with 9949 // multiversion functions. 9950 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9951 MultiVersionKind MVType) { 9952 switch (Kind) { 9953 default: 9954 return false; 9955 case attr::Used: 9956 return MVType == MultiVersionKind::Target; 9957 } 9958 } 9959 9960 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9961 MultiVersionKind MVType) { 9962 for (const Attr *A : FD->attrs()) { 9963 switch (A->getKind()) { 9964 case attr::CPUDispatch: 9965 case attr::CPUSpecific: 9966 if (MVType != MultiVersionKind::CPUDispatch && 9967 MVType != MultiVersionKind::CPUSpecific) 9968 return true; 9969 break; 9970 case attr::Target: 9971 if (MVType != MultiVersionKind::Target) 9972 return true; 9973 break; 9974 default: 9975 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 9976 return true; 9977 break; 9978 } 9979 } 9980 return false; 9981 } 9982 9983 bool Sema::areMultiversionVariantFunctionsCompatible( 9984 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9985 const PartialDiagnostic &NoProtoDiagID, 9986 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9987 const PartialDiagnosticAt &NoSupportDiagIDAt, 9988 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9989 bool ConstexprSupported, bool CLinkageMayDiffer) { 9990 enum DoesntSupport { 9991 FuncTemplates = 0, 9992 VirtFuncs = 1, 9993 DeducedReturn = 2, 9994 Constructors = 3, 9995 Destructors = 4, 9996 DeletedFuncs = 5, 9997 DefaultedFuncs = 6, 9998 ConstexprFuncs = 7, 9999 ConstevalFuncs = 8, 10000 }; 10001 enum Different { 10002 CallingConv = 0, 10003 ReturnType = 1, 10004 ConstexprSpec = 2, 10005 InlineSpec = 3, 10006 StorageClass = 4, 10007 Linkage = 5, 10008 }; 10009 10010 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10011 !OldFD->getType()->getAs<FunctionProtoType>()) { 10012 Diag(OldFD->getLocation(), NoProtoDiagID); 10013 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10014 return true; 10015 } 10016 10017 if (NoProtoDiagID.getDiagID() != 0 && 10018 !NewFD->getType()->getAs<FunctionProtoType>()) 10019 return Diag(NewFD->getLocation(), NoProtoDiagID); 10020 10021 if (!TemplatesSupported && 10022 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10023 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10024 << FuncTemplates; 10025 10026 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10027 if (NewCXXFD->isVirtual()) 10028 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10029 << VirtFuncs; 10030 10031 if (isa<CXXConstructorDecl>(NewCXXFD)) 10032 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10033 << Constructors; 10034 10035 if (isa<CXXDestructorDecl>(NewCXXFD)) 10036 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10037 << Destructors; 10038 } 10039 10040 if (NewFD->isDeleted()) 10041 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10042 << DeletedFuncs; 10043 10044 if (NewFD->isDefaulted()) 10045 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10046 << DefaultedFuncs; 10047 10048 if (!ConstexprSupported && NewFD->isConstexpr()) 10049 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10050 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10051 10052 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10053 const auto *NewType = cast<FunctionType>(NewQType); 10054 QualType NewReturnType = NewType->getReturnType(); 10055 10056 if (NewReturnType->isUndeducedType()) 10057 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10058 << DeducedReturn; 10059 10060 // Ensure the return type is identical. 10061 if (OldFD) { 10062 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10063 const auto *OldType = cast<FunctionType>(OldQType); 10064 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10065 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10066 10067 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10068 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10069 10070 QualType OldReturnType = OldType->getReturnType(); 10071 10072 if (OldReturnType != NewReturnType) 10073 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10074 10075 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10076 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10077 10078 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10079 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10080 10081 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10082 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10083 10084 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10085 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10086 10087 if (CheckEquivalentExceptionSpec( 10088 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10089 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10090 return true; 10091 } 10092 return false; 10093 } 10094 10095 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10096 const FunctionDecl *NewFD, 10097 bool CausesMV, 10098 MultiVersionKind MVType) { 10099 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10100 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10101 if (OldFD) 10102 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10103 return true; 10104 } 10105 10106 bool IsCPUSpecificCPUDispatchMVType = 10107 MVType == MultiVersionKind::CPUDispatch || 10108 MVType == MultiVersionKind::CPUSpecific; 10109 10110 // For now, disallow all other attributes. These should be opt-in, but 10111 // an analysis of all of them is a future FIXME. 10112 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10113 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10114 << IsCPUSpecificCPUDispatchMVType; 10115 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10116 return true; 10117 } 10118 10119 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10120 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10121 << IsCPUSpecificCPUDispatchMVType; 10122 10123 // Only allow transition to MultiVersion if it hasn't been used. 10124 if (OldFD && CausesMV && OldFD->isUsed(false)) 10125 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10126 10127 return S.areMultiversionVariantFunctionsCompatible( 10128 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10129 PartialDiagnosticAt(NewFD->getLocation(), 10130 S.PDiag(diag::note_multiversioning_caused_here)), 10131 PartialDiagnosticAt(NewFD->getLocation(), 10132 S.PDiag(diag::err_multiversion_doesnt_support) 10133 << IsCPUSpecificCPUDispatchMVType), 10134 PartialDiagnosticAt(NewFD->getLocation(), 10135 S.PDiag(diag::err_multiversion_diff)), 10136 /*TemplatesSupported=*/false, 10137 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10138 /*CLinkageMayDiffer=*/false); 10139 } 10140 10141 /// Check the validity of a multiversion function declaration that is the 10142 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10143 /// 10144 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10145 /// 10146 /// Returns true if there was an error, false otherwise. 10147 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10148 MultiVersionKind MVType, 10149 const TargetAttr *TA) { 10150 assert(MVType != MultiVersionKind::None && 10151 "Function lacks multiversion attribute"); 10152 10153 // Target only causes MV if it is default, otherwise this is a normal 10154 // function. 10155 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10156 return false; 10157 10158 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10159 FD->setInvalidDecl(); 10160 return true; 10161 } 10162 10163 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10164 FD->setInvalidDecl(); 10165 return true; 10166 } 10167 10168 FD->setIsMultiVersion(); 10169 return false; 10170 } 10171 10172 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10173 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10174 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10175 return true; 10176 } 10177 10178 return false; 10179 } 10180 10181 static bool CheckTargetCausesMultiVersioning( 10182 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10183 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10184 LookupResult &Previous) { 10185 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10186 ParsedTargetAttr NewParsed = NewTA->parse(); 10187 // Sort order doesn't matter, it just needs to be consistent. 10188 llvm::sort(NewParsed.Features); 10189 10190 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10191 // to change, this is a simple redeclaration. 10192 if (!NewTA->isDefaultVersion() && 10193 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10194 return false; 10195 10196 // Otherwise, this decl causes MultiVersioning. 10197 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10198 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10199 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10200 NewFD->setInvalidDecl(); 10201 return true; 10202 } 10203 10204 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10205 MultiVersionKind::Target)) { 10206 NewFD->setInvalidDecl(); 10207 return true; 10208 } 10209 10210 if (CheckMultiVersionValue(S, NewFD)) { 10211 NewFD->setInvalidDecl(); 10212 return true; 10213 } 10214 10215 // If this is 'default', permit the forward declaration. 10216 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10217 Redeclaration = true; 10218 OldDecl = OldFD; 10219 OldFD->setIsMultiVersion(); 10220 NewFD->setIsMultiVersion(); 10221 return false; 10222 } 10223 10224 if (CheckMultiVersionValue(S, OldFD)) { 10225 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10226 NewFD->setInvalidDecl(); 10227 return true; 10228 } 10229 10230 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10231 10232 if (OldParsed == NewParsed) { 10233 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10234 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10235 NewFD->setInvalidDecl(); 10236 return true; 10237 } 10238 10239 for (const auto *FD : OldFD->redecls()) { 10240 const auto *CurTA = FD->getAttr<TargetAttr>(); 10241 // We allow forward declarations before ANY multiversioning attributes, but 10242 // nothing after the fact. 10243 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10244 (!CurTA || CurTA->isInherited())) { 10245 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10246 << 0; 10247 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10248 NewFD->setInvalidDecl(); 10249 return true; 10250 } 10251 } 10252 10253 OldFD->setIsMultiVersion(); 10254 NewFD->setIsMultiVersion(); 10255 Redeclaration = false; 10256 MergeTypeWithPrevious = false; 10257 OldDecl = nullptr; 10258 Previous.clear(); 10259 return false; 10260 } 10261 10262 /// Check the validity of a new function declaration being added to an existing 10263 /// multiversioned declaration collection. 10264 static bool CheckMultiVersionAdditionalDecl( 10265 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10266 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10267 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10268 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10269 LookupResult &Previous) { 10270 10271 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10272 // Disallow mixing of multiversioning types. 10273 if ((OldMVType == MultiVersionKind::Target && 10274 NewMVType != MultiVersionKind::Target) || 10275 (NewMVType == MultiVersionKind::Target && 10276 OldMVType != MultiVersionKind::Target)) { 10277 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10278 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10279 NewFD->setInvalidDecl(); 10280 return true; 10281 } 10282 10283 ParsedTargetAttr NewParsed; 10284 if (NewTA) { 10285 NewParsed = NewTA->parse(); 10286 llvm::sort(NewParsed.Features); 10287 } 10288 10289 bool UseMemberUsingDeclRules = 10290 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10291 10292 // Next, check ALL non-overloads to see if this is a redeclaration of a 10293 // previous member of the MultiVersion set. 10294 for (NamedDecl *ND : Previous) { 10295 FunctionDecl *CurFD = ND->getAsFunction(); 10296 if (!CurFD) 10297 continue; 10298 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10299 continue; 10300 10301 if (NewMVType == MultiVersionKind::Target) { 10302 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10303 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10304 NewFD->setIsMultiVersion(); 10305 Redeclaration = true; 10306 OldDecl = ND; 10307 return false; 10308 } 10309 10310 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10311 if (CurParsed == NewParsed) { 10312 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10313 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10314 NewFD->setInvalidDecl(); 10315 return true; 10316 } 10317 } else { 10318 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10319 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10320 // Handle CPUDispatch/CPUSpecific versions. 10321 // Only 1 CPUDispatch function is allowed, this will make it go through 10322 // the redeclaration errors. 10323 if (NewMVType == MultiVersionKind::CPUDispatch && 10324 CurFD->hasAttr<CPUDispatchAttr>()) { 10325 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10326 std::equal( 10327 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10328 NewCPUDisp->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 // If the declarations don't match, this is an error condition. 10339 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10340 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10341 NewFD->setInvalidDecl(); 10342 return true; 10343 } 10344 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10345 10346 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10347 std::equal( 10348 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10349 NewCPUSpec->cpus_begin(), 10350 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10351 return Cur->getName() == New->getName(); 10352 })) { 10353 NewFD->setIsMultiVersion(); 10354 Redeclaration = true; 10355 OldDecl = ND; 10356 return false; 10357 } 10358 10359 // Only 1 version of CPUSpecific is allowed for each CPU. 10360 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10361 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10362 if (CurII == NewII) { 10363 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10364 << NewII; 10365 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10366 NewFD->setInvalidDecl(); 10367 return true; 10368 } 10369 } 10370 } 10371 } 10372 // If the two decls aren't the same MVType, there is no possible error 10373 // condition. 10374 } 10375 } 10376 10377 // Else, this is simply a non-redecl case. Checking the 'value' is only 10378 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10379 // handled in the attribute adding step. 10380 if (NewMVType == MultiVersionKind::Target && 10381 CheckMultiVersionValue(S, NewFD)) { 10382 NewFD->setInvalidDecl(); 10383 return true; 10384 } 10385 10386 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10387 !OldFD->isMultiVersion(), NewMVType)) { 10388 NewFD->setInvalidDecl(); 10389 return true; 10390 } 10391 10392 // Permit forward declarations in the case where these two are compatible. 10393 if (!OldFD->isMultiVersion()) { 10394 OldFD->setIsMultiVersion(); 10395 NewFD->setIsMultiVersion(); 10396 Redeclaration = true; 10397 OldDecl = OldFD; 10398 return false; 10399 } 10400 10401 NewFD->setIsMultiVersion(); 10402 Redeclaration = false; 10403 MergeTypeWithPrevious = false; 10404 OldDecl = nullptr; 10405 Previous.clear(); 10406 return false; 10407 } 10408 10409 10410 /// Check the validity of a mulitversion function declaration. 10411 /// Also sets the multiversion'ness' of the function itself. 10412 /// 10413 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10414 /// 10415 /// Returns true if there was an error, false otherwise. 10416 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10417 bool &Redeclaration, NamedDecl *&OldDecl, 10418 bool &MergeTypeWithPrevious, 10419 LookupResult &Previous) { 10420 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10421 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10422 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10423 10424 // Mixing Multiversioning types is prohibited. 10425 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10426 (NewCPUDisp && NewCPUSpec)) { 10427 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10428 NewFD->setInvalidDecl(); 10429 return true; 10430 } 10431 10432 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10433 10434 // Main isn't allowed to become a multiversion function, however it IS 10435 // permitted to have 'main' be marked with the 'target' optimization hint. 10436 if (NewFD->isMain()) { 10437 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10438 MVType == MultiVersionKind::CPUDispatch || 10439 MVType == MultiVersionKind::CPUSpecific) { 10440 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10441 NewFD->setInvalidDecl(); 10442 return true; 10443 } 10444 return false; 10445 } 10446 10447 if (!OldDecl || !OldDecl->getAsFunction() || 10448 OldDecl->getDeclContext()->getRedeclContext() != 10449 NewFD->getDeclContext()->getRedeclContext()) { 10450 // If there's no previous declaration, AND this isn't attempting to cause 10451 // multiversioning, this isn't an error condition. 10452 if (MVType == MultiVersionKind::None) 10453 return false; 10454 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10455 } 10456 10457 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10458 10459 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10460 return false; 10461 10462 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10463 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10464 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10465 NewFD->setInvalidDecl(); 10466 return true; 10467 } 10468 10469 // Handle the target potentially causes multiversioning case. 10470 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10471 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10472 Redeclaration, OldDecl, 10473 MergeTypeWithPrevious, Previous); 10474 10475 // At this point, we have a multiversion function decl (in OldFD) AND an 10476 // appropriate attribute in the current function decl. Resolve that these are 10477 // still compatible with previous declarations. 10478 return CheckMultiVersionAdditionalDecl( 10479 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10480 OldDecl, MergeTypeWithPrevious, Previous); 10481 } 10482 10483 /// Perform semantic checking of a new function declaration. 10484 /// 10485 /// Performs semantic analysis of the new function declaration 10486 /// NewFD. This routine performs all semantic checking that does not 10487 /// require the actual declarator involved in the declaration, and is 10488 /// used both for the declaration of functions as they are parsed 10489 /// (called via ActOnDeclarator) and for the declaration of functions 10490 /// that have been instantiated via C++ template instantiation (called 10491 /// via InstantiateDecl). 10492 /// 10493 /// \param IsMemberSpecialization whether this new function declaration is 10494 /// a member specialization (that replaces any definition provided by the 10495 /// previous declaration). 10496 /// 10497 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10498 /// 10499 /// \returns true if the function declaration is a redeclaration. 10500 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10501 LookupResult &Previous, 10502 bool IsMemberSpecialization) { 10503 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10504 "Variably modified return types are not handled here"); 10505 10506 // Determine whether the type of this function should be merged with 10507 // a previous visible declaration. This never happens for functions in C++, 10508 // and always happens in C if the previous declaration was visible. 10509 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10510 !Previous.isShadowed(); 10511 10512 bool Redeclaration = false; 10513 NamedDecl *OldDecl = nullptr; 10514 bool MayNeedOverloadableChecks = false; 10515 10516 // Merge or overload the declaration with an existing declaration of 10517 // the same name, if appropriate. 10518 if (!Previous.empty()) { 10519 // Determine whether NewFD is an overload of PrevDecl or 10520 // a declaration that requires merging. If it's an overload, 10521 // there's no more work to do here; we'll just add the new 10522 // function to the scope. 10523 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10524 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10525 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10526 Redeclaration = true; 10527 OldDecl = Candidate; 10528 } 10529 } else { 10530 MayNeedOverloadableChecks = true; 10531 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10532 /*NewIsUsingDecl*/ false)) { 10533 case Ovl_Match: 10534 Redeclaration = true; 10535 break; 10536 10537 case Ovl_NonFunction: 10538 Redeclaration = true; 10539 break; 10540 10541 case Ovl_Overload: 10542 Redeclaration = false; 10543 break; 10544 } 10545 } 10546 } 10547 10548 // Check for a previous extern "C" declaration with this name. 10549 if (!Redeclaration && 10550 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10551 if (!Previous.empty()) { 10552 // This is an extern "C" declaration with the same name as a previous 10553 // declaration, and thus redeclares that entity... 10554 Redeclaration = true; 10555 OldDecl = Previous.getFoundDecl(); 10556 MergeTypeWithPrevious = false; 10557 10558 // ... except in the presence of __attribute__((overloadable)). 10559 if (OldDecl->hasAttr<OverloadableAttr>() || 10560 NewFD->hasAttr<OverloadableAttr>()) { 10561 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10562 MayNeedOverloadableChecks = true; 10563 Redeclaration = false; 10564 OldDecl = nullptr; 10565 } 10566 } 10567 } 10568 } 10569 10570 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10571 MergeTypeWithPrevious, Previous)) 10572 return Redeclaration; 10573 10574 // C++11 [dcl.constexpr]p8: 10575 // A constexpr specifier for a non-static member function that is not 10576 // a constructor declares that member function to be const. 10577 // 10578 // This needs to be delayed until we know whether this is an out-of-line 10579 // definition of a static member function. 10580 // 10581 // This rule is not present in C++1y, so we produce a backwards 10582 // compatibility warning whenever it happens in C++11. 10583 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10584 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10585 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10586 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10587 CXXMethodDecl *OldMD = nullptr; 10588 if (OldDecl) 10589 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10590 if (!OldMD || !OldMD->isStatic()) { 10591 const FunctionProtoType *FPT = 10592 MD->getType()->castAs<FunctionProtoType>(); 10593 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10594 EPI.TypeQuals.addConst(); 10595 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10596 FPT->getParamTypes(), EPI)); 10597 10598 // Warn that we did this, if we're not performing template instantiation. 10599 // In that case, we'll have warned already when the template was defined. 10600 if (!inTemplateInstantiation()) { 10601 SourceLocation AddConstLoc; 10602 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10603 .IgnoreParens().getAs<FunctionTypeLoc>()) 10604 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10605 10606 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10607 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10608 } 10609 } 10610 } 10611 10612 if (Redeclaration) { 10613 // NewFD and OldDecl represent declarations that need to be 10614 // merged. 10615 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10616 NewFD->setInvalidDecl(); 10617 return Redeclaration; 10618 } 10619 10620 Previous.clear(); 10621 Previous.addDecl(OldDecl); 10622 10623 if (FunctionTemplateDecl *OldTemplateDecl = 10624 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10625 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10626 FunctionTemplateDecl *NewTemplateDecl 10627 = NewFD->getDescribedFunctionTemplate(); 10628 assert(NewTemplateDecl && "Template/non-template mismatch"); 10629 10630 // The call to MergeFunctionDecl above may have created some state in 10631 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10632 // can add it as a redeclaration. 10633 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10634 10635 NewFD->setPreviousDeclaration(OldFD); 10636 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10637 if (NewFD->isCXXClassMember()) { 10638 NewFD->setAccess(OldTemplateDecl->getAccess()); 10639 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10640 } 10641 10642 // If this is an explicit specialization of a member that is a function 10643 // template, mark it as a member specialization. 10644 if (IsMemberSpecialization && 10645 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10646 NewTemplateDecl->setMemberSpecialization(); 10647 assert(OldTemplateDecl->isMemberSpecialization()); 10648 // Explicit specializations of a member template do not inherit deleted 10649 // status from the parent member template that they are specializing. 10650 if (OldFD->isDeleted()) { 10651 // FIXME: This assert will not hold in the presence of modules. 10652 assert(OldFD->getCanonicalDecl() == OldFD); 10653 // FIXME: We need an update record for this AST mutation. 10654 OldFD->setDeletedAsWritten(false); 10655 } 10656 } 10657 10658 } else { 10659 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10660 auto *OldFD = cast<FunctionDecl>(OldDecl); 10661 // This needs to happen first so that 'inline' propagates. 10662 NewFD->setPreviousDeclaration(OldFD); 10663 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10664 if (NewFD->isCXXClassMember()) 10665 NewFD->setAccess(OldFD->getAccess()); 10666 } 10667 } 10668 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10669 !NewFD->getAttr<OverloadableAttr>()) { 10670 assert((Previous.empty() || 10671 llvm::any_of(Previous, 10672 [](const NamedDecl *ND) { 10673 return ND->hasAttr<OverloadableAttr>(); 10674 })) && 10675 "Non-redecls shouldn't happen without overloadable present"); 10676 10677 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10678 const auto *FD = dyn_cast<FunctionDecl>(ND); 10679 return FD && !FD->hasAttr<OverloadableAttr>(); 10680 }); 10681 10682 if (OtherUnmarkedIter != Previous.end()) { 10683 Diag(NewFD->getLocation(), 10684 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10685 Diag((*OtherUnmarkedIter)->getLocation(), 10686 diag::note_attribute_overloadable_prev_overload) 10687 << false; 10688 10689 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10690 } 10691 } 10692 10693 // Semantic checking for this function declaration (in isolation). 10694 10695 if (getLangOpts().CPlusPlus) { 10696 // C++-specific checks. 10697 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10698 CheckConstructor(Constructor); 10699 } else if (CXXDestructorDecl *Destructor = 10700 dyn_cast<CXXDestructorDecl>(NewFD)) { 10701 CXXRecordDecl *Record = Destructor->getParent(); 10702 QualType ClassType = Context.getTypeDeclType(Record); 10703 10704 // FIXME: Shouldn't we be able to perform this check even when the class 10705 // type is dependent? Both gcc and edg can handle that. 10706 if (!ClassType->isDependentType()) { 10707 DeclarationName Name 10708 = Context.DeclarationNames.getCXXDestructorName( 10709 Context.getCanonicalType(ClassType)); 10710 if (NewFD->getDeclName() != Name) { 10711 Diag(NewFD->getLocation(), diag::err_destructor_name); 10712 NewFD->setInvalidDecl(); 10713 return Redeclaration; 10714 } 10715 } 10716 } else if (CXXConversionDecl *Conversion 10717 = dyn_cast<CXXConversionDecl>(NewFD)) { 10718 ActOnConversionDeclarator(Conversion); 10719 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10720 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10721 CheckDeductionGuideTemplate(TD); 10722 10723 // A deduction guide is not on the list of entities that can be 10724 // explicitly specialized. 10725 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10726 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10727 << /*explicit specialization*/ 1; 10728 } 10729 10730 // Find any virtual functions that this function overrides. 10731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10732 if (!Method->isFunctionTemplateSpecialization() && 10733 !Method->getDescribedFunctionTemplate() && 10734 Method->isCanonicalDecl()) { 10735 AddOverriddenMethods(Method->getParent(), Method); 10736 } 10737 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10738 // C++2a [class.virtual]p6 10739 // A virtual method shall not have a requires-clause. 10740 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10741 diag::err_constrained_virtual_method); 10742 10743 if (Method->isStatic()) 10744 checkThisInStaticMemberFunctionType(Method); 10745 } 10746 10747 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10748 if (NewFD->isOverloadedOperator() && 10749 CheckOverloadedOperatorDeclaration(NewFD)) { 10750 NewFD->setInvalidDecl(); 10751 return Redeclaration; 10752 } 10753 10754 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10755 if (NewFD->getLiteralIdentifier() && 10756 CheckLiteralOperatorDeclaration(NewFD)) { 10757 NewFD->setInvalidDecl(); 10758 return Redeclaration; 10759 } 10760 10761 // In C++, check default arguments now that we have merged decls. Unless 10762 // the lexical context is the class, because in this case this is done 10763 // during delayed parsing anyway. 10764 if (!CurContext->isRecord()) 10765 CheckCXXDefaultArguments(NewFD); 10766 10767 // If this function declares a builtin function, check the type of this 10768 // declaration against the expected type for the builtin. 10769 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10770 ASTContext::GetBuiltinTypeError Error; 10771 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10772 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10773 // If the type of the builtin differs only in its exception 10774 // specification, that's OK. 10775 // FIXME: If the types do differ in this way, it would be better to 10776 // retain the 'noexcept' form of the type. 10777 if (!T.isNull() && 10778 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10779 NewFD->getType())) 10780 // The type of this function differs from the type of the builtin, 10781 // so forget about the builtin entirely. 10782 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10783 } 10784 10785 // If this function is declared as being extern "C", then check to see if 10786 // the function returns a UDT (class, struct, or union type) that is not C 10787 // compatible, and if it does, warn the user. 10788 // But, issue any diagnostic on the first declaration only. 10789 if (Previous.empty() && NewFD->isExternC()) { 10790 QualType R = NewFD->getReturnType(); 10791 if (R->isIncompleteType() && !R->isVoidType()) 10792 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10793 << NewFD << R; 10794 else if (!R.isPODType(Context) && !R->isVoidType() && 10795 !R->isObjCObjectPointerType()) 10796 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10797 } 10798 10799 // C++1z [dcl.fct]p6: 10800 // [...] whether the function has a non-throwing exception-specification 10801 // [is] part of the function type 10802 // 10803 // This results in an ABI break between C++14 and C++17 for functions whose 10804 // declared type includes an exception-specification in a parameter or 10805 // return type. (Exception specifications on the function itself are OK in 10806 // most cases, and exception specifications are not permitted in most other 10807 // contexts where they could make it into a mangling.) 10808 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10809 auto HasNoexcept = [&](QualType T) -> bool { 10810 // Strip off declarator chunks that could be between us and a function 10811 // type. We don't need to look far, exception specifications are very 10812 // restricted prior to C++17. 10813 if (auto *RT = T->getAs<ReferenceType>()) 10814 T = RT->getPointeeType(); 10815 else if (T->isAnyPointerType()) 10816 T = T->getPointeeType(); 10817 else if (auto *MPT = T->getAs<MemberPointerType>()) 10818 T = MPT->getPointeeType(); 10819 if (auto *FPT = T->getAs<FunctionProtoType>()) 10820 if (FPT->isNothrow()) 10821 return true; 10822 return false; 10823 }; 10824 10825 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10826 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10827 for (QualType T : FPT->param_types()) 10828 AnyNoexcept |= HasNoexcept(T); 10829 if (AnyNoexcept) 10830 Diag(NewFD->getLocation(), 10831 diag::warn_cxx17_compat_exception_spec_in_signature) 10832 << NewFD; 10833 } 10834 10835 if (!Redeclaration && LangOpts.CUDA) 10836 checkCUDATargetOverload(NewFD, Previous); 10837 } 10838 return Redeclaration; 10839 } 10840 10841 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10842 // C++11 [basic.start.main]p3: 10843 // A program that [...] declares main to be inline, static or 10844 // constexpr is ill-formed. 10845 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10846 // appear in a declaration of main. 10847 // static main is not an error under C99, but we should warn about it. 10848 // We accept _Noreturn main as an extension. 10849 if (FD->getStorageClass() == SC_Static) 10850 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10851 ? diag::err_static_main : diag::warn_static_main) 10852 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10853 if (FD->isInlineSpecified()) 10854 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10855 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10856 if (DS.isNoreturnSpecified()) { 10857 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10858 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10859 Diag(NoreturnLoc, diag::ext_noreturn_main); 10860 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10861 << FixItHint::CreateRemoval(NoreturnRange); 10862 } 10863 if (FD->isConstexpr()) { 10864 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10865 << FD->isConsteval() 10866 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10867 FD->setConstexprKind(CSK_unspecified); 10868 } 10869 10870 if (getLangOpts().OpenCL) { 10871 Diag(FD->getLocation(), diag::err_opencl_no_main) 10872 << FD->hasAttr<OpenCLKernelAttr>(); 10873 FD->setInvalidDecl(); 10874 return; 10875 } 10876 10877 QualType T = FD->getType(); 10878 assert(T->isFunctionType() && "function decl is not of function type"); 10879 const FunctionType* FT = T->castAs<FunctionType>(); 10880 10881 // Set default calling convention for main() 10882 if (FT->getCallConv() != CC_C) { 10883 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10884 FD->setType(QualType(FT, 0)); 10885 T = Context.getCanonicalType(FD->getType()); 10886 } 10887 10888 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10889 // In C with GNU extensions we allow main() to have non-integer return 10890 // type, but we should warn about the extension, and we disable the 10891 // implicit-return-zero rule. 10892 10893 // GCC in C mode accepts qualified 'int'. 10894 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10895 FD->setHasImplicitReturnZero(true); 10896 else { 10897 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10898 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10899 if (RTRange.isValid()) 10900 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10901 << FixItHint::CreateReplacement(RTRange, "int"); 10902 } 10903 } else { 10904 // In C and C++, main magically returns 0 if you fall off the end; 10905 // set the flag which tells us that. 10906 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10907 10908 // All the standards say that main() should return 'int'. 10909 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10910 FD->setHasImplicitReturnZero(true); 10911 else { 10912 // Otherwise, this is just a flat-out error. 10913 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10914 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10915 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10916 : FixItHint()); 10917 FD->setInvalidDecl(true); 10918 } 10919 } 10920 10921 // Treat protoless main() as nullary. 10922 if (isa<FunctionNoProtoType>(FT)) return; 10923 10924 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10925 unsigned nparams = FTP->getNumParams(); 10926 assert(FD->getNumParams() == nparams); 10927 10928 bool HasExtraParameters = (nparams > 3); 10929 10930 if (FTP->isVariadic()) { 10931 Diag(FD->getLocation(), diag::ext_variadic_main); 10932 // FIXME: if we had information about the location of the ellipsis, we 10933 // could add a FixIt hint to remove it as a parameter. 10934 } 10935 10936 // Darwin passes an undocumented fourth argument of type char**. If 10937 // other platforms start sprouting these, the logic below will start 10938 // getting shifty. 10939 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10940 HasExtraParameters = false; 10941 10942 if (HasExtraParameters) { 10943 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10944 FD->setInvalidDecl(true); 10945 nparams = 3; 10946 } 10947 10948 // FIXME: a lot of the following diagnostics would be improved 10949 // if we had some location information about types. 10950 10951 QualType CharPP = 10952 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10953 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10954 10955 for (unsigned i = 0; i < nparams; ++i) { 10956 QualType AT = FTP->getParamType(i); 10957 10958 bool mismatch = true; 10959 10960 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10961 mismatch = false; 10962 else if (Expected[i] == CharPP) { 10963 // As an extension, the following forms are okay: 10964 // char const ** 10965 // char const * const * 10966 // char * const * 10967 10968 QualifierCollector qs; 10969 const PointerType* PT; 10970 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10971 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10972 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10973 Context.CharTy)) { 10974 qs.removeConst(); 10975 mismatch = !qs.empty(); 10976 } 10977 } 10978 10979 if (mismatch) { 10980 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10981 // TODO: suggest replacing given type with expected type 10982 FD->setInvalidDecl(true); 10983 } 10984 } 10985 10986 if (nparams == 1 && !FD->isInvalidDecl()) { 10987 Diag(FD->getLocation(), diag::warn_main_one_arg); 10988 } 10989 10990 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10991 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10992 FD->setInvalidDecl(); 10993 } 10994 } 10995 10996 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10997 QualType T = FD->getType(); 10998 assert(T->isFunctionType() && "function decl is not of function type"); 10999 const FunctionType *FT = T->castAs<FunctionType>(); 11000 11001 // Set an implicit return of 'zero' if the function can return some integral, 11002 // enumeration, pointer or nullptr type. 11003 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11004 FT->getReturnType()->isAnyPointerType() || 11005 FT->getReturnType()->isNullPtrType()) 11006 // DllMain is exempt because a return value of zero means it failed. 11007 if (FD->getName() != "DllMain") 11008 FD->setHasImplicitReturnZero(true); 11009 11010 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11011 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11012 FD->setInvalidDecl(); 11013 } 11014 } 11015 11016 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11017 // FIXME: Need strict checking. In C89, we need to check for 11018 // any assignment, increment, decrement, function-calls, or 11019 // commas outside of a sizeof. In C99, it's the same list, 11020 // except that the aforementioned are allowed in unevaluated 11021 // expressions. Everything else falls under the 11022 // "may accept other forms of constant expressions" exception. 11023 // (We never end up here for C++, so the constant expression 11024 // rules there don't matter.) 11025 const Expr *Culprit; 11026 if (Init->isConstantInitializer(Context, false, &Culprit)) 11027 return false; 11028 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11029 << Culprit->getSourceRange(); 11030 return true; 11031 } 11032 11033 namespace { 11034 // Visits an initialization expression to see if OrigDecl is evaluated in 11035 // its own initialization and throws a warning if it does. 11036 class SelfReferenceChecker 11037 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11038 Sema &S; 11039 Decl *OrigDecl; 11040 bool isRecordType; 11041 bool isPODType; 11042 bool isReferenceType; 11043 11044 bool isInitList; 11045 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11046 11047 public: 11048 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11049 11050 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11051 S(S), OrigDecl(OrigDecl) { 11052 isPODType = false; 11053 isRecordType = false; 11054 isReferenceType = false; 11055 isInitList = false; 11056 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11057 isPODType = VD->getType().isPODType(S.Context); 11058 isRecordType = VD->getType()->isRecordType(); 11059 isReferenceType = VD->getType()->isReferenceType(); 11060 } 11061 } 11062 11063 // For most expressions, just call the visitor. For initializer lists, 11064 // track the index of the field being initialized since fields are 11065 // initialized in order allowing use of previously initialized fields. 11066 void CheckExpr(Expr *E) { 11067 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11068 if (!InitList) { 11069 Visit(E); 11070 return; 11071 } 11072 11073 // Track and increment the index here. 11074 isInitList = true; 11075 InitFieldIndex.push_back(0); 11076 for (auto Child : InitList->children()) { 11077 CheckExpr(cast<Expr>(Child)); 11078 ++InitFieldIndex.back(); 11079 } 11080 InitFieldIndex.pop_back(); 11081 } 11082 11083 // Returns true if MemberExpr is checked and no further checking is needed. 11084 // Returns false if additional checking is required. 11085 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11086 llvm::SmallVector<FieldDecl*, 4> Fields; 11087 Expr *Base = E; 11088 bool ReferenceField = false; 11089 11090 // Get the field members used. 11091 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11092 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11093 if (!FD) 11094 return false; 11095 Fields.push_back(FD); 11096 if (FD->getType()->isReferenceType()) 11097 ReferenceField = true; 11098 Base = ME->getBase()->IgnoreParenImpCasts(); 11099 } 11100 11101 // Keep checking only if the base Decl is the same. 11102 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11103 if (!DRE || DRE->getDecl() != OrigDecl) 11104 return false; 11105 11106 // A reference field can be bound to an unininitialized field. 11107 if (CheckReference && !ReferenceField) 11108 return true; 11109 11110 // Convert FieldDecls to their index number. 11111 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11112 for (const FieldDecl *I : llvm::reverse(Fields)) 11113 UsedFieldIndex.push_back(I->getFieldIndex()); 11114 11115 // See if a warning is needed by checking the first difference in index 11116 // numbers. If field being used has index less than the field being 11117 // initialized, then the use is safe. 11118 for (auto UsedIter = UsedFieldIndex.begin(), 11119 UsedEnd = UsedFieldIndex.end(), 11120 OrigIter = InitFieldIndex.begin(), 11121 OrigEnd = InitFieldIndex.end(); 11122 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11123 if (*UsedIter < *OrigIter) 11124 return true; 11125 if (*UsedIter > *OrigIter) 11126 break; 11127 } 11128 11129 // TODO: Add a different warning which will print the field names. 11130 HandleDeclRefExpr(DRE); 11131 return true; 11132 } 11133 11134 // For most expressions, the cast is directly above the DeclRefExpr. 11135 // For conditional operators, the cast can be outside the conditional 11136 // operator if both expressions are DeclRefExpr's. 11137 void HandleValue(Expr *E) { 11138 E = E->IgnoreParens(); 11139 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11140 HandleDeclRefExpr(DRE); 11141 return; 11142 } 11143 11144 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11145 Visit(CO->getCond()); 11146 HandleValue(CO->getTrueExpr()); 11147 HandleValue(CO->getFalseExpr()); 11148 return; 11149 } 11150 11151 if (BinaryConditionalOperator *BCO = 11152 dyn_cast<BinaryConditionalOperator>(E)) { 11153 Visit(BCO->getCond()); 11154 HandleValue(BCO->getFalseExpr()); 11155 return; 11156 } 11157 11158 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11159 HandleValue(OVE->getSourceExpr()); 11160 return; 11161 } 11162 11163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11164 if (BO->getOpcode() == BO_Comma) { 11165 Visit(BO->getLHS()); 11166 HandleValue(BO->getRHS()); 11167 return; 11168 } 11169 } 11170 11171 if (isa<MemberExpr>(E)) { 11172 if (isInitList) { 11173 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11174 false /*CheckReference*/)) 11175 return; 11176 } 11177 11178 Expr *Base = E->IgnoreParenImpCasts(); 11179 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11180 // Check for static member variables and don't warn on them. 11181 if (!isa<FieldDecl>(ME->getMemberDecl())) 11182 return; 11183 Base = ME->getBase()->IgnoreParenImpCasts(); 11184 } 11185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11186 HandleDeclRefExpr(DRE); 11187 return; 11188 } 11189 11190 Visit(E); 11191 } 11192 11193 // Reference types not handled in HandleValue are handled here since all 11194 // uses of references are bad, not just r-value uses. 11195 void VisitDeclRefExpr(DeclRefExpr *E) { 11196 if (isReferenceType) 11197 HandleDeclRefExpr(E); 11198 } 11199 11200 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11201 if (E->getCastKind() == CK_LValueToRValue) { 11202 HandleValue(E->getSubExpr()); 11203 return; 11204 } 11205 11206 Inherited::VisitImplicitCastExpr(E); 11207 } 11208 11209 void VisitMemberExpr(MemberExpr *E) { 11210 if (isInitList) { 11211 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11212 return; 11213 } 11214 11215 // Don't warn on arrays since they can be treated as pointers. 11216 if (E->getType()->canDecayToPointerType()) return; 11217 11218 // Warn when a non-static method call is followed by non-static member 11219 // field accesses, which is followed by a DeclRefExpr. 11220 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11221 bool Warn = (MD && !MD->isStatic()); 11222 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11223 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11224 if (!isa<FieldDecl>(ME->getMemberDecl())) 11225 Warn = false; 11226 Base = ME->getBase()->IgnoreParenImpCasts(); 11227 } 11228 11229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11230 if (Warn) 11231 HandleDeclRefExpr(DRE); 11232 return; 11233 } 11234 11235 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11236 // Visit that expression. 11237 Visit(Base); 11238 } 11239 11240 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11241 Expr *Callee = E->getCallee(); 11242 11243 if (isa<UnresolvedLookupExpr>(Callee)) 11244 return Inherited::VisitCXXOperatorCallExpr(E); 11245 11246 Visit(Callee); 11247 for (auto Arg: E->arguments()) 11248 HandleValue(Arg->IgnoreParenImpCasts()); 11249 } 11250 11251 void VisitUnaryOperator(UnaryOperator *E) { 11252 // For POD record types, addresses of its own members are well-defined. 11253 if (E->getOpcode() == UO_AddrOf && isRecordType && 11254 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11255 if (!isPODType) 11256 HandleValue(E->getSubExpr()); 11257 return; 11258 } 11259 11260 if (E->isIncrementDecrementOp()) { 11261 HandleValue(E->getSubExpr()); 11262 return; 11263 } 11264 11265 Inherited::VisitUnaryOperator(E); 11266 } 11267 11268 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11269 11270 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11271 if (E->getConstructor()->isCopyConstructor()) { 11272 Expr *ArgExpr = E->getArg(0); 11273 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11274 if (ILE->getNumInits() == 1) 11275 ArgExpr = ILE->getInit(0); 11276 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11277 if (ICE->getCastKind() == CK_NoOp) 11278 ArgExpr = ICE->getSubExpr(); 11279 HandleValue(ArgExpr); 11280 return; 11281 } 11282 Inherited::VisitCXXConstructExpr(E); 11283 } 11284 11285 void VisitCallExpr(CallExpr *E) { 11286 // Treat std::move as a use. 11287 if (E->isCallToStdMove()) { 11288 HandleValue(E->getArg(0)); 11289 return; 11290 } 11291 11292 Inherited::VisitCallExpr(E); 11293 } 11294 11295 void VisitBinaryOperator(BinaryOperator *E) { 11296 if (E->isCompoundAssignmentOp()) { 11297 HandleValue(E->getLHS()); 11298 Visit(E->getRHS()); 11299 return; 11300 } 11301 11302 Inherited::VisitBinaryOperator(E); 11303 } 11304 11305 // A custom visitor for BinaryConditionalOperator is needed because the 11306 // regular visitor would check the condition and true expression separately 11307 // but both point to the same place giving duplicate diagnostics. 11308 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11309 Visit(E->getCond()); 11310 Visit(E->getFalseExpr()); 11311 } 11312 11313 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11314 Decl* ReferenceDecl = DRE->getDecl(); 11315 if (OrigDecl != ReferenceDecl) return; 11316 unsigned diag; 11317 if (isReferenceType) { 11318 diag = diag::warn_uninit_self_reference_in_reference_init; 11319 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11320 diag = diag::warn_static_self_reference_in_init; 11321 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11322 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11323 DRE->getDecl()->getType()->isRecordType()) { 11324 diag = diag::warn_uninit_self_reference_in_init; 11325 } else { 11326 // Local variables will be handled by the CFG analysis. 11327 return; 11328 } 11329 11330 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11331 S.PDiag(diag) 11332 << DRE->getDecl() << OrigDecl->getLocation() 11333 << DRE->getSourceRange()); 11334 } 11335 }; 11336 11337 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11338 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11339 bool DirectInit) { 11340 // Parameters arguments are occassionially constructed with itself, 11341 // for instance, in recursive functions. Skip them. 11342 if (isa<ParmVarDecl>(OrigDecl)) 11343 return; 11344 11345 E = E->IgnoreParens(); 11346 11347 // Skip checking T a = a where T is not a record or reference type. 11348 // Doing so is a way to silence uninitialized warnings. 11349 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11350 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11351 if (ICE->getCastKind() == CK_LValueToRValue) 11352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11353 if (DRE->getDecl() == OrigDecl) 11354 return; 11355 11356 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11357 } 11358 } // end anonymous namespace 11359 11360 namespace { 11361 // Simple wrapper to add the name of a variable or (if no variable is 11362 // available) a DeclarationName into a diagnostic. 11363 struct VarDeclOrName { 11364 VarDecl *VDecl; 11365 DeclarationName Name; 11366 11367 friend const Sema::SemaDiagnosticBuilder & 11368 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11369 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11370 } 11371 }; 11372 } // end anonymous namespace 11373 11374 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11375 DeclarationName Name, QualType Type, 11376 TypeSourceInfo *TSI, 11377 SourceRange Range, bool DirectInit, 11378 Expr *Init) { 11379 bool IsInitCapture = !VDecl; 11380 assert((!VDecl || !VDecl->isInitCapture()) && 11381 "init captures are expected to be deduced prior to initialization"); 11382 11383 VarDeclOrName VN{VDecl, Name}; 11384 11385 DeducedType *Deduced = Type->getContainedDeducedType(); 11386 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11387 11388 // C++11 [dcl.spec.auto]p3 11389 if (!Init) { 11390 assert(VDecl && "no init for init capture deduction?"); 11391 11392 // Except for class argument deduction, and then for an initializing 11393 // declaration only, i.e. no static at class scope or extern. 11394 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11395 VDecl->hasExternalStorage() || 11396 VDecl->isStaticDataMember()) { 11397 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11398 << VDecl->getDeclName() << Type; 11399 return QualType(); 11400 } 11401 } 11402 11403 ArrayRef<Expr*> DeduceInits; 11404 if (Init) 11405 DeduceInits = Init; 11406 11407 if (DirectInit) { 11408 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11409 DeduceInits = PL->exprs(); 11410 } 11411 11412 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11413 assert(VDecl && "non-auto type for init capture deduction?"); 11414 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11415 InitializationKind Kind = InitializationKind::CreateForInit( 11416 VDecl->getLocation(), DirectInit, Init); 11417 // FIXME: Initialization should not be taking a mutable list of inits. 11418 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11419 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11420 InitsCopy); 11421 } 11422 11423 if (DirectInit) { 11424 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11425 DeduceInits = IL->inits(); 11426 } 11427 11428 // Deduction only works if we have exactly one source expression. 11429 if (DeduceInits.empty()) { 11430 // It isn't possible to write this directly, but it is possible to 11431 // end up in this situation with "auto x(some_pack...);" 11432 Diag(Init->getBeginLoc(), IsInitCapture 11433 ? diag::err_init_capture_no_expression 11434 : diag::err_auto_var_init_no_expression) 11435 << VN << Type << Range; 11436 return QualType(); 11437 } 11438 11439 if (DeduceInits.size() > 1) { 11440 Diag(DeduceInits[1]->getBeginLoc(), 11441 IsInitCapture ? diag::err_init_capture_multiple_expressions 11442 : diag::err_auto_var_init_multiple_expressions) 11443 << VN << Type << Range; 11444 return QualType(); 11445 } 11446 11447 Expr *DeduceInit = DeduceInits[0]; 11448 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11449 Diag(Init->getBeginLoc(), IsInitCapture 11450 ? diag::err_init_capture_paren_braces 11451 : diag::err_auto_var_init_paren_braces) 11452 << isa<InitListExpr>(Init) << VN << Type << Range; 11453 return QualType(); 11454 } 11455 11456 // Expressions default to 'id' when we're in a debugger. 11457 bool DefaultedAnyToId = false; 11458 if (getLangOpts().DebuggerCastResultToId && 11459 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11460 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11461 if (Result.isInvalid()) { 11462 return QualType(); 11463 } 11464 Init = Result.get(); 11465 DefaultedAnyToId = true; 11466 } 11467 11468 // C++ [dcl.decomp]p1: 11469 // If the assignment-expression [...] has array type A and no ref-qualifier 11470 // is present, e has type cv A 11471 if (VDecl && isa<DecompositionDecl>(VDecl) && 11472 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11473 DeduceInit->getType()->isConstantArrayType()) 11474 return Context.getQualifiedType(DeduceInit->getType(), 11475 Type.getQualifiers()); 11476 11477 QualType DeducedType; 11478 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11479 if (!IsInitCapture) 11480 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11481 else if (isa<InitListExpr>(Init)) 11482 Diag(Range.getBegin(), 11483 diag::err_init_capture_deduction_failure_from_init_list) 11484 << VN 11485 << (DeduceInit->getType().isNull() ? TSI->getType() 11486 : DeduceInit->getType()) 11487 << DeduceInit->getSourceRange(); 11488 else 11489 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11490 << VN << TSI->getType() 11491 << (DeduceInit->getType().isNull() ? TSI->getType() 11492 : DeduceInit->getType()) 11493 << DeduceInit->getSourceRange(); 11494 } 11495 11496 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11497 // 'id' instead of a specific object type prevents most of our usual 11498 // checks. 11499 // We only want to warn outside of template instantiations, though: 11500 // inside a template, the 'id' could have come from a parameter. 11501 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11502 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11503 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11504 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11505 } 11506 11507 return DeducedType; 11508 } 11509 11510 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11511 Expr *Init) { 11512 assert(!Init || !Init->containsErrors()); 11513 QualType DeducedType = deduceVarTypeFromInitializer( 11514 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11515 VDecl->getSourceRange(), DirectInit, Init); 11516 if (DeducedType.isNull()) { 11517 VDecl->setInvalidDecl(); 11518 return true; 11519 } 11520 11521 VDecl->setType(DeducedType); 11522 assert(VDecl->isLinkageValid()); 11523 11524 // In ARC, infer lifetime. 11525 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11526 VDecl->setInvalidDecl(); 11527 11528 if (getLangOpts().OpenCL) 11529 deduceOpenCLAddressSpace(VDecl); 11530 11531 // If this is a redeclaration, check that the type we just deduced matches 11532 // the previously declared type. 11533 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11534 // We never need to merge the type, because we cannot form an incomplete 11535 // array of auto, nor deduce such a type. 11536 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11537 } 11538 11539 // Check the deduced type is valid for a variable declaration. 11540 CheckVariableDeclarationType(VDecl); 11541 return VDecl->isInvalidDecl(); 11542 } 11543 11544 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11545 SourceLocation Loc) { 11546 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11547 Init = EWC->getSubExpr(); 11548 11549 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11550 Init = CE->getSubExpr(); 11551 11552 QualType InitType = Init->getType(); 11553 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11554 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11555 "shouldn't be called if type doesn't have a non-trivial C struct"); 11556 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11557 for (auto I : ILE->inits()) { 11558 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11559 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11560 continue; 11561 SourceLocation SL = I->getExprLoc(); 11562 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11563 } 11564 return; 11565 } 11566 11567 if (isa<ImplicitValueInitExpr>(Init)) { 11568 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11569 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11570 NTCUK_Init); 11571 } else { 11572 // Assume all other explicit initializers involving copying some existing 11573 // object. 11574 // TODO: ignore any explicit initializers where we can guarantee 11575 // copy-elision. 11576 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11577 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11578 } 11579 } 11580 11581 namespace { 11582 11583 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11584 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11585 // in the source code or implicitly by the compiler if it is in a union 11586 // defined in a system header and has non-trivial ObjC ownership 11587 // qualifications. We don't want those fields to participate in determining 11588 // whether the containing union is non-trivial. 11589 return FD->hasAttr<UnavailableAttr>(); 11590 } 11591 11592 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11593 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11594 void> { 11595 using Super = 11596 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11597 void>; 11598 11599 DiagNonTrivalCUnionDefaultInitializeVisitor( 11600 QualType OrigTy, SourceLocation OrigLoc, 11601 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11602 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11603 11604 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11605 const FieldDecl *FD, bool InNonTrivialUnion) { 11606 if (const auto *AT = S.Context.getAsArrayType(QT)) 11607 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11608 InNonTrivialUnion); 11609 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11610 } 11611 11612 void visitARCStrong(QualType QT, const FieldDecl *FD, 11613 bool InNonTrivialUnion) { 11614 if (InNonTrivialUnion) 11615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11616 << 1 << 0 << QT << FD->getName(); 11617 } 11618 11619 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11620 if (InNonTrivialUnion) 11621 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11622 << 1 << 0 << QT << FD->getName(); 11623 } 11624 11625 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11626 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11627 if (RD->isUnion()) { 11628 if (OrigLoc.isValid()) { 11629 bool IsUnion = false; 11630 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11631 IsUnion = OrigRD->isUnion(); 11632 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11633 << 0 << OrigTy << IsUnion << UseContext; 11634 // Reset OrigLoc so that this diagnostic is emitted only once. 11635 OrigLoc = SourceLocation(); 11636 } 11637 InNonTrivialUnion = true; 11638 } 11639 11640 if (InNonTrivialUnion) 11641 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11642 << 0 << 0 << QT.getUnqualifiedType() << ""; 11643 11644 for (const FieldDecl *FD : RD->fields()) 11645 if (!shouldIgnoreForRecordTriviality(FD)) 11646 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11647 } 11648 11649 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11650 11651 // The non-trivial C union type or the struct/union type that contains a 11652 // non-trivial C union. 11653 QualType OrigTy; 11654 SourceLocation OrigLoc; 11655 Sema::NonTrivialCUnionContext UseContext; 11656 Sema &S; 11657 }; 11658 11659 struct DiagNonTrivalCUnionDestructedTypeVisitor 11660 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11661 using Super = 11662 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11663 11664 DiagNonTrivalCUnionDestructedTypeVisitor( 11665 QualType OrigTy, SourceLocation OrigLoc, 11666 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11667 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11668 11669 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11670 const FieldDecl *FD, bool InNonTrivialUnion) { 11671 if (const auto *AT = S.Context.getAsArrayType(QT)) 11672 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11673 InNonTrivialUnion); 11674 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11675 } 11676 11677 void visitARCStrong(QualType QT, const FieldDecl *FD, 11678 bool InNonTrivialUnion) { 11679 if (InNonTrivialUnion) 11680 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11681 << 1 << 1 << QT << FD->getName(); 11682 } 11683 11684 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11685 if (InNonTrivialUnion) 11686 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11687 << 1 << 1 << QT << FD->getName(); 11688 } 11689 11690 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11691 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11692 if (RD->isUnion()) { 11693 if (OrigLoc.isValid()) { 11694 bool IsUnion = false; 11695 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11696 IsUnion = OrigRD->isUnion(); 11697 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11698 << 1 << OrigTy << IsUnion << UseContext; 11699 // Reset OrigLoc so that this diagnostic is emitted only once. 11700 OrigLoc = SourceLocation(); 11701 } 11702 InNonTrivialUnion = true; 11703 } 11704 11705 if (InNonTrivialUnion) 11706 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11707 << 0 << 1 << QT.getUnqualifiedType() << ""; 11708 11709 for (const FieldDecl *FD : RD->fields()) 11710 if (!shouldIgnoreForRecordTriviality(FD)) 11711 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11712 } 11713 11714 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11715 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11716 bool InNonTrivialUnion) {} 11717 11718 // The non-trivial C union type or the struct/union type that contains a 11719 // non-trivial C union. 11720 QualType OrigTy; 11721 SourceLocation OrigLoc; 11722 Sema::NonTrivialCUnionContext UseContext; 11723 Sema &S; 11724 }; 11725 11726 struct DiagNonTrivalCUnionCopyVisitor 11727 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11728 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11729 11730 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11731 Sema::NonTrivialCUnionContext UseContext, 11732 Sema &S) 11733 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11734 11735 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11736 const FieldDecl *FD, bool InNonTrivialUnion) { 11737 if (const auto *AT = S.Context.getAsArrayType(QT)) 11738 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11739 InNonTrivialUnion); 11740 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11741 } 11742 11743 void visitARCStrong(QualType QT, const FieldDecl *FD, 11744 bool InNonTrivialUnion) { 11745 if (InNonTrivialUnion) 11746 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11747 << 1 << 2 << QT << FD->getName(); 11748 } 11749 11750 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11751 if (InNonTrivialUnion) 11752 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11753 << 1 << 2 << QT << FD->getName(); 11754 } 11755 11756 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11757 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11758 if (RD->isUnion()) { 11759 if (OrigLoc.isValid()) { 11760 bool IsUnion = false; 11761 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11762 IsUnion = OrigRD->isUnion(); 11763 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11764 << 2 << OrigTy << IsUnion << UseContext; 11765 // Reset OrigLoc so that this diagnostic is emitted only once. 11766 OrigLoc = SourceLocation(); 11767 } 11768 InNonTrivialUnion = true; 11769 } 11770 11771 if (InNonTrivialUnion) 11772 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11773 << 0 << 2 << QT.getUnqualifiedType() << ""; 11774 11775 for (const FieldDecl *FD : RD->fields()) 11776 if (!shouldIgnoreForRecordTriviality(FD)) 11777 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11778 } 11779 11780 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11781 const FieldDecl *FD, bool InNonTrivialUnion) {} 11782 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11783 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11784 bool InNonTrivialUnion) {} 11785 11786 // The non-trivial C union type or the struct/union type that contains a 11787 // non-trivial C union. 11788 QualType OrigTy; 11789 SourceLocation OrigLoc; 11790 Sema::NonTrivialCUnionContext UseContext; 11791 Sema &S; 11792 }; 11793 11794 } // namespace 11795 11796 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11797 NonTrivialCUnionContext UseContext, 11798 unsigned NonTrivialKind) { 11799 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11800 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11801 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11802 "shouldn't be called if type doesn't have a non-trivial C union"); 11803 11804 if ((NonTrivialKind & NTCUK_Init) && 11805 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11806 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11807 .visit(QT, nullptr, false); 11808 if ((NonTrivialKind & NTCUK_Destruct) && 11809 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11810 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11811 .visit(QT, nullptr, false); 11812 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11813 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11814 .visit(QT, nullptr, false); 11815 } 11816 11817 /// AddInitializerToDecl - Adds the initializer Init to the 11818 /// declaration dcl. If DirectInit is true, this is C++ direct 11819 /// initialization rather than copy initialization. 11820 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11821 // If there is no declaration, there was an error parsing it. Just ignore 11822 // the initializer. 11823 if (!RealDecl || RealDecl->isInvalidDecl()) { 11824 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11825 return; 11826 } 11827 11828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11829 // Pure-specifiers are handled in ActOnPureSpecifier. 11830 Diag(Method->getLocation(), diag::err_member_function_initialization) 11831 << Method->getDeclName() << Init->getSourceRange(); 11832 Method->setInvalidDecl(); 11833 return; 11834 } 11835 11836 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11837 if (!VDecl) { 11838 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11839 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11840 RealDecl->setInvalidDecl(); 11841 return; 11842 } 11843 11844 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11845 if (VDecl->getType()->isUndeducedType()) { 11846 // Attempt typo correction early so that the type of the init expression can 11847 // be deduced based on the chosen correction if the original init contains a 11848 // TypoExpr. 11849 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11850 if (!Res.isUsable()) { 11851 // There are unresolved typos in Init, just drop them. 11852 // FIXME: improve the recovery strategy to preserve the Init. 11853 RealDecl->setInvalidDecl(); 11854 return; 11855 } 11856 if (Res.get()->containsErrors()) { 11857 // Invalidate the decl as we don't know the type for recovery-expr yet. 11858 RealDecl->setInvalidDecl(); 11859 VDecl->setInit(Res.get()); 11860 return; 11861 } 11862 Init = Res.get(); 11863 11864 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11865 return; 11866 } 11867 11868 // dllimport cannot be used on variable definitions. 11869 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11870 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11871 VDecl->setInvalidDecl(); 11872 return; 11873 } 11874 11875 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11876 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11877 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11878 VDecl->setInvalidDecl(); 11879 return; 11880 } 11881 11882 if (!VDecl->getType()->isDependentType()) { 11883 // A definition must end up with a complete type, which means it must be 11884 // complete with the restriction that an array type might be completed by 11885 // the initializer; note that later code assumes this restriction. 11886 QualType BaseDeclType = VDecl->getType(); 11887 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11888 BaseDeclType = Array->getElementType(); 11889 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11890 diag::err_typecheck_decl_incomplete_type)) { 11891 RealDecl->setInvalidDecl(); 11892 return; 11893 } 11894 11895 // The variable can not have an abstract class type. 11896 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11897 diag::err_abstract_type_in_decl, 11898 AbstractVariableType)) 11899 VDecl->setInvalidDecl(); 11900 } 11901 11902 // If adding the initializer will turn this declaration into a definition, 11903 // and we already have a definition for this variable, diagnose or otherwise 11904 // handle the situation. 11905 VarDecl *Def; 11906 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11907 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11908 !VDecl->isThisDeclarationADemotedDefinition() && 11909 checkVarDeclRedefinition(Def, VDecl)) 11910 return; 11911 11912 if (getLangOpts().CPlusPlus) { 11913 // C++ [class.static.data]p4 11914 // If a static data member is of const integral or const 11915 // enumeration type, its declaration in the class definition can 11916 // specify a constant-initializer which shall be an integral 11917 // constant expression (5.19). In that case, the member can appear 11918 // in integral constant expressions. The member shall still be 11919 // defined in a namespace scope if it is used in the program and the 11920 // namespace scope definition shall not contain an initializer. 11921 // 11922 // We already performed a redefinition check above, but for static 11923 // data members we also need to check whether there was an in-class 11924 // declaration with an initializer. 11925 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11926 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11927 << VDecl->getDeclName(); 11928 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11929 diag::note_previous_initializer) 11930 << 0; 11931 return; 11932 } 11933 11934 if (VDecl->hasLocalStorage()) 11935 setFunctionHasBranchProtectedScope(); 11936 11937 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11938 VDecl->setInvalidDecl(); 11939 return; 11940 } 11941 } 11942 11943 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11944 // a kernel function cannot be initialized." 11945 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11946 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11947 VDecl->setInvalidDecl(); 11948 return; 11949 } 11950 11951 // The LoaderUninitialized attribute acts as a definition (of undef). 11952 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11953 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11954 VDecl->setInvalidDecl(); 11955 return; 11956 } 11957 11958 // Get the decls type and save a reference for later, since 11959 // CheckInitializerTypes may change it. 11960 QualType DclT = VDecl->getType(), SavT = DclT; 11961 11962 // Expressions default to 'id' when we're in a debugger 11963 // and we are assigning it to a variable of Objective-C pointer type. 11964 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11965 Init->getType() == Context.UnknownAnyTy) { 11966 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11967 if (Result.isInvalid()) { 11968 VDecl->setInvalidDecl(); 11969 return; 11970 } 11971 Init = Result.get(); 11972 } 11973 11974 // Perform the initialization. 11975 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11976 if (!VDecl->isInvalidDecl()) { 11977 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11978 InitializationKind Kind = InitializationKind::CreateForInit( 11979 VDecl->getLocation(), DirectInit, Init); 11980 11981 MultiExprArg Args = Init; 11982 if (CXXDirectInit) 11983 Args = MultiExprArg(CXXDirectInit->getExprs(), 11984 CXXDirectInit->getNumExprs()); 11985 11986 // Try to correct any TypoExprs in the initialization arguments. 11987 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11988 ExprResult Res = CorrectDelayedTyposInExpr( 11989 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11990 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11991 return Init.Failed() ? ExprError() : E; 11992 }); 11993 if (Res.isInvalid()) { 11994 VDecl->setInvalidDecl(); 11995 } else if (Res.get() != Args[Idx]) { 11996 Args[Idx] = Res.get(); 11997 } 11998 } 11999 if (VDecl->isInvalidDecl()) 12000 return; 12001 12002 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12003 /*TopLevelOfInitList=*/false, 12004 /*TreatUnavailableAsInvalid=*/false); 12005 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12006 if (Result.isInvalid()) { 12007 // If the provied initializer fails to initialize the var decl, 12008 // we attach a recovery expr for better recovery. 12009 auto RecoveryExpr = 12010 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12011 if (RecoveryExpr.get()) 12012 VDecl->setInit(RecoveryExpr.get()); 12013 return; 12014 } 12015 12016 Init = Result.getAs<Expr>(); 12017 } 12018 12019 // Check for self-references within variable initializers. 12020 // Variables declared within a function/method body (except for references) 12021 // are handled by a dataflow analysis. 12022 // This is undefined behavior in C++, but valid in C. 12023 if (getLangOpts().CPlusPlus) { 12024 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12025 VDecl->getType()->isReferenceType()) { 12026 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12027 } 12028 } 12029 12030 // If the type changed, it means we had an incomplete type that was 12031 // completed by the initializer. For example: 12032 // int ary[] = { 1, 3, 5 }; 12033 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12034 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12035 VDecl->setType(DclT); 12036 12037 if (!VDecl->isInvalidDecl()) { 12038 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12039 12040 if (VDecl->hasAttr<BlocksAttr>()) 12041 checkRetainCycles(VDecl, Init); 12042 12043 // It is safe to assign a weak reference into a strong variable. 12044 // Although this code can still have problems: 12045 // id x = self.weakProp; 12046 // id y = self.weakProp; 12047 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12048 // paths through the function. This should be revisited if 12049 // -Wrepeated-use-of-weak is made flow-sensitive. 12050 if (FunctionScopeInfo *FSI = getCurFunction()) 12051 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12052 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12053 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12054 Init->getBeginLoc())) 12055 FSI->markSafeWeakUse(Init); 12056 } 12057 12058 // The initialization is usually a full-expression. 12059 // 12060 // FIXME: If this is a braced initialization of an aggregate, it is not 12061 // an expression, and each individual field initializer is a separate 12062 // full-expression. For instance, in: 12063 // 12064 // struct Temp { ~Temp(); }; 12065 // struct S { S(Temp); }; 12066 // struct T { S a, b; } t = { Temp(), Temp() } 12067 // 12068 // we should destroy the first Temp before constructing the second. 12069 ExprResult Result = 12070 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12071 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12072 if (Result.isInvalid()) { 12073 VDecl->setInvalidDecl(); 12074 return; 12075 } 12076 Init = Result.get(); 12077 12078 // Attach the initializer to the decl. 12079 VDecl->setInit(Init); 12080 12081 if (VDecl->isLocalVarDecl()) { 12082 // Don't check the initializer if the declaration is malformed. 12083 if (VDecl->isInvalidDecl()) { 12084 // do nothing 12085 12086 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12087 // This is true even in C++ for OpenCL. 12088 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12089 CheckForConstantInitializer(Init, DclT); 12090 12091 // Otherwise, C++ does not restrict the initializer. 12092 } else if (getLangOpts().CPlusPlus) { 12093 // do nothing 12094 12095 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12096 // static storage duration shall be constant expressions or string literals. 12097 } else if (VDecl->getStorageClass() == SC_Static) { 12098 CheckForConstantInitializer(Init, DclT); 12099 12100 // C89 is stricter than C99 for aggregate initializers. 12101 // C89 6.5.7p3: All the expressions [...] in an initializer list 12102 // for an object that has aggregate or union type shall be 12103 // constant expressions. 12104 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12105 isa<InitListExpr>(Init)) { 12106 const Expr *Culprit; 12107 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12108 Diag(Culprit->getExprLoc(), 12109 diag::ext_aggregate_init_not_constant) 12110 << Culprit->getSourceRange(); 12111 } 12112 } 12113 12114 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12115 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12116 if (VDecl->hasLocalStorage()) 12117 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12118 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12119 VDecl->getLexicalDeclContext()->isRecord()) { 12120 // This is an in-class initialization for a static data member, e.g., 12121 // 12122 // struct S { 12123 // static const int value = 17; 12124 // }; 12125 12126 // C++ [class.mem]p4: 12127 // A member-declarator can contain a constant-initializer only 12128 // if it declares a static member (9.4) of const integral or 12129 // const enumeration type, see 9.4.2. 12130 // 12131 // C++11 [class.static.data]p3: 12132 // If a non-volatile non-inline const static data member is of integral 12133 // or enumeration type, its declaration in the class definition can 12134 // specify a brace-or-equal-initializer in which every initializer-clause 12135 // that is an assignment-expression is a constant expression. A static 12136 // data member of literal type can be declared in the class definition 12137 // with the constexpr specifier; if so, its declaration shall specify a 12138 // brace-or-equal-initializer in which every initializer-clause that is 12139 // an assignment-expression is a constant expression. 12140 12141 // Do nothing on dependent types. 12142 if (DclT->isDependentType()) { 12143 12144 // Allow any 'static constexpr' members, whether or not they are of literal 12145 // type. We separately check that every constexpr variable is of literal 12146 // type. 12147 } else if (VDecl->isConstexpr()) { 12148 12149 // Require constness. 12150 } else if (!DclT.isConstQualified()) { 12151 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12152 << Init->getSourceRange(); 12153 VDecl->setInvalidDecl(); 12154 12155 // We allow integer constant expressions in all cases. 12156 } else if (DclT->isIntegralOrEnumerationType()) { 12157 // Check whether the expression is a constant expression. 12158 SourceLocation Loc; 12159 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12160 // In C++11, a non-constexpr const static data member with an 12161 // in-class initializer cannot be volatile. 12162 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12163 else if (Init->isValueDependent()) 12164 ; // Nothing to check. 12165 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12166 ; // Ok, it's an ICE! 12167 else if (Init->getType()->isScopedEnumeralType() && 12168 Init->isCXX11ConstantExpr(Context)) 12169 ; // Ok, it is a scoped-enum constant expression. 12170 else if (Init->isEvaluatable(Context)) { 12171 // If we can constant fold the initializer through heroics, accept it, 12172 // but report this as a use of an extension for -pedantic. 12173 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12174 << Init->getSourceRange(); 12175 } else { 12176 // Otherwise, this is some crazy unknown case. Report the issue at the 12177 // location provided by the isIntegerConstantExpr failed check. 12178 Diag(Loc, diag::err_in_class_initializer_non_constant) 12179 << Init->getSourceRange(); 12180 VDecl->setInvalidDecl(); 12181 } 12182 12183 // We allow foldable floating-point constants as an extension. 12184 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12185 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12186 // it anyway and provide a fixit to add the 'constexpr'. 12187 if (getLangOpts().CPlusPlus11) { 12188 Diag(VDecl->getLocation(), 12189 diag::ext_in_class_initializer_float_type_cxx11) 12190 << DclT << Init->getSourceRange(); 12191 Diag(VDecl->getBeginLoc(), 12192 diag::note_in_class_initializer_float_type_cxx11) 12193 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12194 } else { 12195 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12196 << DclT << Init->getSourceRange(); 12197 12198 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12199 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12200 << Init->getSourceRange(); 12201 VDecl->setInvalidDecl(); 12202 } 12203 } 12204 12205 // Suggest adding 'constexpr' in C++11 for literal types. 12206 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12207 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12208 << DclT << Init->getSourceRange() 12209 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12210 VDecl->setConstexpr(true); 12211 12212 } else { 12213 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12214 << DclT << Init->getSourceRange(); 12215 VDecl->setInvalidDecl(); 12216 } 12217 } else if (VDecl->isFileVarDecl()) { 12218 // In C, extern is typically used to avoid tentative definitions when 12219 // declaring variables in headers, but adding an intializer makes it a 12220 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12221 // In C++, extern is often used to give implictly static const variables 12222 // external linkage, so don't warn in that case. If selectany is present, 12223 // this might be header code intended for C and C++ inclusion, so apply the 12224 // C++ rules. 12225 if (VDecl->getStorageClass() == SC_Extern && 12226 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12227 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12228 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12229 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12230 Diag(VDecl->getLocation(), diag::warn_extern_init); 12231 12232 // In Microsoft C++ mode, a const variable defined in namespace scope has 12233 // external linkage by default if the variable is declared with 12234 // __declspec(dllexport). 12235 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12236 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12237 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12238 VDecl->setStorageClass(SC_Extern); 12239 12240 // C99 6.7.8p4. All file scoped initializers need to be constant. 12241 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12242 CheckForConstantInitializer(Init, DclT); 12243 } 12244 12245 QualType InitType = Init->getType(); 12246 if (!InitType.isNull() && 12247 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12248 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12249 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12250 12251 // We will represent direct-initialization similarly to copy-initialization: 12252 // int x(1); -as-> int x = 1; 12253 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12254 // 12255 // Clients that want to distinguish between the two forms, can check for 12256 // direct initializer using VarDecl::getInitStyle(). 12257 // A major benefit is that clients that don't particularly care about which 12258 // exactly form was it (like the CodeGen) can handle both cases without 12259 // special case code. 12260 12261 // C++ 8.5p11: 12262 // The form of initialization (using parentheses or '=') is generally 12263 // insignificant, but does matter when the entity being initialized has a 12264 // class type. 12265 if (CXXDirectInit) { 12266 assert(DirectInit && "Call-style initializer must be direct init."); 12267 VDecl->setInitStyle(VarDecl::CallInit); 12268 } else if (DirectInit) { 12269 // This must be list-initialization. No other way is direct-initialization. 12270 VDecl->setInitStyle(VarDecl::ListInit); 12271 } 12272 12273 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12274 DeclsToCheckForDeferredDiags.push_back(VDecl); 12275 CheckCompleteVariableDeclaration(VDecl); 12276 } 12277 12278 /// ActOnInitializerError - Given that there was an error parsing an 12279 /// initializer for the given declaration, try to return to some form 12280 /// of sanity. 12281 void Sema::ActOnInitializerError(Decl *D) { 12282 // Our main concern here is re-establishing invariants like "a 12283 // variable's type is either dependent or complete". 12284 if (!D || D->isInvalidDecl()) return; 12285 12286 VarDecl *VD = dyn_cast<VarDecl>(D); 12287 if (!VD) return; 12288 12289 // Bindings are not usable if we can't make sense of the initializer. 12290 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12291 for (auto *BD : DD->bindings()) 12292 BD->setInvalidDecl(); 12293 12294 // Auto types are meaningless if we can't make sense of the initializer. 12295 if (ParsingInitForAutoVars.count(D)) { 12296 D->setInvalidDecl(); 12297 return; 12298 } 12299 12300 QualType Ty = VD->getType(); 12301 if (Ty->isDependentType()) return; 12302 12303 // Require a complete type. 12304 if (RequireCompleteType(VD->getLocation(), 12305 Context.getBaseElementType(Ty), 12306 diag::err_typecheck_decl_incomplete_type)) { 12307 VD->setInvalidDecl(); 12308 return; 12309 } 12310 12311 // Require a non-abstract type. 12312 if (RequireNonAbstractType(VD->getLocation(), Ty, 12313 diag::err_abstract_type_in_decl, 12314 AbstractVariableType)) { 12315 VD->setInvalidDecl(); 12316 return; 12317 } 12318 12319 // Don't bother complaining about constructors or destructors, 12320 // though. 12321 } 12322 12323 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12324 // If there is no declaration, there was an error parsing it. Just ignore it. 12325 if (!RealDecl) 12326 return; 12327 12328 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12329 QualType Type = Var->getType(); 12330 12331 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12332 if (isa<DecompositionDecl>(RealDecl)) { 12333 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12334 Var->setInvalidDecl(); 12335 return; 12336 } 12337 12338 if (Type->isUndeducedType() && 12339 DeduceVariableDeclarationType(Var, false, nullptr)) 12340 return; 12341 12342 // C++11 [class.static.data]p3: A static data member can be declared with 12343 // the constexpr specifier; if so, its declaration shall specify 12344 // a brace-or-equal-initializer. 12345 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12346 // the definition of a variable [...] or the declaration of a static data 12347 // member. 12348 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12349 !Var->isThisDeclarationADemotedDefinition()) { 12350 if (Var->isStaticDataMember()) { 12351 // C++1z removes the relevant rule; the in-class declaration is always 12352 // a definition there. 12353 if (!getLangOpts().CPlusPlus17 && 12354 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12355 Diag(Var->getLocation(), 12356 diag::err_constexpr_static_mem_var_requires_init) 12357 << Var->getDeclName(); 12358 Var->setInvalidDecl(); 12359 return; 12360 } 12361 } else { 12362 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12363 Var->setInvalidDecl(); 12364 return; 12365 } 12366 } 12367 12368 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12369 // be initialized. 12370 if (!Var->isInvalidDecl() && 12371 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12372 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12373 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12374 Var->setInvalidDecl(); 12375 return; 12376 } 12377 12378 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12379 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12380 if (!RD->hasTrivialDefaultConstructor()) { 12381 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12382 Var->setInvalidDecl(); 12383 return; 12384 } 12385 } 12386 if (Var->getStorageClass() == SC_Extern) { 12387 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12388 << Var; 12389 Var->setInvalidDecl(); 12390 return; 12391 } 12392 } 12393 12394 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12395 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12396 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12397 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12398 NTCUC_DefaultInitializedObject, NTCUK_Init); 12399 12400 12401 switch (DefKind) { 12402 case VarDecl::Definition: 12403 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12404 break; 12405 12406 // We have an out-of-line definition of a static data member 12407 // that has an in-class initializer, so we type-check this like 12408 // a declaration. 12409 // 12410 LLVM_FALLTHROUGH; 12411 12412 case VarDecl::DeclarationOnly: 12413 // It's only a declaration. 12414 12415 // Block scope. C99 6.7p7: If an identifier for an object is 12416 // declared with no linkage (C99 6.2.2p6), the type for the 12417 // object shall be complete. 12418 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12419 !Var->hasLinkage() && !Var->isInvalidDecl() && 12420 RequireCompleteType(Var->getLocation(), Type, 12421 diag::err_typecheck_decl_incomplete_type)) 12422 Var->setInvalidDecl(); 12423 12424 // Make sure that the type is not abstract. 12425 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12426 RequireNonAbstractType(Var->getLocation(), Type, 12427 diag::err_abstract_type_in_decl, 12428 AbstractVariableType)) 12429 Var->setInvalidDecl(); 12430 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12431 Var->getStorageClass() == SC_PrivateExtern) { 12432 Diag(Var->getLocation(), diag::warn_private_extern); 12433 Diag(Var->getLocation(), diag::note_private_extern); 12434 } 12435 12436 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12437 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12438 ExternalDeclarations.push_back(Var); 12439 12440 return; 12441 12442 case VarDecl::TentativeDefinition: 12443 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12444 // object that has file scope without an initializer, and without a 12445 // storage-class specifier or with the storage-class specifier "static", 12446 // constitutes a tentative definition. Note: A tentative definition with 12447 // external linkage is valid (C99 6.2.2p5). 12448 if (!Var->isInvalidDecl()) { 12449 if (const IncompleteArrayType *ArrayT 12450 = Context.getAsIncompleteArrayType(Type)) { 12451 if (RequireCompleteSizedType( 12452 Var->getLocation(), ArrayT->getElementType(), 12453 diag::err_array_incomplete_or_sizeless_type)) 12454 Var->setInvalidDecl(); 12455 } else if (Var->getStorageClass() == SC_Static) { 12456 // C99 6.9.2p3: If the declaration of an identifier for an object is 12457 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12458 // declared type shall not be an incomplete type. 12459 // NOTE: code such as the following 12460 // static struct s; 12461 // struct s { int a; }; 12462 // is accepted by gcc. Hence here we issue a warning instead of 12463 // an error and we do not invalidate the static declaration. 12464 // NOTE: to avoid multiple warnings, only check the first declaration. 12465 if (Var->isFirstDecl()) 12466 RequireCompleteType(Var->getLocation(), Type, 12467 diag::ext_typecheck_decl_incomplete_type); 12468 } 12469 } 12470 12471 // Record the tentative definition; we're done. 12472 if (!Var->isInvalidDecl()) 12473 TentativeDefinitions.push_back(Var); 12474 return; 12475 } 12476 12477 // Provide a specific diagnostic for uninitialized variable 12478 // definitions with incomplete array type. 12479 if (Type->isIncompleteArrayType()) { 12480 Diag(Var->getLocation(), 12481 diag::err_typecheck_incomplete_array_needs_initializer); 12482 Var->setInvalidDecl(); 12483 return; 12484 } 12485 12486 // Provide a specific diagnostic for uninitialized variable 12487 // definitions with reference type. 12488 if (Type->isReferenceType()) { 12489 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12490 << Var->getDeclName() 12491 << SourceRange(Var->getLocation(), Var->getLocation()); 12492 Var->setInvalidDecl(); 12493 return; 12494 } 12495 12496 // Do not attempt to type-check the default initializer for a 12497 // variable with dependent type. 12498 if (Type->isDependentType()) 12499 return; 12500 12501 if (Var->isInvalidDecl()) 12502 return; 12503 12504 if (!Var->hasAttr<AliasAttr>()) { 12505 if (RequireCompleteType(Var->getLocation(), 12506 Context.getBaseElementType(Type), 12507 diag::err_typecheck_decl_incomplete_type)) { 12508 Var->setInvalidDecl(); 12509 return; 12510 } 12511 } else { 12512 return; 12513 } 12514 12515 // The variable can not have an abstract class type. 12516 if (RequireNonAbstractType(Var->getLocation(), Type, 12517 diag::err_abstract_type_in_decl, 12518 AbstractVariableType)) { 12519 Var->setInvalidDecl(); 12520 return; 12521 } 12522 12523 // Check for jumps past the implicit initializer. C++0x 12524 // clarifies that this applies to a "variable with automatic 12525 // storage duration", not a "local variable". 12526 // C++11 [stmt.dcl]p3 12527 // A program that jumps from a point where a variable with automatic 12528 // storage duration is not in scope to a point where it is in scope is 12529 // ill-formed unless the variable has scalar type, class type with a 12530 // trivial default constructor and a trivial destructor, a cv-qualified 12531 // version of one of these types, or an array of one of the preceding 12532 // types and is declared without an initializer. 12533 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12534 if (const RecordType *Record 12535 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12536 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12537 // Mark the function (if we're in one) for further checking even if the 12538 // looser rules of C++11 do not require such checks, so that we can 12539 // diagnose incompatibilities with C++98. 12540 if (!CXXRecord->isPOD()) 12541 setFunctionHasBranchProtectedScope(); 12542 } 12543 } 12544 // In OpenCL, we can't initialize objects in the __local address space, 12545 // even implicitly, so don't synthesize an implicit initializer. 12546 if (getLangOpts().OpenCL && 12547 Var->getType().getAddressSpace() == LangAS::opencl_local) 12548 return; 12549 // C++03 [dcl.init]p9: 12550 // If no initializer is specified for an object, and the 12551 // object is of (possibly cv-qualified) non-POD class type (or 12552 // array thereof), the object shall be default-initialized; if 12553 // the object is of const-qualified type, the underlying class 12554 // type shall have a user-declared default 12555 // constructor. Otherwise, if no initializer is specified for 12556 // a non- static object, the object and its subobjects, if 12557 // any, have an indeterminate initial value); if the object 12558 // or any of its subobjects are of const-qualified type, the 12559 // program is ill-formed. 12560 // C++0x [dcl.init]p11: 12561 // If no initializer is specified for an object, the object is 12562 // default-initialized; [...]. 12563 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12564 InitializationKind Kind 12565 = InitializationKind::CreateDefault(Var->getLocation()); 12566 12567 InitializationSequence InitSeq(*this, Entity, Kind, None); 12568 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12569 12570 if (Init.get()) { 12571 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12572 // This is important for template substitution. 12573 Var->setInitStyle(VarDecl::CallInit); 12574 } else if (Init.isInvalid()) { 12575 // If default-init fails, attach a recovery-expr initializer to track 12576 // that initialization was attempted and failed. 12577 auto RecoveryExpr = 12578 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12579 if (RecoveryExpr.get()) 12580 Var->setInit(RecoveryExpr.get()); 12581 } 12582 12583 CheckCompleteVariableDeclaration(Var); 12584 } 12585 } 12586 12587 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12588 // If there is no declaration, there was an error parsing it. Ignore it. 12589 if (!D) 12590 return; 12591 12592 VarDecl *VD = dyn_cast<VarDecl>(D); 12593 if (!VD) { 12594 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12595 D->setInvalidDecl(); 12596 return; 12597 } 12598 12599 VD->setCXXForRangeDecl(true); 12600 12601 // for-range-declaration cannot be given a storage class specifier. 12602 int Error = -1; 12603 switch (VD->getStorageClass()) { 12604 case SC_None: 12605 break; 12606 case SC_Extern: 12607 Error = 0; 12608 break; 12609 case SC_Static: 12610 Error = 1; 12611 break; 12612 case SC_PrivateExtern: 12613 Error = 2; 12614 break; 12615 case SC_Auto: 12616 Error = 3; 12617 break; 12618 case SC_Register: 12619 Error = 4; 12620 break; 12621 } 12622 if (Error != -1) { 12623 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12624 << VD->getDeclName() << Error; 12625 D->setInvalidDecl(); 12626 } 12627 } 12628 12629 StmtResult 12630 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12631 IdentifierInfo *Ident, 12632 ParsedAttributes &Attrs, 12633 SourceLocation AttrEnd) { 12634 // C++1y [stmt.iter]p1: 12635 // A range-based for statement of the form 12636 // for ( for-range-identifier : for-range-initializer ) statement 12637 // is equivalent to 12638 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12639 DeclSpec DS(Attrs.getPool().getFactory()); 12640 12641 const char *PrevSpec; 12642 unsigned DiagID; 12643 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12644 getPrintingPolicy()); 12645 12646 Declarator D(DS, DeclaratorContext::ForContext); 12647 D.SetIdentifier(Ident, IdentLoc); 12648 D.takeAttributes(Attrs, AttrEnd); 12649 12650 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12651 IdentLoc); 12652 Decl *Var = ActOnDeclarator(S, D); 12653 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12654 FinalizeDeclaration(Var); 12655 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12656 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12657 } 12658 12659 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12660 if (var->isInvalidDecl()) return; 12661 12662 if (getLangOpts().OpenCL) { 12663 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12664 // initialiser 12665 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12666 !var->hasInit()) { 12667 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12668 << 1 /*Init*/; 12669 var->setInvalidDecl(); 12670 return; 12671 } 12672 } 12673 12674 // In Objective-C, don't allow jumps past the implicit initialization of a 12675 // local retaining variable. 12676 if (getLangOpts().ObjC && 12677 var->hasLocalStorage()) { 12678 switch (var->getType().getObjCLifetime()) { 12679 case Qualifiers::OCL_None: 12680 case Qualifiers::OCL_ExplicitNone: 12681 case Qualifiers::OCL_Autoreleasing: 12682 break; 12683 12684 case Qualifiers::OCL_Weak: 12685 case Qualifiers::OCL_Strong: 12686 setFunctionHasBranchProtectedScope(); 12687 break; 12688 } 12689 } 12690 12691 if (var->hasLocalStorage() && 12692 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12693 setFunctionHasBranchProtectedScope(); 12694 12695 // Warn about externally-visible variables being defined without a 12696 // prior declaration. We only want to do this for global 12697 // declarations, but we also specifically need to avoid doing it for 12698 // class members because the linkage of an anonymous class can 12699 // change if it's later given a typedef name. 12700 if (var->isThisDeclarationADefinition() && 12701 var->getDeclContext()->getRedeclContext()->isFileContext() && 12702 var->isExternallyVisible() && var->hasLinkage() && 12703 !var->isInline() && !var->getDescribedVarTemplate() && 12704 !isa<VarTemplatePartialSpecializationDecl>(var) && 12705 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12706 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12707 var->getLocation())) { 12708 // Find a previous declaration that's not a definition. 12709 VarDecl *prev = var->getPreviousDecl(); 12710 while (prev && prev->isThisDeclarationADefinition()) 12711 prev = prev->getPreviousDecl(); 12712 12713 if (!prev) { 12714 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12715 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12716 << /* variable */ 0; 12717 } 12718 } 12719 12720 // Cache the result of checking for constant initialization. 12721 Optional<bool> CacheHasConstInit; 12722 const Expr *CacheCulprit = nullptr; 12723 auto checkConstInit = [&]() mutable { 12724 if (!CacheHasConstInit) 12725 CacheHasConstInit = var->getInit()->isConstantInitializer( 12726 Context, var->getType()->isReferenceType(), &CacheCulprit); 12727 return *CacheHasConstInit; 12728 }; 12729 12730 if (var->getTLSKind() == VarDecl::TLS_Static) { 12731 if (var->getType().isDestructedType()) { 12732 // GNU C++98 edits for __thread, [basic.start.term]p3: 12733 // The type of an object with thread storage duration shall not 12734 // have a non-trivial destructor. 12735 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12736 if (getLangOpts().CPlusPlus11) 12737 Diag(var->getLocation(), diag::note_use_thread_local); 12738 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12739 if (!checkConstInit()) { 12740 // GNU C++98 edits for __thread, [basic.start.init]p4: 12741 // An object of thread storage duration shall not require dynamic 12742 // initialization. 12743 // FIXME: Need strict checking here. 12744 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12745 << CacheCulprit->getSourceRange(); 12746 if (getLangOpts().CPlusPlus11) 12747 Diag(var->getLocation(), diag::note_use_thread_local); 12748 } 12749 } 12750 } 12751 12752 // Apply section attributes and pragmas to global variables. 12753 bool GlobalStorage = var->hasGlobalStorage(); 12754 if (GlobalStorage && var->isThisDeclarationADefinition() && 12755 !inTemplateInstantiation()) { 12756 PragmaStack<StringLiteral *> *Stack = nullptr; 12757 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12758 if (var->getType().isConstQualified()) 12759 Stack = &ConstSegStack; 12760 else if (!var->getInit()) { 12761 Stack = &BSSSegStack; 12762 SectionFlags |= ASTContext::PSF_Write; 12763 } else { 12764 Stack = &DataSegStack; 12765 SectionFlags |= ASTContext::PSF_Write; 12766 } 12767 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12768 var->addAttr(SectionAttr::CreateImplicit( 12769 Context, Stack->CurrentValue->getString(), 12770 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12771 SectionAttr::Declspec_allocate)); 12772 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12773 if (UnifySection(SA->getName(), SectionFlags, var)) 12774 var->dropAttr<SectionAttr>(); 12775 12776 // Apply the init_seg attribute if this has an initializer. If the 12777 // initializer turns out to not be dynamic, we'll end up ignoring this 12778 // attribute. 12779 if (CurInitSeg && var->getInit()) 12780 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12781 CurInitSegLoc, 12782 AttributeCommonInfo::AS_Pragma)); 12783 } 12784 12785 // All the following checks are C++ only. 12786 if (!getLangOpts().CPlusPlus) { 12787 // If this variable must be emitted, add it as an initializer for the 12788 // current module. 12789 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12790 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12791 return; 12792 } 12793 12794 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12795 CheckCompleteDecompositionDeclaration(DD); 12796 12797 QualType type = var->getType(); 12798 if (type->isDependentType()) return; 12799 12800 if (var->hasAttr<BlocksAttr>()) 12801 getCurFunction()->addByrefBlockVar(var); 12802 12803 Expr *Init = var->getInit(); 12804 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12805 QualType baseType = Context.getBaseElementType(type); 12806 12807 if (Init && !Init->isValueDependent()) { 12808 if (var->isConstexpr()) { 12809 SmallVector<PartialDiagnosticAt, 8> Notes; 12810 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12811 SourceLocation DiagLoc = var->getLocation(); 12812 // If the note doesn't add any useful information other than a source 12813 // location, fold it into the primary diagnostic. 12814 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12815 diag::note_invalid_subexpr_in_const_expr) { 12816 DiagLoc = Notes[0].first; 12817 Notes.clear(); 12818 } 12819 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12820 << var << Init->getSourceRange(); 12821 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12822 Diag(Notes[I].first, Notes[I].second); 12823 } 12824 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12825 // Check whether the initializer of a const variable of integral or 12826 // enumeration type is an ICE now, since we can't tell whether it was 12827 // initialized by a constant expression if we check later. 12828 var->checkInitIsICE(); 12829 } 12830 12831 // Don't emit further diagnostics about constexpr globals since they 12832 // were just diagnosed. 12833 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12834 // FIXME: Need strict checking in C++03 here. 12835 bool DiagErr = getLangOpts().CPlusPlus11 12836 ? !var->checkInitIsICE() : !checkConstInit(); 12837 if (DiagErr) { 12838 auto *Attr = var->getAttr<ConstInitAttr>(); 12839 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12840 << Init->getSourceRange(); 12841 Diag(Attr->getLocation(), 12842 diag::note_declared_required_constant_init_here) 12843 << Attr->getRange() << Attr->isConstinit(); 12844 if (getLangOpts().CPlusPlus11) { 12845 APValue Value; 12846 SmallVector<PartialDiagnosticAt, 8> Notes; 12847 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12848 for (auto &it : Notes) 12849 Diag(it.first, it.second); 12850 } else { 12851 Diag(CacheCulprit->getExprLoc(), 12852 diag::note_invalid_subexpr_in_const_expr) 12853 << CacheCulprit->getSourceRange(); 12854 } 12855 } 12856 } 12857 else if (!var->isConstexpr() && IsGlobal && 12858 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12859 var->getLocation())) { 12860 // Warn about globals which don't have a constant initializer. Don't 12861 // warn about globals with a non-trivial destructor because we already 12862 // warned about them. 12863 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12864 if (!(RD && !RD->hasTrivialDestructor())) { 12865 if (!checkConstInit()) 12866 Diag(var->getLocation(), diag::warn_global_constructor) 12867 << Init->getSourceRange(); 12868 } 12869 } 12870 } 12871 12872 // Require the destructor. 12873 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12874 FinalizeVarWithDestructor(var, recordType); 12875 12876 // If this variable must be emitted, add it as an initializer for the current 12877 // module. 12878 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12879 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12880 } 12881 12882 /// Determines if a variable's alignment is dependent. 12883 static bool hasDependentAlignment(VarDecl *VD) { 12884 if (VD->getType()->isDependentType()) 12885 return true; 12886 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12887 if (I->isAlignmentDependent()) 12888 return true; 12889 return false; 12890 } 12891 12892 /// Check if VD needs to be dllexport/dllimport due to being in a 12893 /// dllexport/import function. 12894 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12895 assert(VD->isStaticLocal()); 12896 12897 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12898 12899 // Find outermost function when VD is in lambda function. 12900 while (FD && !getDLLAttr(FD) && 12901 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12902 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12903 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12904 } 12905 12906 if (!FD) 12907 return; 12908 12909 // Static locals inherit dll attributes from their function. 12910 if (Attr *A = getDLLAttr(FD)) { 12911 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12912 NewAttr->setInherited(true); 12913 VD->addAttr(NewAttr); 12914 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12915 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12916 NewAttr->setInherited(true); 12917 VD->addAttr(NewAttr); 12918 12919 // Export this function to enforce exporting this static variable even 12920 // if it is not used in this compilation unit. 12921 if (!FD->hasAttr<DLLExportAttr>()) 12922 FD->addAttr(NewAttr); 12923 12924 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12925 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12926 NewAttr->setInherited(true); 12927 VD->addAttr(NewAttr); 12928 } 12929 } 12930 12931 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12932 /// any semantic actions necessary after any initializer has been attached. 12933 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12934 // Note that we are no longer parsing the initializer for this declaration. 12935 ParsingInitForAutoVars.erase(ThisDecl); 12936 12937 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12938 if (!VD) 12939 return; 12940 12941 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12942 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12943 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12944 if (PragmaClangBSSSection.Valid) 12945 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12946 Context, PragmaClangBSSSection.SectionName, 12947 PragmaClangBSSSection.PragmaLocation, 12948 AttributeCommonInfo::AS_Pragma)); 12949 if (PragmaClangDataSection.Valid) 12950 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12951 Context, PragmaClangDataSection.SectionName, 12952 PragmaClangDataSection.PragmaLocation, 12953 AttributeCommonInfo::AS_Pragma)); 12954 if (PragmaClangRodataSection.Valid) 12955 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12956 Context, PragmaClangRodataSection.SectionName, 12957 PragmaClangRodataSection.PragmaLocation, 12958 AttributeCommonInfo::AS_Pragma)); 12959 if (PragmaClangRelroSection.Valid) 12960 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12961 Context, PragmaClangRelroSection.SectionName, 12962 PragmaClangRelroSection.PragmaLocation, 12963 AttributeCommonInfo::AS_Pragma)); 12964 } 12965 12966 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12967 for (auto *BD : DD->bindings()) { 12968 FinalizeDeclaration(BD); 12969 } 12970 } 12971 12972 checkAttributesAfterMerging(*this, *VD); 12973 12974 // Perform TLS alignment check here after attributes attached to the variable 12975 // which may affect the alignment have been processed. Only perform the check 12976 // if the target has a maximum TLS alignment (zero means no constraints). 12977 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12978 // Protect the check so that it's not performed on dependent types and 12979 // dependent alignments (we can't determine the alignment in that case). 12980 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12981 !VD->isInvalidDecl()) { 12982 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12983 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12984 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12985 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12986 << (unsigned)MaxAlignChars.getQuantity(); 12987 } 12988 } 12989 } 12990 12991 if (VD->isStaticLocal()) { 12992 CheckStaticLocalForDllExport(VD); 12993 12994 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12995 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12996 // function, only __shared__ variables or variables without any device 12997 // memory qualifiers may be declared with static storage class. 12998 // Note: It is unclear how a function-scope non-const static variable 12999 // without device memory qualifier is implemented, therefore only static 13000 // const variable without device memory qualifier is allowed. 13001 [&]() { 13002 if (!getLangOpts().CUDA) 13003 return; 13004 if (VD->hasAttr<CUDASharedAttr>()) 13005 return; 13006 if (VD->getType().isConstQualified() && 13007 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13008 return; 13009 if (CUDADiagIfDeviceCode(VD->getLocation(), 13010 diag::err_device_static_local_var) 13011 << CurrentCUDATarget()) 13012 VD->setInvalidDecl(); 13013 }(); 13014 } 13015 } 13016 13017 // Perform check for initializers of device-side global variables. 13018 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13019 // 7.5). We must also apply the same checks to all __shared__ 13020 // variables whether they are local or not. CUDA also allows 13021 // constant initializers for __constant__ and __device__ variables. 13022 if (getLangOpts().CUDA) 13023 checkAllowedCUDAInitializer(VD); 13024 13025 // Grab the dllimport or dllexport attribute off of the VarDecl. 13026 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13027 13028 // Imported static data members cannot be defined out-of-line. 13029 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13030 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13031 VD->isThisDeclarationADefinition()) { 13032 // We allow definitions of dllimport class template static data members 13033 // with a warning. 13034 CXXRecordDecl *Context = 13035 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13036 bool IsClassTemplateMember = 13037 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13038 Context->getDescribedClassTemplate(); 13039 13040 Diag(VD->getLocation(), 13041 IsClassTemplateMember 13042 ? diag::warn_attribute_dllimport_static_field_definition 13043 : diag::err_attribute_dllimport_static_field_definition); 13044 Diag(IA->getLocation(), diag::note_attribute); 13045 if (!IsClassTemplateMember) 13046 VD->setInvalidDecl(); 13047 } 13048 } 13049 13050 // dllimport/dllexport variables cannot be thread local, their TLS index 13051 // isn't exported with the variable. 13052 if (DLLAttr && VD->getTLSKind()) { 13053 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13054 if (F && getDLLAttr(F)) { 13055 assert(VD->isStaticLocal()); 13056 // But if this is a static local in a dlimport/dllexport function, the 13057 // function will never be inlined, which means the var would never be 13058 // imported, so having it marked import/export is safe. 13059 } else { 13060 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13061 << DLLAttr; 13062 VD->setInvalidDecl(); 13063 } 13064 } 13065 13066 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13067 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13068 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13069 VD->dropAttr<UsedAttr>(); 13070 } 13071 } 13072 13073 const DeclContext *DC = VD->getDeclContext(); 13074 // If there's a #pragma GCC visibility in scope, and this isn't a class 13075 // member, set the visibility of this variable. 13076 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13077 AddPushedVisibilityAttribute(VD); 13078 13079 // FIXME: Warn on unused var template partial specializations. 13080 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13081 MarkUnusedFileScopedDecl(VD); 13082 13083 // Now we have parsed the initializer and can update the table of magic 13084 // tag values. 13085 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13086 !VD->getType()->isIntegralOrEnumerationType()) 13087 return; 13088 13089 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13090 const Expr *MagicValueExpr = VD->getInit(); 13091 if (!MagicValueExpr) { 13092 continue; 13093 } 13094 llvm::APSInt MagicValueInt; 13095 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13096 Diag(I->getRange().getBegin(), 13097 diag::err_type_tag_for_datatype_not_ice) 13098 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13099 continue; 13100 } 13101 if (MagicValueInt.getActiveBits() > 64) { 13102 Diag(I->getRange().getBegin(), 13103 diag::err_type_tag_for_datatype_too_large) 13104 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13105 continue; 13106 } 13107 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13108 RegisterTypeTagForDatatype(I->getArgumentKind(), 13109 MagicValue, 13110 I->getMatchingCType(), 13111 I->getLayoutCompatible(), 13112 I->getMustBeNull()); 13113 } 13114 } 13115 13116 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13117 auto *VD = dyn_cast<VarDecl>(DD); 13118 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13119 } 13120 13121 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13122 ArrayRef<Decl *> Group) { 13123 SmallVector<Decl*, 8> Decls; 13124 13125 if (DS.isTypeSpecOwned()) 13126 Decls.push_back(DS.getRepAsDecl()); 13127 13128 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13129 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13130 bool DiagnosedMultipleDecomps = false; 13131 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13132 bool DiagnosedNonDeducedAuto = false; 13133 13134 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13135 if (Decl *D = Group[i]) { 13136 // For declarators, there are some additional syntactic-ish checks we need 13137 // to perform. 13138 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13139 if (!FirstDeclaratorInGroup) 13140 FirstDeclaratorInGroup = DD; 13141 if (!FirstDecompDeclaratorInGroup) 13142 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13143 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13144 !hasDeducedAuto(DD)) 13145 FirstNonDeducedAutoInGroup = DD; 13146 13147 if (FirstDeclaratorInGroup != DD) { 13148 // A decomposition declaration cannot be combined with any other 13149 // declaration in the same group. 13150 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13151 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13152 diag::err_decomp_decl_not_alone) 13153 << FirstDeclaratorInGroup->getSourceRange() 13154 << DD->getSourceRange(); 13155 DiagnosedMultipleDecomps = true; 13156 } 13157 13158 // A declarator that uses 'auto' in any way other than to declare a 13159 // variable with a deduced type cannot be combined with any other 13160 // declarator in the same group. 13161 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13162 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13163 diag::err_auto_non_deduced_not_alone) 13164 << FirstNonDeducedAutoInGroup->getType() 13165 ->hasAutoForTrailingReturnType() 13166 << FirstDeclaratorInGroup->getSourceRange() 13167 << DD->getSourceRange(); 13168 DiagnosedNonDeducedAuto = true; 13169 } 13170 } 13171 } 13172 13173 Decls.push_back(D); 13174 } 13175 } 13176 13177 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13178 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13179 handleTagNumbering(Tag, S); 13180 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13181 getLangOpts().CPlusPlus) 13182 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13183 } 13184 } 13185 13186 return BuildDeclaratorGroup(Decls); 13187 } 13188 13189 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13190 /// group, performing any necessary semantic checking. 13191 Sema::DeclGroupPtrTy 13192 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13193 // C++14 [dcl.spec.auto]p7: (DR1347) 13194 // If the type that replaces the placeholder type is not the same in each 13195 // deduction, the program is ill-formed. 13196 if (Group.size() > 1) { 13197 QualType Deduced; 13198 VarDecl *DeducedDecl = nullptr; 13199 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13200 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13201 if (!D || D->isInvalidDecl()) 13202 break; 13203 DeducedType *DT = D->getType()->getContainedDeducedType(); 13204 if (!DT || DT->getDeducedType().isNull()) 13205 continue; 13206 if (Deduced.isNull()) { 13207 Deduced = DT->getDeducedType(); 13208 DeducedDecl = D; 13209 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13210 auto *AT = dyn_cast<AutoType>(DT); 13211 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13212 diag::err_auto_different_deductions) 13213 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13214 << DeducedDecl->getDeclName() << DT->getDeducedType() 13215 << D->getDeclName(); 13216 if (DeducedDecl->hasInit()) 13217 Dia << DeducedDecl->getInit()->getSourceRange(); 13218 if (D->getInit()) 13219 Dia << D->getInit()->getSourceRange(); 13220 D->setInvalidDecl(); 13221 break; 13222 } 13223 } 13224 } 13225 13226 ActOnDocumentableDecls(Group); 13227 13228 return DeclGroupPtrTy::make( 13229 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13230 } 13231 13232 void Sema::ActOnDocumentableDecl(Decl *D) { 13233 ActOnDocumentableDecls(D); 13234 } 13235 13236 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13237 // Don't parse the comment if Doxygen diagnostics are ignored. 13238 if (Group.empty() || !Group[0]) 13239 return; 13240 13241 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13242 Group[0]->getLocation()) && 13243 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13244 Group[0]->getLocation())) 13245 return; 13246 13247 if (Group.size() >= 2) { 13248 // This is a decl group. Normally it will contain only declarations 13249 // produced from declarator list. But in case we have any definitions or 13250 // additional declaration references: 13251 // 'typedef struct S {} S;' 13252 // 'typedef struct S *S;' 13253 // 'struct S *pS;' 13254 // FinalizeDeclaratorGroup adds these as separate declarations. 13255 Decl *MaybeTagDecl = Group[0]; 13256 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13257 Group = Group.slice(1); 13258 } 13259 } 13260 13261 // FIMXE: We assume every Decl in the group is in the same file. 13262 // This is false when preprocessor constructs the group from decls in 13263 // different files (e. g. macros or #include). 13264 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13265 } 13266 13267 /// Common checks for a parameter-declaration that should apply to both function 13268 /// parameters and non-type template parameters. 13269 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13270 // Check that there are no default arguments inside the type of this 13271 // parameter. 13272 if (getLangOpts().CPlusPlus) 13273 CheckExtraCXXDefaultArguments(D); 13274 13275 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13276 if (D.getCXXScopeSpec().isSet()) { 13277 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13278 << D.getCXXScopeSpec().getRange(); 13279 } 13280 13281 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13282 // simple identifier except [...irrelevant cases...]. 13283 switch (D.getName().getKind()) { 13284 case UnqualifiedIdKind::IK_Identifier: 13285 break; 13286 13287 case UnqualifiedIdKind::IK_OperatorFunctionId: 13288 case UnqualifiedIdKind::IK_ConversionFunctionId: 13289 case UnqualifiedIdKind::IK_LiteralOperatorId: 13290 case UnqualifiedIdKind::IK_ConstructorName: 13291 case UnqualifiedIdKind::IK_DestructorName: 13292 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13293 case UnqualifiedIdKind::IK_DeductionGuideName: 13294 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13295 << GetNameForDeclarator(D).getName(); 13296 break; 13297 13298 case UnqualifiedIdKind::IK_TemplateId: 13299 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13300 // GetNameForDeclarator would not produce a useful name in this case. 13301 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13302 break; 13303 } 13304 } 13305 13306 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13307 /// to introduce parameters into function prototype scope. 13308 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13309 const DeclSpec &DS = D.getDeclSpec(); 13310 13311 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13312 13313 // C++03 [dcl.stc]p2 also permits 'auto'. 13314 StorageClass SC = SC_None; 13315 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13316 SC = SC_Register; 13317 // In C++11, the 'register' storage class specifier is deprecated. 13318 // In C++17, it is not allowed, but we tolerate it as an extension. 13319 if (getLangOpts().CPlusPlus11) { 13320 Diag(DS.getStorageClassSpecLoc(), 13321 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13322 : diag::warn_deprecated_register) 13323 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13324 } 13325 } else if (getLangOpts().CPlusPlus && 13326 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13327 SC = SC_Auto; 13328 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13329 Diag(DS.getStorageClassSpecLoc(), 13330 diag::err_invalid_storage_class_in_func_decl); 13331 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13332 } 13333 13334 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13335 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13336 << DeclSpec::getSpecifierName(TSCS); 13337 if (DS.isInlineSpecified()) 13338 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13339 << getLangOpts().CPlusPlus17; 13340 if (DS.hasConstexprSpecifier()) 13341 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13342 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13343 13344 DiagnoseFunctionSpecifiers(DS); 13345 13346 CheckFunctionOrTemplateParamDeclarator(S, D); 13347 13348 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13349 QualType parmDeclType = TInfo->getType(); 13350 13351 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13352 IdentifierInfo *II = D.getIdentifier(); 13353 if (II) { 13354 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13355 ForVisibleRedeclaration); 13356 LookupName(R, S); 13357 if (R.isSingleResult()) { 13358 NamedDecl *PrevDecl = R.getFoundDecl(); 13359 if (PrevDecl->isTemplateParameter()) { 13360 // Maybe we will complain about the shadowed template parameter. 13361 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13362 // Just pretend that we didn't see the previous declaration. 13363 PrevDecl = nullptr; 13364 } else if (S->isDeclScope(PrevDecl)) { 13365 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13366 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13367 13368 // Recover by removing the name 13369 II = nullptr; 13370 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13371 D.setInvalidType(true); 13372 } 13373 } 13374 } 13375 13376 // Temporarily put parameter variables in the translation unit, not 13377 // the enclosing context. This prevents them from accidentally 13378 // looking like class members in C++. 13379 ParmVarDecl *New = 13380 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13381 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13382 13383 if (D.isInvalidType()) 13384 New->setInvalidDecl(); 13385 13386 assert(S->isFunctionPrototypeScope()); 13387 assert(S->getFunctionPrototypeDepth() >= 1); 13388 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13389 S->getNextFunctionPrototypeIndex()); 13390 13391 // Add the parameter declaration into this scope. 13392 S->AddDecl(New); 13393 if (II) 13394 IdResolver.AddDecl(New); 13395 13396 ProcessDeclAttributes(S, New, D); 13397 13398 if (D.getDeclSpec().isModulePrivateSpecified()) 13399 Diag(New->getLocation(), diag::err_module_private_local) 13400 << 1 << New->getDeclName() 13401 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13402 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13403 13404 if (New->hasAttr<BlocksAttr>()) { 13405 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13406 } 13407 13408 if (getLangOpts().OpenCL) 13409 deduceOpenCLAddressSpace(New); 13410 13411 return New; 13412 } 13413 13414 /// Synthesizes a variable for a parameter arising from a 13415 /// typedef. 13416 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13417 SourceLocation Loc, 13418 QualType T) { 13419 /* FIXME: setting StartLoc == Loc. 13420 Would it be worth to modify callers so as to provide proper source 13421 location for the unnamed parameters, embedding the parameter's type? */ 13422 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13423 T, Context.getTrivialTypeSourceInfo(T, Loc), 13424 SC_None, nullptr); 13425 Param->setImplicit(); 13426 return Param; 13427 } 13428 13429 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13430 // Don't diagnose unused-parameter errors in template instantiations; we 13431 // will already have done so in the template itself. 13432 if (inTemplateInstantiation()) 13433 return; 13434 13435 for (const ParmVarDecl *Parameter : Parameters) { 13436 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13437 !Parameter->hasAttr<UnusedAttr>()) { 13438 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13439 << Parameter->getDeclName(); 13440 } 13441 } 13442 } 13443 13444 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13445 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13446 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13447 return; 13448 13449 // Warn if the return value is pass-by-value and larger than the specified 13450 // threshold. 13451 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13452 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13453 if (Size > LangOpts.NumLargeByValueCopy) 13454 Diag(D->getLocation(), diag::warn_return_value_size) 13455 << D->getDeclName() << Size; 13456 } 13457 13458 // Warn if any parameter is pass-by-value and larger than the specified 13459 // threshold. 13460 for (const ParmVarDecl *Parameter : Parameters) { 13461 QualType T = Parameter->getType(); 13462 if (T->isDependentType() || !T.isPODType(Context)) 13463 continue; 13464 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13465 if (Size > LangOpts.NumLargeByValueCopy) 13466 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13467 << Parameter->getDeclName() << Size; 13468 } 13469 } 13470 13471 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13472 SourceLocation NameLoc, IdentifierInfo *Name, 13473 QualType T, TypeSourceInfo *TSInfo, 13474 StorageClass SC) { 13475 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13476 if (getLangOpts().ObjCAutoRefCount && 13477 T.getObjCLifetime() == Qualifiers::OCL_None && 13478 T->isObjCLifetimeType()) { 13479 13480 Qualifiers::ObjCLifetime lifetime; 13481 13482 // Special cases for arrays: 13483 // - if it's const, use __unsafe_unretained 13484 // - otherwise, it's an error 13485 if (T->isArrayType()) { 13486 if (!T.isConstQualified()) { 13487 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13488 DelayedDiagnostics.add( 13489 sema::DelayedDiagnostic::makeForbiddenType( 13490 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13491 else 13492 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13493 << TSInfo->getTypeLoc().getSourceRange(); 13494 } 13495 lifetime = Qualifiers::OCL_ExplicitNone; 13496 } else { 13497 lifetime = T->getObjCARCImplicitLifetime(); 13498 } 13499 T = Context.getLifetimeQualifiedType(T, lifetime); 13500 } 13501 13502 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13503 Context.getAdjustedParameterType(T), 13504 TSInfo, SC, nullptr); 13505 13506 // Make a note if we created a new pack in the scope of a lambda, so that 13507 // we know that references to that pack must also be expanded within the 13508 // lambda scope. 13509 if (New->isParameterPack()) 13510 if (auto *LSI = getEnclosingLambda()) 13511 LSI->LocalPacks.push_back(New); 13512 13513 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13514 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13515 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13516 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13517 13518 // Parameters can not be abstract class types. 13519 // For record types, this is done by the AbstractClassUsageDiagnoser once 13520 // the class has been completely parsed. 13521 if (!CurContext->isRecord() && 13522 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13523 AbstractParamType)) 13524 New->setInvalidDecl(); 13525 13526 // Parameter declarators cannot be interface types. All ObjC objects are 13527 // passed by reference. 13528 if (T->isObjCObjectType()) { 13529 SourceLocation TypeEndLoc = 13530 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13531 Diag(NameLoc, 13532 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13533 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13534 T = Context.getObjCObjectPointerType(T); 13535 New->setType(T); 13536 } 13537 13538 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13539 // duration shall not be qualified by an address-space qualifier." 13540 // Since all parameters have automatic store duration, they can not have 13541 // an address space. 13542 if (T.getAddressSpace() != LangAS::Default && 13543 // OpenCL allows function arguments declared to be an array of a type 13544 // to be qualified with an address space. 13545 !(getLangOpts().OpenCL && 13546 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13547 Diag(NameLoc, diag::err_arg_with_address_space); 13548 New->setInvalidDecl(); 13549 } 13550 13551 return New; 13552 } 13553 13554 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13555 SourceLocation LocAfterDecls) { 13556 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13557 13558 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13559 // for a K&R function. 13560 if (!FTI.hasPrototype) { 13561 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13562 --i; 13563 if (FTI.Params[i].Param == nullptr) { 13564 SmallString<256> Code; 13565 llvm::raw_svector_ostream(Code) 13566 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13567 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13568 << FTI.Params[i].Ident 13569 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13570 13571 // Implicitly declare the argument as type 'int' for lack of a better 13572 // type. 13573 AttributeFactory attrs; 13574 DeclSpec DS(attrs); 13575 const char* PrevSpec; // unused 13576 unsigned DiagID; // unused 13577 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13578 DiagID, Context.getPrintingPolicy()); 13579 // Use the identifier location for the type source range. 13580 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13581 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13582 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13583 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13584 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13585 } 13586 } 13587 } 13588 } 13589 13590 Decl * 13591 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13592 MultiTemplateParamsArg TemplateParameterLists, 13593 SkipBodyInfo *SkipBody) { 13594 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13595 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13596 Scope *ParentScope = FnBodyScope->getParent(); 13597 13598 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13599 // we define a non-templated function definition, we will create a declaration 13600 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13601 // The base function declaration will have the equivalent of an `omp declare 13602 // variant` annotation which specifies the mangled definition as a 13603 // specialization function under the OpenMP context defined as part of the 13604 // `omp begin declare variant`. 13605 FunctionDecl *BaseFD = nullptr; 13606 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13607 TemplateParameterLists.empty()) 13608 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13609 ParentScope, D); 13610 13611 D.setFunctionDefinitionKind(FDK_Definition); 13612 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13613 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13614 13615 if (BaseFD) 13616 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13617 cast<FunctionDecl>(Dcl), BaseFD); 13618 13619 return Dcl; 13620 } 13621 13622 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13623 Consumer.HandleInlineFunctionDefinition(D); 13624 } 13625 13626 static bool 13627 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13628 const FunctionDecl *&PossiblePrototype) { 13629 // Don't warn about invalid declarations. 13630 if (FD->isInvalidDecl()) 13631 return false; 13632 13633 // Or declarations that aren't global. 13634 if (!FD->isGlobal()) 13635 return false; 13636 13637 // Don't warn about C++ member functions. 13638 if (isa<CXXMethodDecl>(FD)) 13639 return false; 13640 13641 // Don't warn about 'main'. 13642 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13643 if (IdentifierInfo *II = FD->getIdentifier()) 13644 if (II->isStr("main")) 13645 return false; 13646 13647 // Don't warn about inline functions. 13648 if (FD->isInlined()) 13649 return false; 13650 13651 // Don't warn about function templates. 13652 if (FD->getDescribedFunctionTemplate()) 13653 return false; 13654 13655 // Don't warn about function template specializations. 13656 if (FD->isFunctionTemplateSpecialization()) 13657 return false; 13658 13659 // Don't warn for OpenCL kernels. 13660 if (FD->hasAttr<OpenCLKernelAttr>()) 13661 return false; 13662 13663 // Don't warn on explicitly deleted functions. 13664 if (FD->isDeleted()) 13665 return false; 13666 13667 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13668 Prev; Prev = Prev->getPreviousDecl()) { 13669 // Ignore any declarations that occur in function or method 13670 // scope, because they aren't visible from the header. 13671 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13672 continue; 13673 13674 PossiblePrototype = Prev; 13675 return Prev->getType()->isFunctionNoProtoType(); 13676 } 13677 13678 return true; 13679 } 13680 13681 void 13682 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13683 const FunctionDecl *EffectiveDefinition, 13684 SkipBodyInfo *SkipBody) { 13685 const FunctionDecl *Definition = EffectiveDefinition; 13686 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13687 // If this is a friend function defined in a class template, it does not 13688 // have a body until it is used, nevertheless it is a definition, see 13689 // [temp.inst]p2: 13690 // 13691 // ... for the purpose of determining whether an instantiated redeclaration 13692 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13693 // corresponds to a definition in the template is considered to be a 13694 // definition. 13695 // 13696 // The following code must produce redefinition error: 13697 // 13698 // template<typename T> struct C20 { friend void func_20() {} }; 13699 // C20<int> c20i; 13700 // void func_20() {} 13701 // 13702 for (auto I : FD->redecls()) { 13703 if (I != FD && !I->isInvalidDecl() && 13704 I->getFriendObjectKind() != Decl::FOK_None) { 13705 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13706 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13707 // A merged copy of the same function, instantiated as a member of 13708 // the same class, is OK. 13709 if (declaresSameEntity(OrigFD, Original) && 13710 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13711 cast<Decl>(FD->getLexicalDeclContext()))) 13712 continue; 13713 } 13714 13715 if (Original->isThisDeclarationADefinition()) { 13716 Definition = I; 13717 break; 13718 } 13719 } 13720 } 13721 } 13722 } 13723 13724 if (!Definition) 13725 // Similar to friend functions a friend function template may be a 13726 // definition and do not have a body if it is instantiated in a class 13727 // template. 13728 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13729 for (auto I : FTD->redecls()) { 13730 auto D = cast<FunctionTemplateDecl>(I); 13731 if (D != FTD) { 13732 assert(!D->isThisDeclarationADefinition() && 13733 "More than one definition in redeclaration chain"); 13734 if (D->getFriendObjectKind() != Decl::FOK_None) 13735 if (FunctionTemplateDecl *FT = 13736 D->getInstantiatedFromMemberTemplate()) { 13737 if (FT->isThisDeclarationADefinition()) { 13738 Definition = D->getTemplatedDecl(); 13739 break; 13740 } 13741 } 13742 } 13743 } 13744 } 13745 13746 if (!Definition) 13747 return; 13748 13749 if (canRedefineFunction(Definition, getLangOpts())) 13750 return; 13751 13752 // Don't emit an error when this is redefinition of a typo-corrected 13753 // definition. 13754 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13755 return; 13756 13757 // If we don't have a visible definition of the function, and it's inline or 13758 // a template, skip the new definition. 13759 if (SkipBody && !hasVisibleDefinition(Definition) && 13760 (Definition->getFormalLinkage() == InternalLinkage || 13761 Definition->isInlined() || 13762 Definition->getDescribedFunctionTemplate() || 13763 Definition->getNumTemplateParameterLists())) { 13764 SkipBody->ShouldSkip = true; 13765 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13766 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13767 makeMergedDefinitionVisible(TD); 13768 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13769 return; 13770 } 13771 13772 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13773 Definition->getStorageClass() == SC_Extern) 13774 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13775 << FD->getDeclName() << getLangOpts().CPlusPlus; 13776 else 13777 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13778 13779 Diag(Definition->getLocation(), diag::note_previous_definition); 13780 FD->setInvalidDecl(); 13781 } 13782 13783 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13784 Sema &S) { 13785 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13786 13787 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13788 LSI->CallOperator = CallOperator; 13789 LSI->Lambda = LambdaClass; 13790 LSI->ReturnType = CallOperator->getReturnType(); 13791 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13792 13793 if (LCD == LCD_None) 13794 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13795 else if (LCD == LCD_ByCopy) 13796 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13797 else if (LCD == LCD_ByRef) 13798 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13799 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13800 13801 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13802 LSI->Mutable = !CallOperator->isConst(); 13803 13804 // Add the captures to the LSI so they can be noted as already 13805 // captured within tryCaptureVar. 13806 auto I = LambdaClass->field_begin(); 13807 for (const auto &C : LambdaClass->captures()) { 13808 if (C.capturesVariable()) { 13809 VarDecl *VD = C.getCapturedVar(); 13810 if (VD->isInitCapture()) 13811 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13812 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13813 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13814 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13815 /*EllipsisLoc*/C.isPackExpansion() 13816 ? C.getEllipsisLoc() : SourceLocation(), 13817 I->getType(), /*Invalid*/false); 13818 13819 } else if (C.capturesThis()) { 13820 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13821 C.getCaptureKind() == LCK_StarThis); 13822 } else { 13823 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13824 I->getType()); 13825 } 13826 ++I; 13827 } 13828 } 13829 13830 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13831 SkipBodyInfo *SkipBody) { 13832 if (!D) { 13833 // Parsing the function declaration failed in some way. Push on a fake scope 13834 // anyway so we can try to parse the function body. 13835 PushFunctionScope(); 13836 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13837 return D; 13838 } 13839 13840 FunctionDecl *FD = nullptr; 13841 13842 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13843 FD = FunTmpl->getTemplatedDecl(); 13844 else 13845 FD = cast<FunctionDecl>(D); 13846 13847 // Do not push if it is a lambda because one is already pushed when building 13848 // the lambda in ActOnStartOfLambdaDefinition(). 13849 if (!isLambdaCallOperator(FD)) 13850 PushExpressionEvaluationContext( 13851 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13852 : ExprEvalContexts.back().Context); 13853 13854 // Check for defining attributes before the check for redefinition. 13855 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13856 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13857 FD->dropAttr<AliasAttr>(); 13858 FD->setInvalidDecl(); 13859 } 13860 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13861 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13862 FD->dropAttr<IFuncAttr>(); 13863 FD->setInvalidDecl(); 13864 } 13865 13866 // See if this is a redefinition. If 'will have body' is already set, then 13867 // these checks were already performed when it was set. 13868 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13869 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13870 13871 // If we're skipping the body, we're done. Don't enter the scope. 13872 if (SkipBody && SkipBody->ShouldSkip) 13873 return D; 13874 } 13875 13876 // Mark this function as "will have a body eventually". This lets users to 13877 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13878 // this function. 13879 FD->setWillHaveBody(); 13880 13881 // If we are instantiating a generic lambda call operator, push 13882 // a LambdaScopeInfo onto the function stack. But use the information 13883 // that's already been calculated (ActOnLambdaExpr) to prime the current 13884 // LambdaScopeInfo. 13885 // When the template operator is being specialized, the LambdaScopeInfo, 13886 // has to be properly restored so that tryCaptureVariable doesn't try 13887 // and capture any new variables. In addition when calculating potential 13888 // captures during transformation of nested lambdas, it is necessary to 13889 // have the LSI properly restored. 13890 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13891 assert(inTemplateInstantiation() && 13892 "There should be an active template instantiation on the stack " 13893 "when instantiating a generic lambda!"); 13894 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13895 } else { 13896 // Enter a new function scope 13897 PushFunctionScope(); 13898 } 13899 13900 // Builtin functions cannot be defined. 13901 if (unsigned BuiltinID = FD->getBuiltinID()) { 13902 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13903 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13904 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13905 FD->setInvalidDecl(); 13906 } 13907 } 13908 13909 // The return type of a function definition must be complete 13910 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13911 QualType ResultType = FD->getReturnType(); 13912 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13913 !FD->isInvalidDecl() && 13914 RequireCompleteType(FD->getLocation(), ResultType, 13915 diag::err_func_def_incomplete_result)) 13916 FD->setInvalidDecl(); 13917 13918 if (FnBodyScope) 13919 PushDeclContext(FnBodyScope, FD); 13920 13921 // Check the validity of our function parameters 13922 CheckParmsForFunctionDef(FD->parameters(), 13923 /*CheckParameterNames=*/true); 13924 13925 // Add non-parameter declarations already in the function to the current 13926 // scope. 13927 if (FnBodyScope) { 13928 for (Decl *NPD : FD->decls()) { 13929 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13930 if (!NonParmDecl) 13931 continue; 13932 assert(!isa<ParmVarDecl>(NonParmDecl) && 13933 "parameters should not be in newly created FD yet"); 13934 13935 // If the decl has a name, make it accessible in the current scope. 13936 if (NonParmDecl->getDeclName()) 13937 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13938 13939 // Similarly, dive into enums and fish their constants out, making them 13940 // accessible in this scope. 13941 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13942 for (auto *EI : ED->enumerators()) 13943 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13944 } 13945 } 13946 } 13947 13948 // Introduce our parameters into the function scope 13949 for (auto Param : FD->parameters()) { 13950 Param->setOwningFunction(FD); 13951 13952 // If this has an identifier, add it to the scope stack. 13953 if (Param->getIdentifier() && FnBodyScope) { 13954 CheckShadow(FnBodyScope, Param); 13955 13956 PushOnScopeChains(Param, FnBodyScope); 13957 } 13958 } 13959 13960 // Ensure that the function's exception specification is instantiated. 13961 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13962 ResolveExceptionSpec(D->getLocation(), FPT); 13963 13964 // dllimport cannot be applied to non-inline function definitions. 13965 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13966 !FD->isTemplateInstantiation()) { 13967 assert(!FD->hasAttr<DLLExportAttr>()); 13968 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13969 FD->setInvalidDecl(); 13970 return D; 13971 } 13972 // We want to attach documentation to original Decl (which might be 13973 // a function template). 13974 ActOnDocumentableDecl(D); 13975 if (getCurLexicalContext()->isObjCContainer() && 13976 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13977 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13978 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13979 13980 return D; 13981 } 13982 13983 /// Given the set of return statements within a function body, 13984 /// compute the variables that are subject to the named return value 13985 /// optimization. 13986 /// 13987 /// Each of the variables that is subject to the named return value 13988 /// optimization will be marked as NRVO variables in the AST, and any 13989 /// return statement that has a marked NRVO variable as its NRVO candidate can 13990 /// use the named return value optimization. 13991 /// 13992 /// This function applies a very simplistic algorithm for NRVO: if every return 13993 /// statement in the scope of a variable has the same NRVO candidate, that 13994 /// candidate is an NRVO variable. 13995 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13996 ReturnStmt **Returns = Scope->Returns.data(); 13997 13998 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13999 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14000 if (!NRVOCandidate->isNRVOVariable()) 14001 Returns[I]->setNRVOCandidate(nullptr); 14002 } 14003 } 14004 } 14005 14006 bool Sema::canDelayFunctionBody(const Declarator &D) { 14007 // We can't delay parsing the body of a constexpr function template (yet). 14008 if (D.getDeclSpec().hasConstexprSpecifier()) 14009 return false; 14010 14011 // We can't delay parsing the body of a function template with a deduced 14012 // return type (yet). 14013 if (D.getDeclSpec().hasAutoTypeSpec()) { 14014 // If the placeholder introduces a non-deduced trailing return type, 14015 // we can still delay parsing it. 14016 if (D.getNumTypeObjects()) { 14017 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14018 if (Outer.Kind == DeclaratorChunk::Function && 14019 Outer.Fun.hasTrailingReturnType()) { 14020 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14021 return Ty.isNull() || !Ty->isUndeducedType(); 14022 } 14023 } 14024 return false; 14025 } 14026 14027 return true; 14028 } 14029 14030 bool Sema::canSkipFunctionBody(Decl *D) { 14031 // We cannot skip the body of a function (or function template) which is 14032 // constexpr, since we may need to evaluate its body in order to parse the 14033 // rest of the file. 14034 // We cannot skip the body of a function with an undeduced return type, 14035 // because any callers of that function need to know the type. 14036 if (const FunctionDecl *FD = D->getAsFunction()) { 14037 if (FD->isConstexpr()) 14038 return false; 14039 // We can't simply call Type::isUndeducedType here, because inside template 14040 // auto can be deduced to a dependent type, which is not considered 14041 // "undeduced". 14042 if (FD->getReturnType()->getContainedDeducedType()) 14043 return false; 14044 } 14045 return Consumer.shouldSkipFunctionBody(D); 14046 } 14047 14048 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14049 if (!Decl) 14050 return nullptr; 14051 if (FunctionDecl *FD = Decl->getAsFunction()) 14052 FD->setHasSkippedBody(); 14053 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14054 MD->setHasSkippedBody(); 14055 return Decl; 14056 } 14057 14058 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14059 return ActOnFinishFunctionBody(D, BodyArg, false); 14060 } 14061 14062 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14063 /// body. 14064 class ExitFunctionBodyRAII { 14065 public: 14066 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14067 ~ExitFunctionBodyRAII() { 14068 if (!IsLambda) 14069 S.PopExpressionEvaluationContext(); 14070 } 14071 14072 private: 14073 Sema &S; 14074 bool IsLambda = false; 14075 }; 14076 14077 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14078 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14079 14080 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14081 if (EscapeInfo.count(BD)) 14082 return EscapeInfo[BD]; 14083 14084 bool R = false; 14085 const BlockDecl *CurBD = BD; 14086 14087 do { 14088 R = !CurBD->doesNotEscape(); 14089 if (R) 14090 break; 14091 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14092 } while (CurBD); 14093 14094 return EscapeInfo[BD] = R; 14095 }; 14096 14097 // If the location where 'self' is implicitly retained is inside a escaping 14098 // block, emit a diagnostic. 14099 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14100 S.ImplicitlyRetainedSelfLocs) 14101 if (IsOrNestedInEscapingBlock(P.second)) 14102 S.Diag(P.first, diag::warn_implicitly_retains_self) 14103 << FixItHint::CreateInsertion(P.first, "self->"); 14104 } 14105 14106 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14107 bool IsInstantiation) { 14108 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14109 14110 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14111 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14112 14113 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14114 CheckCompletedCoroutineBody(FD, Body); 14115 14116 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14117 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14118 // meant to pop the context added in ActOnStartOfFunctionDef(). 14119 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14120 14121 if (FD) { 14122 FD->setBody(Body); 14123 FD->setWillHaveBody(false); 14124 14125 if (getLangOpts().CPlusPlus14) { 14126 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14127 FD->getReturnType()->isUndeducedType()) { 14128 // If the function has a deduced result type but contains no 'return' 14129 // statements, the result type as written must be exactly 'auto', and 14130 // the deduced result type is 'void'. 14131 if (!FD->getReturnType()->getAs<AutoType>()) { 14132 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14133 << FD->getReturnType(); 14134 FD->setInvalidDecl(); 14135 } else { 14136 // Substitute 'void' for the 'auto' in the type. 14137 TypeLoc ResultType = getReturnTypeLoc(FD); 14138 Context.adjustDeducedFunctionResultType( 14139 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14140 } 14141 } 14142 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14143 // In C++11, we don't use 'auto' deduction rules for lambda call 14144 // operators because we don't support return type deduction. 14145 auto *LSI = getCurLambda(); 14146 if (LSI->HasImplicitReturnType) { 14147 deduceClosureReturnType(*LSI); 14148 14149 // C++11 [expr.prim.lambda]p4: 14150 // [...] if there are no return statements in the compound-statement 14151 // [the deduced type is] the type void 14152 QualType RetType = 14153 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14154 14155 // Update the return type to the deduced type. 14156 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14157 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14158 Proto->getExtProtoInfo())); 14159 } 14160 } 14161 14162 // If the function implicitly returns zero (like 'main') or is naked, 14163 // don't complain about missing return statements. 14164 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14165 WP.disableCheckFallThrough(); 14166 14167 // MSVC permits the use of pure specifier (=0) on function definition, 14168 // defined at class scope, warn about this non-standard construct. 14169 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14170 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14171 14172 if (!FD->isInvalidDecl()) { 14173 // Don't diagnose unused parameters of defaulted or deleted functions. 14174 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14175 DiagnoseUnusedParameters(FD->parameters()); 14176 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14177 FD->getReturnType(), FD); 14178 14179 // If this is a structor, we need a vtable. 14180 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14181 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14182 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14183 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14184 14185 // Try to apply the named return value optimization. We have to check 14186 // if we can do this here because lambdas keep return statements around 14187 // to deduce an implicit return type. 14188 if (FD->getReturnType()->isRecordType() && 14189 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14190 computeNRVO(Body, getCurFunction()); 14191 } 14192 14193 // GNU warning -Wmissing-prototypes: 14194 // Warn if a global function is defined without a previous 14195 // prototype declaration. This warning is issued even if the 14196 // definition itself provides a prototype. The aim is to detect 14197 // global functions that fail to be declared in header files. 14198 const FunctionDecl *PossiblePrototype = nullptr; 14199 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14200 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14201 14202 if (PossiblePrototype) { 14203 // We found a declaration that is not a prototype, 14204 // but that could be a zero-parameter prototype 14205 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14206 TypeLoc TL = TI->getTypeLoc(); 14207 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14208 Diag(PossiblePrototype->getLocation(), 14209 diag::note_declaration_not_a_prototype) 14210 << (FD->getNumParams() != 0) 14211 << (FD->getNumParams() == 0 14212 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14213 : FixItHint{}); 14214 } 14215 } else { 14216 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14217 << /* function */ 1 14218 << (FD->getStorageClass() == SC_None 14219 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14220 "static ") 14221 : FixItHint{}); 14222 } 14223 14224 // GNU warning -Wstrict-prototypes 14225 // Warn if K&R function is defined without a previous declaration. 14226 // This warning is issued only if the definition itself does not provide 14227 // a prototype. Only K&R definitions do not provide a prototype. 14228 if (!FD->hasWrittenPrototype()) { 14229 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14230 TypeLoc TL = TI->getTypeLoc(); 14231 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14232 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14233 } 14234 } 14235 14236 // Warn on CPUDispatch with an actual body. 14237 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14238 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14239 if (!CmpndBody->body_empty()) 14240 Diag(CmpndBody->body_front()->getBeginLoc(), 14241 diag::warn_dispatch_body_ignored); 14242 14243 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14244 const CXXMethodDecl *KeyFunction; 14245 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14246 MD->isVirtual() && 14247 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14248 MD == KeyFunction->getCanonicalDecl()) { 14249 // Update the key-function state if necessary for this ABI. 14250 if (FD->isInlined() && 14251 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14252 Context.setNonKeyFunction(MD); 14253 14254 // If the newly-chosen key function is already defined, then we 14255 // need to mark the vtable as used retroactively. 14256 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14257 const FunctionDecl *Definition; 14258 if (KeyFunction && KeyFunction->isDefined(Definition)) 14259 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14260 } else { 14261 // We just defined they key function; mark the vtable as used. 14262 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14263 } 14264 } 14265 } 14266 14267 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14268 "Function parsing confused"); 14269 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14270 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14271 MD->setBody(Body); 14272 if (!MD->isInvalidDecl()) { 14273 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14274 MD->getReturnType(), MD); 14275 14276 if (Body) 14277 computeNRVO(Body, getCurFunction()); 14278 } 14279 if (getCurFunction()->ObjCShouldCallSuper) { 14280 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14281 << MD->getSelector().getAsString(); 14282 getCurFunction()->ObjCShouldCallSuper = false; 14283 } 14284 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14285 const ObjCMethodDecl *InitMethod = nullptr; 14286 bool isDesignated = 14287 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14288 assert(isDesignated && InitMethod); 14289 (void)isDesignated; 14290 14291 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14292 auto IFace = MD->getClassInterface(); 14293 if (!IFace) 14294 return false; 14295 auto SuperD = IFace->getSuperClass(); 14296 if (!SuperD) 14297 return false; 14298 return SuperD->getIdentifier() == 14299 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14300 }; 14301 // Don't issue this warning for unavailable inits or direct subclasses 14302 // of NSObject. 14303 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14304 Diag(MD->getLocation(), 14305 diag::warn_objc_designated_init_missing_super_call); 14306 Diag(InitMethod->getLocation(), 14307 diag::note_objc_designated_init_marked_here); 14308 } 14309 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14310 } 14311 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14312 // Don't issue this warning for unavaialable inits. 14313 if (!MD->isUnavailable()) 14314 Diag(MD->getLocation(), 14315 diag::warn_objc_secondary_init_missing_init_call); 14316 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14317 } 14318 14319 diagnoseImplicitlyRetainedSelf(*this); 14320 } else { 14321 // Parsing the function declaration failed in some way. Pop the fake scope 14322 // we pushed on. 14323 PopFunctionScopeInfo(ActivePolicy, dcl); 14324 return nullptr; 14325 } 14326 14327 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14328 DiagnoseUnguardedAvailabilityViolations(dcl); 14329 14330 assert(!getCurFunction()->ObjCShouldCallSuper && 14331 "This should only be set for ObjC methods, which should have been " 14332 "handled in the block above."); 14333 14334 // Verify and clean out per-function state. 14335 if (Body && (!FD || !FD->isDefaulted())) { 14336 // C++ constructors that have function-try-blocks can't have return 14337 // statements in the handlers of that block. (C++ [except.handle]p14) 14338 // Verify this. 14339 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14340 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14341 14342 // Verify that gotos and switch cases don't jump into scopes illegally. 14343 if (getCurFunction()->NeedsScopeChecking() && 14344 !PP.isCodeCompletionEnabled()) 14345 DiagnoseInvalidJumps(Body); 14346 14347 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14348 if (!Destructor->getParent()->isDependentType()) 14349 CheckDestructor(Destructor); 14350 14351 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14352 Destructor->getParent()); 14353 } 14354 14355 // If any errors have occurred, clear out any temporaries that may have 14356 // been leftover. This ensures that these temporaries won't be picked up for 14357 // deletion in some later function. 14358 if (getDiagnostics().hasErrorOccurred() || 14359 getDiagnostics().getSuppressAllDiagnostics()) { 14360 DiscardCleanupsInEvaluationContext(); 14361 } 14362 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14363 !isa<FunctionTemplateDecl>(dcl)) { 14364 // Since the body is valid, issue any analysis-based warnings that are 14365 // enabled. 14366 ActivePolicy = &WP; 14367 } 14368 14369 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14370 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14371 FD->setInvalidDecl(); 14372 14373 if (FD && FD->hasAttr<NakedAttr>()) { 14374 for (const Stmt *S : Body->children()) { 14375 // Allow local register variables without initializer as they don't 14376 // require prologue. 14377 bool RegisterVariables = false; 14378 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14379 for (const auto *Decl : DS->decls()) { 14380 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14381 RegisterVariables = 14382 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14383 if (!RegisterVariables) 14384 break; 14385 } 14386 } 14387 } 14388 if (RegisterVariables) 14389 continue; 14390 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14391 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14392 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14393 FD->setInvalidDecl(); 14394 break; 14395 } 14396 } 14397 } 14398 14399 assert(ExprCleanupObjects.size() == 14400 ExprEvalContexts.back().NumCleanupObjects && 14401 "Leftover temporaries in function"); 14402 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14403 assert(MaybeODRUseExprs.empty() && 14404 "Leftover expressions for odr-use checking"); 14405 } 14406 14407 if (!IsInstantiation) 14408 PopDeclContext(); 14409 14410 PopFunctionScopeInfo(ActivePolicy, dcl); 14411 // If any errors have occurred, clear out any temporaries that may have 14412 // been leftover. This ensures that these temporaries won't be picked up for 14413 // deletion in some later function. 14414 if (getDiagnostics().hasErrorOccurred()) { 14415 DiscardCleanupsInEvaluationContext(); 14416 } 14417 14418 if (LangOpts.OpenMP || LangOpts.CUDA) { 14419 auto ES = getEmissionStatus(FD); 14420 if (ES == Sema::FunctionEmissionStatus::Emitted || 14421 ES == Sema::FunctionEmissionStatus::Unknown) 14422 DeclsToCheckForDeferredDiags.push_back(FD); 14423 } 14424 14425 return dcl; 14426 } 14427 14428 /// When we finish delayed parsing of an attribute, we must attach it to the 14429 /// relevant Decl. 14430 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14431 ParsedAttributes &Attrs) { 14432 // Always attach attributes to the underlying decl. 14433 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14434 D = TD->getTemplatedDecl(); 14435 ProcessDeclAttributeList(S, D, Attrs); 14436 14437 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14438 if (Method->isStatic()) 14439 checkThisInStaticMemberFunctionAttributes(Method); 14440 } 14441 14442 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14443 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14444 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14445 IdentifierInfo &II, Scope *S) { 14446 // Find the scope in which the identifier is injected and the corresponding 14447 // DeclContext. 14448 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14449 // In that case, we inject the declaration into the translation unit scope 14450 // instead. 14451 Scope *BlockScope = S; 14452 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14453 BlockScope = BlockScope->getParent(); 14454 14455 Scope *ContextScope = BlockScope; 14456 while (!ContextScope->getEntity()) 14457 ContextScope = ContextScope->getParent(); 14458 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14459 14460 // Before we produce a declaration for an implicitly defined 14461 // function, see whether there was a locally-scoped declaration of 14462 // this name as a function or variable. If so, use that 14463 // (non-visible) declaration, and complain about it. 14464 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14465 if (ExternCPrev) { 14466 // We still need to inject the function into the enclosing block scope so 14467 // that later (non-call) uses can see it. 14468 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14469 14470 // C89 footnote 38: 14471 // If in fact it is not defined as having type "function returning int", 14472 // the behavior is undefined. 14473 if (!isa<FunctionDecl>(ExternCPrev) || 14474 !Context.typesAreCompatible( 14475 cast<FunctionDecl>(ExternCPrev)->getType(), 14476 Context.getFunctionNoProtoType(Context.IntTy))) { 14477 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14478 << ExternCPrev << !getLangOpts().C99; 14479 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14480 return ExternCPrev; 14481 } 14482 } 14483 14484 // Extension in C99. Legal in C90, but warn about it. 14485 unsigned diag_id; 14486 if (II.getName().startswith("__builtin_")) 14487 diag_id = diag::warn_builtin_unknown; 14488 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14489 else if (getLangOpts().OpenCL) 14490 diag_id = diag::err_opencl_implicit_function_decl; 14491 else if (getLangOpts().C99) 14492 diag_id = diag::ext_implicit_function_decl; 14493 else 14494 diag_id = diag::warn_implicit_function_decl; 14495 Diag(Loc, diag_id) << &II; 14496 14497 // If we found a prior declaration of this function, don't bother building 14498 // another one. We've already pushed that one into scope, so there's nothing 14499 // more to do. 14500 if (ExternCPrev) 14501 return ExternCPrev; 14502 14503 // Because typo correction is expensive, only do it if the implicit 14504 // function declaration is going to be treated as an error. 14505 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14506 TypoCorrection Corrected; 14507 DeclFilterCCC<FunctionDecl> CCC{}; 14508 if (S && (Corrected = 14509 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14510 S, nullptr, CCC, CTK_NonError))) 14511 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14512 /*ErrorRecovery*/false); 14513 } 14514 14515 // Set a Declarator for the implicit definition: int foo(); 14516 const char *Dummy; 14517 AttributeFactory attrFactory; 14518 DeclSpec DS(attrFactory); 14519 unsigned DiagID; 14520 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14521 Context.getPrintingPolicy()); 14522 (void)Error; // Silence warning. 14523 assert(!Error && "Error setting up implicit decl!"); 14524 SourceLocation NoLoc; 14525 Declarator D(DS, DeclaratorContext::BlockContext); 14526 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14527 /*IsAmbiguous=*/false, 14528 /*LParenLoc=*/NoLoc, 14529 /*Params=*/nullptr, 14530 /*NumParams=*/0, 14531 /*EllipsisLoc=*/NoLoc, 14532 /*RParenLoc=*/NoLoc, 14533 /*RefQualifierIsLvalueRef=*/true, 14534 /*RefQualifierLoc=*/NoLoc, 14535 /*MutableLoc=*/NoLoc, EST_None, 14536 /*ESpecRange=*/SourceRange(), 14537 /*Exceptions=*/nullptr, 14538 /*ExceptionRanges=*/nullptr, 14539 /*NumExceptions=*/0, 14540 /*NoexceptExpr=*/nullptr, 14541 /*ExceptionSpecTokens=*/nullptr, 14542 /*DeclsInPrototype=*/None, Loc, 14543 Loc, D), 14544 std::move(DS.getAttributes()), SourceLocation()); 14545 D.SetIdentifier(&II, Loc); 14546 14547 // Insert this function into the enclosing block scope. 14548 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14549 FD->setImplicit(); 14550 14551 AddKnownFunctionAttributes(FD); 14552 14553 return FD; 14554 } 14555 14556 /// If this function is a C++ replaceable global allocation function 14557 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14558 /// adds any function attributes that we know a priori based on the standard. 14559 /// 14560 /// We need to check for duplicate attributes both here and where user-written 14561 /// attributes are applied to declarations. 14562 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14563 FunctionDecl *FD) { 14564 if (FD->isInvalidDecl()) 14565 return; 14566 14567 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14568 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14569 return; 14570 14571 Optional<unsigned> AlignmentParam; 14572 bool IsNothrow = false; 14573 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14574 return; 14575 14576 // C++2a [basic.stc.dynamic.allocation]p4: 14577 // An allocation function that has a non-throwing exception specification 14578 // indicates failure by returning a null pointer value. Any other allocation 14579 // function never returns a null pointer value and indicates failure only by 14580 // throwing an exception [...] 14581 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14582 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14583 14584 // C++2a [basic.stc.dynamic.allocation]p2: 14585 // An allocation function attempts to allocate the requested amount of 14586 // storage. [...] If the request succeeds, the value returned by a 14587 // replaceable allocation function is a [...] pointer value p0 different 14588 // from any previously returned value p1 [...] 14589 // 14590 // However, this particular information is being added in codegen, 14591 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14592 14593 // C++2a [basic.stc.dynamic.allocation]p2: 14594 // An allocation function attempts to allocate the requested amount of 14595 // storage. If it is successful, it returns the address of the start of a 14596 // block of storage whose length in bytes is at least as large as the 14597 // requested size. 14598 if (!FD->hasAttr<AllocSizeAttr>()) { 14599 FD->addAttr(AllocSizeAttr::CreateImplicit( 14600 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14601 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14602 } 14603 14604 // C++2a [basic.stc.dynamic.allocation]p3: 14605 // For an allocation function [...], the pointer returned on a successful 14606 // call shall represent the address of storage that is aligned as follows: 14607 // (3.1) If the allocation function takes an argument of type 14608 // std::align_val_t, the storage will have the alignment 14609 // specified by the value of this argument. 14610 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14611 FD->addAttr(AllocAlignAttr::CreateImplicit( 14612 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14613 } 14614 14615 // FIXME: 14616 // C++2a [basic.stc.dynamic.allocation]p3: 14617 // For an allocation function [...], the pointer returned on a successful 14618 // call shall represent the address of storage that is aligned as follows: 14619 // (3.2) Otherwise, if the allocation function is named operator new[], 14620 // the storage is aligned for any object that does not have 14621 // new-extended alignment ([basic.align]) and is no larger than the 14622 // requested size. 14623 // (3.3) Otherwise, the storage is aligned for any object that does not 14624 // have new-extended alignment and is of the requested size. 14625 } 14626 14627 /// Adds any function attributes that we know a priori based on 14628 /// the declaration of this function. 14629 /// 14630 /// These attributes can apply both to implicitly-declared builtins 14631 /// (like __builtin___printf_chk) or to library-declared functions 14632 /// like NSLog or printf. 14633 /// 14634 /// We need to check for duplicate attributes both here and where user-written 14635 /// attributes are applied to declarations. 14636 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14637 if (FD->isInvalidDecl()) 14638 return; 14639 14640 // If this is a built-in function, map its builtin attributes to 14641 // actual attributes. 14642 if (unsigned BuiltinID = FD->getBuiltinID()) { 14643 // Handle printf-formatting attributes. 14644 unsigned FormatIdx; 14645 bool HasVAListArg; 14646 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14647 if (!FD->hasAttr<FormatAttr>()) { 14648 const char *fmt = "printf"; 14649 unsigned int NumParams = FD->getNumParams(); 14650 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14651 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14652 fmt = "NSString"; 14653 FD->addAttr(FormatAttr::CreateImplicit(Context, 14654 &Context.Idents.get(fmt), 14655 FormatIdx+1, 14656 HasVAListArg ? 0 : FormatIdx+2, 14657 FD->getLocation())); 14658 } 14659 } 14660 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14661 HasVAListArg)) { 14662 if (!FD->hasAttr<FormatAttr>()) 14663 FD->addAttr(FormatAttr::CreateImplicit(Context, 14664 &Context.Idents.get("scanf"), 14665 FormatIdx+1, 14666 HasVAListArg ? 0 : FormatIdx+2, 14667 FD->getLocation())); 14668 } 14669 14670 // Handle automatically recognized callbacks. 14671 SmallVector<int, 4> Encoding; 14672 if (!FD->hasAttr<CallbackAttr>() && 14673 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14674 FD->addAttr(CallbackAttr::CreateImplicit( 14675 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14676 14677 // Mark const if we don't care about errno and that is the only thing 14678 // preventing the function from being const. This allows IRgen to use LLVM 14679 // intrinsics for such functions. 14680 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14681 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14682 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14683 14684 // We make "fma" on some platforms const because we know it does not set 14685 // errno in those environments even though it could set errno based on the 14686 // C standard. 14687 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14688 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14689 !FD->hasAttr<ConstAttr>()) { 14690 switch (BuiltinID) { 14691 case Builtin::BI__builtin_fma: 14692 case Builtin::BI__builtin_fmaf: 14693 case Builtin::BI__builtin_fmal: 14694 case Builtin::BIfma: 14695 case Builtin::BIfmaf: 14696 case Builtin::BIfmal: 14697 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14698 break; 14699 default: 14700 break; 14701 } 14702 } 14703 14704 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14705 !FD->hasAttr<ReturnsTwiceAttr>()) 14706 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14707 FD->getLocation())); 14708 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14709 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14710 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14711 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14712 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14713 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14714 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14715 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14716 // Add the appropriate attribute, depending on the CUDA compilation mode 14717 // and which target the builtin belongs to. For example, during host 14718 // compilation, aux builtins are __device__, while the rest are __host__. 14719 if (getLangOpts().CUDAIsDevice != 14720 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14721 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14722 else 14723 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14724 } 14725 } 14726 14727 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14728 14729 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14730 // throw, add an implicit nothrow attribute to any extern "C" function we come 14731 // across. 14732 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14733 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14734 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14735 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14736 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14737 } 14738 14739 IdentifierInfo *Name = FD->getIdentifier(); 14740 if (!Name) 14741 return; 14742 if ((!getLangOpts().CPlusPlus && 14743 FD->getDeclContext()->isTranslationUnit()) || 14744 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14745 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14746 LinkageSpecDecl::lang_c)) { 14747 // Okay: this could be a libc/libm/Objective-C function we know 14748 // about. 14749 } else 14750 return; 14751 14752 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14753 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14754 // target-specific builtins, perhaps? 14755 if (!FD->hasAttr<FormatAttr>()) 14756 FD->addAttr(FormatAttr::CreateImplicit(Context, 14757 &Context.Idents.get("printf"), 2, 14758 Name->isStr("vasprintf") ? 0 : 3, 14759 FD->getLocation())); 14760 } 14761 14762 if (Name->isStr("__CFStringMakeConstantString")) { 14763 // We already have a __builtin___CFStringMakeConstantString, 14764 // but builds that use -fno-constant-cfstrings don't go through that. 14765 if (!FD->hasAttr<FormatArgAttr>()) 14766 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14767 FD->getLocation())); 14768 } 14769 } 14770 14771 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14772 TypeSourceInfo *TInfo) { 14773 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14774 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14775 14776 if (!TInfo) { 14777 assert(D.isInvalidType() && "no declarator info for valid type"); 14778 TInfo = Context.getTrivialTypeSourceInfo(T); 14779 } 14780 14781 // Scope manipulation handled by caller. 14782 TypedefDecl *NewTD = 14783 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14784 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14785 14786 // Bail out immediately if we have an invalid declaration. 14787 if (D.isInvalidType()) { 14788 NewTD->setInvalidDecl(); 14789 return NewTD; 14790 } 14791 14792 if (D.getDeclSpec().isModulePrivateSpecified()) { 14793 if (CurContext->isFunctionOrMethod()) 14794 Diag(NewTD->getLocation(), diag::err_module_private_local) 14795 << 2 << NewTD->getDeclName() 14796 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14797 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14798 else 14799 NewTD->setModulePrivate(); 14800 } 14801 14802 // C++ [dcl.typedef]p8: 14803 // If the typedef declaration defines an unnamed class (or 14804 // enum), the first typedef-name declared by the declaration 14805 // to be that class type (or enum type) is used to denote the 14806 // class type (or enum type) for linkage purposes only. 14807 // We need to check whether the type was declared in the declaration. 14808 switch (D.getDeclSpec().getTypeSpecType()) { 14809 case TST_enum: 14810 case TST_struct: 14811 case TST_interface: 14812 case TST_union: 14813 case TST_class: { 14814 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14815 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14816 break; 14817 } 14818 14819 default: 14820 break; 14821 } 14822 14823 return NewTD; 14824 } 14825 14826 /// Check that this is a valid underlying type for an enum declaration. 14827 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14828 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14829 QualType T = TI->getType(); 14830 14831 if (T->isDependentType()) 14832 return false; 14833 14834 // This doesn't use 'isIntegralType' despite the error message mentioning 14835 // integral type because isIntegralType would also allow enum types in C. 14836 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14837 if (BT->isInteger()) 14838 return false; 14839 14840 if (T->isExtIntType()) 14841 return false; 14842 14843 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14844 } 14845 14846 /// Check whether this is a valid redeclaration of a previous enumeration. 14847 /// \return true if the redeclaration was invalid. 14848 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14849 QualType EnumUnderlyingTy, bool IsFixed, 14850 const EnumDecl *Prev) { 14851 if (IsScoped != Prev->isScoped()) { 14852 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14853 << Prev->isScoped(); 14854 Diag(Prev->getLocation(), diag::note_previous_declaration); 14855 return true; 14856 } 14857 14858 if (IsFixed && Prev->isFixed()) { 14859 if (!EnumUnderlyingTy->isDependentType() && 14860 !Prev->getIntegerType()->isDependentType() && 14861 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14862 Prev->getIntegerType())) { 14863 // TODO: Highlight the underlying type of the redeclaration. 14864 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14865 << EnumUnderlyingTy << Prev->getIntegerType(); 14866 Diag(Prev->getLocation(), diag::note_previous_declaration) 14867 << Prev->getIntegerTypeRange(); 14868 return true; 14869 } 14870 } else if (IsFixed != Prev->isFixed()) { 14871 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14872 << Prev->isFixed(); 14873 Diag(Prev->getLocation(), diag::note_previous_declaration); 14874 return true; 14875 } 14876 14877 return false; 14878 } 14879 14880 /// Get diagnostic %select index for tag kind for 14881 /// redeclaration diagnostic message. 14882 /// WARNING: Indexes apply to particular diagnostics only! 14883 /// 14884 /// \returns diagnostic %select index. 14885 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14886 switch (Tag) { 14887 case TTK_Struct: return 0; 14888 case TTK_Interface: return 1; 14889 case TTK_Class: return 2; 14890 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14891 } 14892 } 14893 14894 /// Determine if tag kind is a class-key compatible with 14895 /// class for redeclaration (class, struct, or __interface). 14896 /// 14897 /// \returns true iff the tag kind is compatible. 14898 static bool isClassCompatTagKind(TagTypeKind Tag) 14899 { 14900 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14901 } 14902 14903 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14904 TagTypeKind TTK) { 14905 if (isa<TypedefDecl>(PrevDecl)) 14906 return NTK_Typedef; 14907 else if (isa<TypeAliasDecl>(PrevDecl)) 14908 return NTK_TypeAlias; 14909 else if (isa<ClassTemplateDecl>(PrevDecl)) 14910 return NTK_Template; 14911 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14912 return NTK_TypeAliasTemplate; 14913 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14914 return NTK_TemplateTemplateArgument; 14915 switch (TTK) { 14916 case TTK_Struct: 14917 case TTK_Interface: 14918 case TTK_Class: 14919 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14920 case TTK_Union: 14921 return NTK_NonUnion; 14922 case TTK_Enum: 14923 return NTK_NonEnum; 14924 } 14925 llvm_unreachable("invalid TTK"); 14926 } 14927 14928 /// Determine whether a tag with a given kind is acceptable 14929 /// as a redeclaration of the given tag declaration. 14930 /// 14931 /// \returns true if the new tag kind is acceptable, false otherwise. 14932 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14933 TagTypeKind NewTag, bool isDefinition, 14934 SourceLocation NewTagLoc, 14935 const IdentifierInfo *Name) { 14936 // C++ [dcl.type.elab]p3: 14937 // The class-key or enum keyword present in the 14938 // elaborated-type-specifier shall agree in kind with the 14939 // declaration to which the name in the elaborated-type-specifier 14940 // refers. This rule also applies to the form of 14941 // elaborated-type-specifier that declares a class-name or 14942 // friend class since it can be construed as referring to the 14943 // definition of the class. Thus, in any 14944 // elaborated-type-specifier, the enum keyword shall be used to 14945 // refer to an enumeration (7.2), the union class-key shall be 14946 // used to refer to a union (clause 9), and either the class or 14947 // struct class-key shall be used to refer to a class (clause 9) 14948 // declared using the class or struct class-key. 14949 TagTypeKind OldTag = Previous->getTagKind(); 14950 if (OldTag != NewTag && 14951 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14952 return false; 14953 14954 // Tags are compatible, but we might still want to warn on mismatched tags. 14955 // Non-class tags can't be mismatched at this point. 14956 if (!isClassCompatTagKind(NewTag)) 14957 return true; 14958 14959 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14960 // by our warning analysis. We don't want to warn about mismatches with (eg) 14961 // declarations in system headers that are designed to be specialized, but if 14962 // a user asks us to warn, we should warn if their code contains mismatched 14963 // declarations. 14964 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14965 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14966 Loc); 14967 }; 14968 if (IsIgnoredLoc(NewTagLoc)) 14969 return true; 14970 14971 auto IsIgnored = [&](const TagDecl *Tag) { 14972 return IsIgnoredLoc(Tag->getLocation()); 14973 }; 14974 while (IsIgnored(Previous)) { 14975 Previous = Previous->getPreviousDecl(); 14976 if (!Previous) 14977 return true; 14978 OldTag = Previous->getTagKind(); 14979 } 14980 14981 bool isTemplate = false; 14982 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14983 isTemplate = Record->getDescribedClassTemplate(); 14984 14985 if (inTemplateInstantiation()) { 14986 if (OldTag != NewTag) { 14987 // In a template instantiation, do not offer fix-its for tag mismatches 14988 // since they usually mess up the template instead of fixing the problem. 14989 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14990 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14991 << getRedeclDiagFromTagKind(OldTag); 14992 // FIXME: Note previous location? 14993 } 14994 return true; 14995 } 14996 14997 if (isDefinition) { 14998 // On definitions, check all previous tags and issue a fix-it for each 14999 // one that doesn't match the current tag. 15000 if (Previous->getDefinition()) { 15001 // Don't suggest fix-its for redefinitions. 15002 return true; 15003 } 15004 15005 bool previousMismatch = false; 15006 for (const TagDecl *I : Previous->redecls()) { 15007 if (I->getTagKind() != NewTag) { 15008 // Ignore previous declarations for which the warning was disabled. 15009 if (IsIgnored(I)) 15010 continue; 15011 15012 if (!previousMismatch) { 15013 previousMismatch = true; 15014 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15015 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15016 << getRedeclDiagFromTagKind(I->getTagKind()); 15017 } 15018 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15019 << getRedeclDiagFromTagKind(NewTag) 15020 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15021 TypeWithKeyword::getTagTypeKindName(NewTag)); 15022 } 15023 } 15024 return true; 15025 } 15026 15027 // Identify the prevailing tag kind: this is the kind of the definition (if 15028 // there is a non-ignored definition), or otherwise the kind of the prior 15029 // (non-ignored) declaration. 15030 const TagDecl *PrevDef = Previous->getDefinition(); 15031 if (PrevDef && IsIgnored(PrevDef)) 15032 PrevDef = nullptr; 15033 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15034 if (Redecl->getTagKind() != NewTag) { 15035 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15036 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15037 << getRedeclDiagFromTagKind(OldTag); 15038 Diag(Redecl->getLocation(), diag::note_previous_use); 15039 15040 // If there is a previous definition, suggest a fix-it. 15041 if (PrevDef) { 15042 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15043 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15044 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15045 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15046 } 15047 } 15048 15049 return true; 15050 } 15051 15052 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15053 /// from an outer enclosing namespace or file scope inside a friend declaration. 15054 /// This should provide the commented out code in the following snippet: 15055 /// namespace N { 15056 /// struct X; 15057 /// namespace M { 15058 /// struct Y { friend struct /*N::*/ X; }; 15059 /// } 15060 /// } 15061 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15062 SourceLocation NameLoc) { 15063 // While the decl is in a namespace, do repeated lookup of that name and see 15064 // if we get the same namespace back. If we do not, continue until 15065 // translation unit scope, at which point we have a fully qualified NNS. 15066 SmallVector<IdentifierInfo *, 4> Namespaces; 15067 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15068 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15069 // This tag should be declared in a namespace, which can only be enclosed by 15070 // other namespaces. Bail if there's an anonymous namespace in the chain. 15071 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15072 if (!Namespace || Namespace->isAnonymousNamespace()) 15073 return FixItHint(); 15074 IdentifierInfo *II = Namespace->getIdentifier(); 15075 Namespaces.push_back(II); 15076 NamedDecl *Lookup = SemaRef.LookupSingleName( 15077 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15078 if (Lookup == Namespace) 15079 break; 15080 } 15081 15082 // Once we have all the namespaces, reverse them to go outermost first, and 15083 // build an NNS. 15084 SmallString<64> Insertion; 15085 llvm::raw_svector_ostream OS(Insertion); 15086 if (DC->isTranslationUnit()) 15087 OS << "::"; 15088 std::reverse(Namespaces.begin(), Namespaces.end()); 15089 for (auto *II : Namespaces) 15090 OS << II->getName() << "::"; 15091 return FixItHint::CreateInsertion(NameLoc, Insertion); 15092 } 15093 15094 /// Determine whether a tag originally declared in context \p OldDC can 15095 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15096 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15097 /// using-declaration). 15098 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15099 DeclContext *NewDC) { 15100 OldDC = OldDC->getRedeclContext(); 15101 NewDC = NewDC->getRedeclContext(); 15102 15103 if (OldDC->Equals(NewDC)) 15104 return true; 15105 15106 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15107 // encloses the other). 15108 if (S.getLangOpts().MSVCCompat && 15109 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15110 return true; 15111 15112 return false; 15113 } 15114 15115 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15116 /// former case, Name will be non-null. In the later case, Name will be null. 15117 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15118 /// reference/declaration/definition of a tag. 15119 /// 15120 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15121 /// trailing-type-specifier) other than one in an alias-declaration. 15122 /// 15123 /// \param SkipBody If non-null, will be set to indicate if the caller should 15124 /// skip the definition of this tag and treat it as if it were a declaration. 15125 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15126 SourceLocation KWLoc, CXXScopeSpec &SS, 15127 IdentifierInfo *Name, SourceLocation NameLoc, 15128 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15129 SourceLocation ModulePrivateLoc, 15130 MultiTemplateParamsArg TemplateParameterLists, 15131 bool &OwnedDecl, bool &IsDependent, 15132 SourceLocation ScopedEnumKWLoc, 15133 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15134 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15135 SkipBodyInfo *SkipBody) { 15136 // If this is not a definition, it must have a name. 15137 IdentifierInfo *OrigName = Name; 15138 assert((Name != nullptr || TUK == TUK_Definition) && 15139 "Nameless record must be a definition!"); 15140 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15141 15142 OwnedDecl = false; 15143 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15144 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15145 15146 // FIXME: Check member specializations more carefully. 15147 bool isMemberSpecialization = false; 15148 bool Invalid = false; 15149 15150 // We only need to do this matching if we have template parameters 15151 // or a scope specifier, which also conveniently avoids this work 15152 // for non-C++ cases. 15153 if (TemplateParameterLists.size() > 0 || 15154 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15155 if (TemplateParameterList *TemplateParams = 15156 MatchTemplateParametersToScopeSpecifier( 15157 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15158 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15159 if (Kind == TTK_Enum) { 15160 Diag(KWLoc, diag::err_enum_template); 15161 return nullptr; 15162 } 15163 15164 if (TemplateParams->size() > 0) { 15165 // This is a declaration or definition of a class template (which may 15166 // be a member of another template). 15167 15168 if (Invalid) 15169 return nullptr; 15170 15171 OwnedDecl = false; 15172 DeclResult Result = CheckClassTemplate( 15173 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15174 AS, ModulePrivateLoc, 15175 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15176 TemplateParameterLists.data(), SkipBody); 15177 return Result.get(); 15178 } else { 15179 // The "template<>" header is extraneous. 15180 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15181 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15182 isMemberSpecialization = true; 15183 } 15184 } 15185 } 15186 15187 // Figure out the underlying type if this a enum declaration. We need to do 15188 // this early, because it's needed to detect if this is an incompatible 15189 // redeclaration. 15190 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15191 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15192 15193 if (Kind == TTK_Enum) { 15194 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15195 // No underlying type explicitly specified, or we failed to parse the 15196 // type, default to int. 15197 EnumUnderlying = Context.IntTy.getTypePtr(); 15198 } else if (UnderlyingType.get()) { 15199 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15200 // integral type; any cv-qualification is ignored. 15201 TypeSourceInfo *TI = nullptr; 15202 GetTypeFromParser(UnderlyingType.get(), &TI); 15203 EnumUnderlying = TI; 15204 15205 if (CheckEnumUnderlyingType(TI)) 15206 // Recover by falling back to int. 15207 EnumUnderlying = Context.IntTy.getTypePtr(); 15208 15209 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15210 UPPC_FixedUnderlyingType)) 15211 EnumUnderlying = Context.IntTy.getTypePtr(); 15212 15213 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15214 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15215 // of 'int'. However, if this is an unfixed forward declaration, don't set 15216 // the underlying type unless the user enables -fms-compatibility. This 15217 // makes unfixed forward declared enums incomplete and is more conforming. 15218 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15219 EnumUnderlying = Context.IntTy.getTypePtr(); 15220 } 15221 } 15222 15223 DeclContext *SearchDC = CurContext; 15224 DeclContext *DC = CurContext; 15225 bool isStdBadAlloc = false; 15226 bool isStdAlignValT = false; 15227 15228 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15229 if (TUK == TUK_Friend || TUK == TUK_Reference) 15230 Redecl = NotForRedeclaration; 15231 15232 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15233 /// implemented asks for structural equivalence checking, the returned decl 15234 /// here is passed back to the parser, allowing the tag body to be parsed. 15235 auto createTagFromNewDecl = [&]() -> TagDecl * { 15236 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15237 // If there is an identifier, use the location of the identifier as the 15238 // location of the decl, otherwise use the location of the struct/union 15239 // keyword. 15240 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15241 TagDecl *New = nullptr; 15242 15243 if (Kind == TTK_Enum) { 15244 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15245 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15246 // If this is an undefined enum, bail. 15247 if (TUK != TUK_Definition && !Invalid) 15248 return nullptr; 15249 if (EnumUnderlying) { 15250 EnumDecl *ED = cast<EnumDecl>(New); 15251 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15252 ED->setIntegerTypeSourceInfo(TI); 15253 else 15254 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15255 ED->setPromotionType(ED->getIntegerType()); 15256 } 15257 } else { // struct/union 15258 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15259 nullptr); 15260 } 15261 15262 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15263 // Add alignment attributes if necessary; these attributes are checked 15264 // when the ASTContext lays out the structure. 15265 // 15266 // It is important for implementing the correct semantics that this 15267 // happen here (in ActOnTag). The #pragma pack stack is 15268 // maintained as a result of parser callbacks which can occur at 15269 // many points during the parsing of a struct declaration (because 15270 // the #pragma tokens are effectively skipped over during the 15271 // parsing of the struct). 15272 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15273 AddAlignmentAttributesForRecord(RD); 15274 AddMsStructLayoutForRecord(RD); 15275 } 15276 } 15277 New->setLexicalDeclContext(CurContext); 15278 return New; 15279 }; 15280 15281 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15282 if (Name && SS.isNotEmpty()) { 15283 // We have a nested-name tag ('struct foo::bar'). 15284 15285 // Check for invalid 'foo::'. 15286 if (SS.isInvalid()) { 15287 Name = nullptr; 15288 goto CreateNewDecl; 15289 } 15290 15291 // If this is a friend or a reference to a class in a dependent 15292 // context, don't try to make a decl for it. 15293 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15294 DC = computeDeclContext(SS, false); 15295 if (!DC) { 15296 IsDependent = true; 15297 return nullptr; 15298 } 15299 } else { 15300 DC = computeDeclContext(SS, true); 15301 if (!DC) { 15302 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15303 << SS.getRange(); 15304 return nullptr; 15305 } 15306 } 15307 15308 if (RequireCompleteDeclContext(SS, DC)) 15309 return nullptr; 15310 15311 SearchDC = DC; 15312 // Look-up name inside 'foo::'. 15313 LookupQualifiedName(Previous, DC); 15314 15315 if (Previous.isAmbiguous()) 15316 return nullptr; 15317 15318 if (Previous.empty()) { 15319 // Name lookup did not find anything. However, if the 15320 // nested-name-specifier refers to the current instantiation, 15321 // and that current instantiation has any dependent base 15322 // classes, we might find something at instantiation time: treat 15323 // this as a dependent elaborated-type-specifier. 15324 // But this only makes any sense for reference-like lookups. 15325 if (Previous.wasNotFoundInCurrentInstantiation() && 15326 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15327 IsDependent = true; 15328 return nullptr; 15329 } 15330 15331 // A tag 'foo::bar' must already exist. 15332 Diag(NameLoc, diag::err_not_tag_in_scope) 15333 << Kind << Name << DC << SS.getRange(); 15334 Name = nullptr; 15335 Invalid = true; 15336 goto CreateNewDecl; 15337 } 15338 } else if (Name) { 15339 // C++14 [class.mem]p14: 15340 // If T is the name of a class, then each of the following shall have a 15341 // name different from T: 15342 // -- every member of class T that is itself a type 15343 if (TUK != TUK_Reference && TUK != TUK_Friend && 15344 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15345 return nullptr; 15346 15347 // If this is a named struct, check to see if there was a previous forward 15348 // declaration or definition. 15349 // FIXME: We're looking into outer scopes here, even when we 15350 // shouldn't be. Doing so can result in ambiguities that we 15351 // shouldn't be diagnosing. 15352 LookupName(Previous, S); 15353 15354 // When declaring or defining a tag, ignore ambiguities introduced 15355 // by types using'ed into this scope. 15356 if (Previous.isAmbiguous() && 15357 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15358 LookupResult::Filter F = Previous.makeFilter(); 15359 while (F.hasNext()) { 15360 NamedDecl *ND = F.next(); 15361 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15362 SearchDC->getRedeclContext())) 15363 F.erase(); 15364 } 15365 F.done(); 15366 } 15367 15368 // C++11 [namespace.memdef]p3: 15369 // If the name in a friend declaration is neither qualified nor 15370 // a template-id and the declaration is a function or an 15371 // elaborated-type-specifier, the lookup to determine whether 15372 // the entity has been previously declared shall not consider 15373 // any scopes outside the innermost enclosing namespace. 15374 // 15375 // MSVC doesn't implement the above rule for types, so a friend tag 15376 // declaration may be a redeclaration of a type declared in an enclosing 15377 // scope. They do implement this rule for friend functions. 15378 // 15379 // Does it matter that this should be by scope instead of by 15380 // semantic context? 15381 if (!Previous.empty() && TUK == TUK_Friend) { 15382 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15383 LookupResult::Filter F = Previous.makeFilter(); 15384 bool FriendSawTagOutsideEnclosingNamespace = false; 15385 while (F.hasNext()) { 15386 NamedDecl *ND = F.next(); 15387 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15388 if (DC->isFileContext() && 15389 !EnclosingNS->Encloses(ND->getDeclContext())) { 15390 if (getLangOpts().MSVCCompat) 15391 FriendSawTagOutsideEnclosingNamespace = true; 15392 else 15393 F.erase(); 15394 } 15395 } 15396 F.done(); 15397 15398 // Diagnose this MSVC extension in the easy case where lookup would have 15399 // unambiguously found something outside the enclosing namespace. 15400 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15401 NamedDecl *ND = Previous.getFoundDecl(); 15402 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15403 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15404 } 15405 } 15406 15407 // Note: there used to be some attempt at recovery here. 15408 if (Previous.isAmbiguous()) 15409 return nullptr; 15410 15411 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15412 // FIXME: This makes sure that we ignore the contexts associated 15413 // with C structs, unions, and enums when looking for a matching 15414 // tag declaration or definition. See the similar lookup tweak 15415 // in Sema::LookupName; is there a better way to deal with this? 15416 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15417 SearchDC = SearchDC->getParent(); 15418 } 15419 } 15420 15421 if (Previous.isSingleResult() && 15422 Previous.getFoundDecl()->isTemplateParameter()) { 15423 // Maybe we will complain about the shadowed template parameter. 15424 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15425 // Just pretend that we didn't see the previous declaration. 15426 Previous.clear(); 15427 } 15428 15429 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15430 DC->Equals(getStdNamespace())) { 15431 if (Name->isStr("bad_alloc")) { 15432 // This is a declaration of or a reference to "std::bad_alloc". 15433 isStdBadAlloc = true; 15434 15435 // If std::bad_alloc has been implicitly declared (but made invisible to 15436 // name lookup), fill in this implicit declaration as the previous 15437 // declaration, so that the declarations get chained appropriately. 15438 if (Previous.empty() && StdBadAlloc) 15439 Previous.addDecl(getStdBadAlloc()); 15440 } else if (Name->isStr("align_val_t")) { 15441 isStdAlignValT = true; 15442 if (Previous.empty() && StdAlignValT) 15443 Previous.addDecl(getStdAlignValT()); 15444 } 15445 } 15446 15447 // If we didn't find a previous declaration, and this is a reference 15448 // (or friend reference), move to the correct scope. In C++, we 15449 // also need to do a redeclaration lookup there, just in case 15450 // there's a shadow friend decl. 15451 if (Name && Previous.empty() && 15452 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15453 if (Invalid) goto CreateNewDecl; 15454 assert(SS.isEmpty()); 15455 15456 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15457 // C++ [basic.scope.pdecl]p5: 15458 // -- for an elaborated-type-specifier of the form 15459 // 15460 // class-key identifier 15461 // 15462 // if the elaborated-type-specifier is used in the 15463 // decl-specifier-seq or parameter-declaration-clause of a 15464 // function defined in namespace scope, the identifier is 15465 // declared as a class-name in the namespace that contains 15466 // the declaration; otherwise, except as a friend 15467 // declaration, the identifier is declared in the smallest 15468 // non-class, non-function-prototype scope that contains the 15469 // declaration. 15470 // 15471 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15472 // C structs and unions. 15473 // 15474 // It is an error in C++ to declare (rather than define) an enum 15475 // type, including via an elaborated type specifier. We'll 15476 // diagnose that later; for now, declare the enum in the same 15477 // scope as we would have picked for any other tag type. 15478 // 15479 // GNU C also supports this behavior as part of its incomplete 15480 // enum types extension, while GNU C++ does not. 15481 // 15482 // Find the context where we'll be declaring the tag. 15483 // FIXME: We would like to maintain the current DeclContext as the 15484 // lexical context, 15485 SearchDC = getTagInjectionContext(SearchDC); 15486 15487 // Find the scope where we'll be declaring the tag. 15488 S = getTagInjectionScope(S, getLangOpts()); 15489 } else { 15490 assert(TUK == TUK_Friend); 15491 // C++ [namespace.memdef]p3: 15492 // If a friend declaration in a non-local class first declares a 15493 // class or function, the friend class or function is a member of 15494 // the innermost enclosing namespace. 15495 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15496 } 15497 15498 // In C++, we need to do a redeclaration lookup to properly 15499 // diagnose some problems. 15500 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15501 // hidden declaration so that we don't get ambiguity errors when using a 15502 // type declared by an elaborated-type-specifier. In C that is not correct 15503 // and we should instead merge compatible types found by lookup. 15504 if (getLangOpts().CPlusPlus) { 15505 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15506 LookupQualifiedName(Previous, SearchDC); 15507 } else { 15508 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15509 LookupName(Previous, S); 15510 } 15511 } 15512 15513 // If we have a known previous declaration to use, then use it. 15514 if (Previous.empty() && SkipBody && SkipBody->Previous) 15515 Previous.addDecl(SkipBody->Previous); 15516 15517 if (!Previous.empty()) { 15518 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15519 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15520 15521 // It's okay to have a tag decl in the same scope as a typedef 15522 // which hides a tag decl in the same scope. Finding this 15523 // insanity with a redeclaration lookup can only actually happen 15524 // in C++. 15525 // 15526 // This is also okay for elaborated-type-specifiers, which is 15527 // technically forbidden by the current standard but which is 15528 // okay according to the likely resolution of an open issue; 15529 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15530 if (getLangOpts().CPlusPlus) { 15531 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15532 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15533 TagDecl *Tag = TT->getDecl(); 15534 if (Tag->getDeclName() == Name && 15535 Tag->getDeclContext()->getRedeclContext() 15536 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15537 PrevDecl = Tag; 15538 Previous.clear(); 15539 Previous.addDecl(Tag); 15540 Previous.resolveKind(); 15541 } 15542 } 15543 } 15544 } 15545 15546 // If this is a redeclaration of a using shadow declaration, it must 15547 // declare a tag in the same context. In MSVC mode, we allow a 15548 // redefinition if either context is within the other. 15549 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15550 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15551 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15552 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15553 !(OldTag && isAcceptableTagRedeclContext( 15554 *this, OldTag->getDeclContext(), SearchDC))) { 15555 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15556 Diag(Shadow->getTargetDecl()->getLocation(), 15557 diag::note_using_decl_target); 15558 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15559 << 0; 15560 // Recover by ignoring the old declaration. 15561 Previous.clear(); 15562 goto CreateNewDecl; 15563 } 15564 } 15565 15566 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15567 // If this is a use of a previous tag, or if the tag is already declared 15568 // in the same scope (so that the definition/declaration completes or 15569 // rementions the tag), reuse the decl. 15570 if (TUK == TUK_Reference || TUK == TUK_Friend || 15571 isDeclInScope(DirectPrevDecl, SearchDC, S, 15572 SS.isNotEmpty() || isMemberSpecialization)) { 15573 // Make sure that this wasn't declared as an enum and now used as a 15574 // struct or something similar. 15575 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15576 TUK == TUK_Definition, KWLoc, 15577 Name)) { 15578 bool SafeToContinue 15579 = (PrevTagDecl->getTagKind() != TTK_Enum && 15580 Kind != TTK_Enum); 15581 if (SafeToContinue) 15582 Diag(KWLoc, diag::err_use_with_wrong_tag) 15583 << Name 15584 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15585 PrevTagDecl->getKindName()); 15586 else 15587 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15588 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15589 15590 if (SafeToContinue) 15591 Kind = PrevTagDecl->getTagKind(); 15592 else { 15593 // Recover by making this an anonymous redefinition. 15594 Name = nullptr; 15595 Previous.clear(); 15596 Invalid = true; 15597 } 15598 } 15599 15600 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15601 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15602 15603 // If this is an elaborated-type-specifier for a scoped enumeration, 15604 // the 'class' keyword is not necessary and not permitted. 15605 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15606 if (ScopedEnum) 15607 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15608 << PrevEnum->isScoped() 15609 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15610 return PrevTagDecl; 15611 } 15612 15613 QualType EnumUnderlyingTy; 15614 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15615 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15616 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15617 EnumUnderlyingTy = QualType(T, 0); 15618 15619 // All conflicts with previous declarations are recovered by 15620 // returning the previous declaration, unless this is a definition, 15621 // in which case we want the caller to bail out. 15622 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15623 ScopedEnum, EnumUnderlyingTy, 15624 IsFixed, PrevEnum)) 15625 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15626 } 15627 15628 // C++11 [class.mem]p1: 15629 // A member shall not be declared twice in the member-specification, 15630 // except that a nested class or member class template can be declared 15631 // and then later defined. 15632 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15633 S->isDeclScope(PrevDecl)) { 15634 Diag(NameLoc, diag::ext_member_redeclared); 15635 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15636 } 15637 15638 if (!Invalid) { 15639 // If this is a use, just return the declaration we found, unless 15640 // we have attributes. 15641 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15642 if (!Attrs.empty()) { 15643 // FIXME: Diagnose these attributes. For now, we create a new 15644 // declaration to hold them. 15645 } else if (TUK == TUK_Reference && 15646 (PrevTagDecl->getFriendObjectKind() == 15647 Decl::FOK_Undeclared || 15648 PrevDecl->getOwningModule() != getCurrentModule()) && 15649 SS.isEmpty()) { 15650 // This declaration is a reference to an existing entity, but 15651 // has different visibility from that entity: it either makes 15652 // a friend visible or it makes a type visible in a new module. 15653 // In either case, create a new declaration. We only do this if 15654 // the declaration would have meant the same thing if no prior 15655 // declaration were found, that is, if it was found in the same 15656 // scope where we would have injected a declaration. 15657 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15658 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15659 return PrevTagDecl; 15660 // This is in the injected scope, create a new declaration in 15661 // that scope. 15662 S = getTagInjectionScope(S, getLangOpts()); 15663 } else { 15664 return PrevTagDecl; 15665 } 15666 } 15667 15668 // Diagnose attempts to redefine a tag. 15669 if (TUK == TUK_Definition) { 15670 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15671 // If we're defining a specialization and the previous definition 15672 // is from an implicit instantiation, don't emit an error 15673 // here; we'll catch this in the general case below. 15674 bool IsExplicitSpecializationAfterInstantiation = false; 15675 if (isMemberSpecialization) { 15676 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15677 IsExplicitSpecializationAfterInstantiation = 15678 RD->getTemplateSpecializationKind() != 15679 TSK_ExplicitSpecialization; 15680 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15681 IsExplicitSpecializationAfterInstantiation = 15682 ED->getTemplateSpecializationKind() != 15683 TSK_ExplicitSpecialization; 15684 } 15685 15686 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15687 // not keep more that one definition around (merge them). However, 15688 // ensure the decl passes the structural compatibility check in 15689 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15690 NamedDecl *Hidden = nullptr; 15691 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15692 // There is a definition of this tag, but it is not visible. We 15693 // explicitly make use of C++'s one definition rule here, and 15694 // assume that this definition is identical to the hidden one 15695 // we already have. Make the existing definition visible and 15696 // use it in place of this one. 15697 if (!getLangOpts().CPlusPlus) { 15698 // Postpone making the old definition visible until after we 15699 // complete parsing the new one and do the structural 15700 // comparison. 15701 SkipBody->CheckSameAsPrevious = true; 15702 SkipBody->New = createTagFromNewDecl(); 15703 SkipBody->Previous = Def; 15704 return Def; 15705 } else { 15706 SkipBody->ShouldSkip = true; 15707 SkipBody->Previous = Def; 15708 makeMergedDefinitionVisible(Hidden); 15709 // Carry on and handle it like a normal definition. We'll 15710 // skip starting the definitiion later. 15711 } 15712 } else if (!IsExplicitSpecializationAfterInstantiation) { 15713 // A redeclaration in function prototype scope in C isn't 15714 // visible elsewhere, so merely issue a warning. 15715 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15716 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15717 else 15718 Diag(NameLoc, diag::err_redefinition) << Name; 15719 notePreviousDefinition(Def, 15720 NameLoc.isValid() ? NameLoc : KWLoc); 15721 // If this is a redefinition, recover by making this 15722 // struct be anonymous, which will make any later 15723 // references get the previous definition. 15724 Name = nullptr; 15725 Previous.clear(); 15726 Invalid = true; 15727 } 15728 } else { 15729 // If the type is currently being defined, complain 15730 // about a nested redefinition. 15731 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15732 if (TD->isBeingDefined()) { 15733 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15734 Diag(PrevTagDecl->getLocation(), 15735 diag::note_previous_definition); 15736 Name = nullptr; 15737 Previous.clear(); 15738 Invalid = true; 15739 } 15740 } 15741 15742 // Okay, this is definition of a previously declared or referenced 15743 // tag. We're going to create a new Decl for it. 15744 } 15745 15746 // Okay, we're going to make a redeclaration. If this is some kind 15747 // of reference, make sure we build the redeclaration in the same DC 15748 // as the original, and ignore the current access specifier. 15749 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15750 SearchDC = PrevTagDecl->getDeclContext(); 15751 AS = AS_none; 15752 } 15753 } 15754 // If we get here we have (another) forward declaration or we 15755 // have a definition. Just create a new decl. 15756 15757 } else { 15758 // If we get here, this is a definition of a new tag type in a nested 15759 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15760 // new decl/type. We set PrevDecl to NULL so that the entities 15761 // have distinct types. 15762 Previous.clear(); 15763 } 15764 // If we get here, we're going to create a new Decl. If PrevDecl 15765 // is non-NULL, it's a definition of the tag declared by 15766 // PrevDecl. If it's NULL, we have a new definition. 15767 15768 // Otherwise, PrevDecl is not a tag, but was found with tag 15769 // lookup. This is only actually possible in C++, where a few 15770 // things like templates still live in the tag namespace. 15771 } else { 15772 // Use a better diagnostic if an elaborated-type-specifier 15773 // found the wrong kind of type on the first 15774 // (non-redeclaration) lookup. 15775 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15776 !Previous.isForRedeclaration()) { 15777 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15778 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15779 << Kind; 15780 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15781 Invalid = true; 15782 15783 // Otherwise, only diagnose if the declaration is in scope. 15784 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15785 SS.isNotEmpty() || isMemberSpecialization)) { 15786 // do nothing 15787 15788 // Diagnose implicit declarations introduced by elaborated types. 15789 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15790 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15791 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15792 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15793 Invalid = true; 15794 15795 // Otherwise it's a declaration. Call out a particularly common 15796 // case here. 15797 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15798 unsigned Kind = 0; 15799 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15800 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15801 << Name << Kind << TND->getUnderlyingType(); 15802 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15803 Invalid = true; 15804 15805 // Otherwise, diagnose. 15806 } else { 15807 // The tag name clashes with something else in the target scope, 15808 // issue an error and recover by making this tag be anonymous. 15809 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15810 notePreviousDefinition(PrevDecl, NameLoc); 15811 Name = nullptr; 15812 Invalid = true; 15813 } 15814 15815 // The existing declaration isn't relevant to us; we're in a 15816 // new scope, so clear out the previous declaration. 15817 Previous.clear(); 15818 } 15819 } 15820 15821 CreateNewDecl: 15822 15823 TagDecl *PrevDecl = nullptr; 15824 if (Previous.isSingleResult()) 15825 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15826 15827 // If there is an identifier, use the location of the identifier as the 15828 // location of the decl, otherwise use the location of the struct/union 15829 // keyword. 15830 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15831 15832 // Otherwise, create a new declaration. If there is a previous 15833 // declaration of the same entity, the two will be linked via 15834 // PrevDecl. 15835 TagDecl *New; 15836 15837 if (Kind == TTK_Enum) { 15838 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15839 // enum X { A, B, C } D; D should chain to X. 15840 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15841 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15842 ScopedEnumUsesClassTag, IsFixed); 15843 15844 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15845 StdAlignValT = cast<EnumDecl>(New); 15846 15847 // If this is an undefined enum, warn. 15848 if (TUK != TUK_Definition && !Invalid) { 15849 TagDecl *Def; 15850 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15851 // C++0x: 7.2p2: opaque-enum-declaration. 15852 // Conflicts are diagnosed above. Do nothing. 15853 } 15854 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15855 Diag(Loc, diag::ext_forward_ref_enum_def) 15856 << New; 15857 Diag(Def->getLocation(), diag::note_previous_definition); 15858 } else { 15859 unsigned DiagID = diag::ext_forward_ref_enum; 15860 if (getLangOpts().MSVCCompat) 15861 DiagID = diag::ext_ms_forward_ref_enum; 15862 else if (getLangOpts().CPlusPlus) 15863 DiagID = diag::err_forward_ref_enum; 15864 Diag(Loc, DiagID); 15865 } 15866 } 15867 15868 if (EnumUnderlying) { 15869 EnumDecl *ED = cast<EnumDecl>(New); 15870 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15871 ED->setIntegerTypeSourceInfo(TI); 15872 else 15873 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15874 ED->setPromotionType(ED->getIntegerType()); 15875 assert(ED->isComplete() && "enum with type should be complete"); 15876 } 15877 } else { 15878 // struct/union/class 15879 15880 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15881 // struct X { int A; } D; D should chain to X. 15882 if (getLangOpts().CPlusPlus) { 15883 // FIXME: Look for a way to use RecordDecl for simple structs. 15884 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15885 cast_or_null<CXXRecordDecl>(PrevDecl)); 15886 15887 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15888 StdBadAlloc = cast<CXXRecordDecl>(New); 15889 } else 15890 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15891 cast_or_null<RecordDecl>(PrevDecl)); 15892 } 15893 15894 // C++11 [dcl.type]p3: 15895 // A type-specifier-seq shall not define a class or enumeration [...]. 15896 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15897 TUK == TUK_Definition) { 15898 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15899 << Context.getTagDeclType(New); 15900 Invalid = true; 15901 } 15902 15903 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15904 DC->getDeclKind() == Decl::Enum) { 15905 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15906 << Context.getTagDeclType(New); 15907 Invalid = true; 15908 } 15909 15910 // Maybe add qualifier info. 15911 if (SS.isNotEmpty()) { 15912 if (SS.isSet()) { 15913 // If this is either a declaration or a definition, check the 15914 // nested-name-specifier against the current context. 15915 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15916 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15917 isMemberSpecialization)) 15918 Invalid = true; 15919 15920 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15921 if (TemplateParameterLists.size() > 0) { 15922 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15923 } 15924 } 15925 else 15926 Invalid = true; 15927 } 15928 15929 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15930 // Add alignment attributes if necessary; these attributes are checked when 15931 // the ASTContext lays out the structure. 15932 // 15933 // It is important for implementing the correct semantics that this 15934 // happen here (in ActOnTag). The #pragma pack stack is 15935 // maintained as a result of parser callbacks which can occur at 15936 // many points during the parsing of a struct declaration (because 15937 // the #pragma tokens are effectively skipped over during the 15938 // parsing of the struct). 15939 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15940 AddAlignmentAttributesForRecord(RD); 15941 AddMsStructLayoutForRecord(RD); 15942 } 15943 } 15944 15945 if (ModulePrivateLoc.isValid()) { 15946 if (isMemberSpecialization) 15947 Diag(New->getLocation(), diag::err_module_private_specialization) 15948 << 2 15949 << FixItHint::CreateRemoval(ModulePrivateLoc); 15950 // __module_private__ does not apply to local classes. However, we only 15951 // diagnose this as an error when the declaration specifiers are 15952 // freestanding. Here, we just ignore the __module_private__. 15953 else if (!SearchDC->isFunctionOrMethod()) 15954 New->setModulePrivate(); 15955 } 15956 15957 // If this is a specialization of a member class (of a class template), 15958 // check the specialization. 15959 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15960 Invalid = true; 15961 15962 // If we're declaring or defining a tag in function prototype scope in C, 15963 // note that this type can only be used within the function and add it to 15964 // the list of decls to inject into the function definition scope. 15965 if ((Name || Kind == TTK_Enum) && 15966 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15967 if (getLangOpts().CPlusPlus) { 15968 // C++ [dcl.fct]p6: 15969 // Types shall not be defined in return or parameter types. 15970 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15971 Diag(Loc, diag::err_type_defined_in_param_type) 15972 << Name; 15973 Invalid = true; 15974 } 15975 } else if (!PrevDecl) { 15976 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15977 } 15978 } 15979 15980 if (Invalid) 15981 New->setInvalidDecl(); 15982 15983 // Set the lexical context. If the tag has a C++ scope specifier, the 15984 // lexical context will be different from the semantic context. 15985 New->setLexicalDeclContext(CurContext); 15986 15987 // Mark this as a friend decl if applicable. 15988 // In Microsoft mode, a friend declaration also acts as a forward 15989 // declaration so we always pass true to setObjectOfFriendDecl to make 15990 // the tag name visible. 15991 if (TUK == TUK_Friend) 15992 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15993 15994 // Set the access specifier. 15995 if (!Invalid && SearchDC->isRecord()) 15996 SetMemberAccessSpecifier(New, PrevDecl, AS); 15997 15998 if (PrevDecl) 15999 CheckRedeclarationModuleOwnership(New, PrevDecl); 16000 16001 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16002 New->startDefinition(); 16003 16004 ProcessDeclAttributeList(S, New, Attrs); 16005 AddPragmaAttributes(S, New); 16006 16007 // If this has an identifier, add it to the scope stack. 16008 if (TUK == TUK_Friend) { 16009 // We might be replacing an existing declaration in the lookup tables; 16010 // if so, borrow its access specifier. 16011 if (PrevDecl) 16012 New->setAccess(PrevDecl->getAccess()); 16013 16014 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16015 DC->makeDeclVisibleInContext(New); 16016 if (Name) // can be null along some error paths 16017 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16018 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16019 } else if (Name) { 16020 S = getNonFieldDeclScope(S); 16021 PushOnScopeChains(New, S, true); 16022 } else { 16023 CurContext->addDecl(New); 16024 } 16025 16026 // If this is the C FILE type, notify the AST context. 16027 if (IdentifierInfo *II = New->getIdentifier()) 16028 if (!New->isInvalidDecl() && 16029 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16030 II->isStr("FILE")) 16031 Context.setFILEDecl(New); 16032 16033 if (PrevDecl) 16034 mergeDeclAttributes(New, PrevDecl); 16035 16036 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16037 inferGslOwnerPointerAttribute(CXXRD); 16038 16039 // If there's a #pragma GCC visibility in scope, set the visibility of this 16040 // record. 16041 AddPushedVisibilityAttribute(New); 16042 16043 if (isMemberSpecialization && !New->isInvalidDecl()) 16044 CompleteMemberSpecialization(New, Previous); 16045 16046 OwnedDecl = true; 16047 // In C++, don't return an invalid declaration. We can't recover well from 16048 // the cases where we make the type anonymous. 16049 if (Invalid && getLangOpts().CPlusPlus) { 16050 if (New->isBeingDefined()) 16051 if (auto RD = dyn_cast<RecordDecl>(New)) 16052 RD->completeDefinition(); 16053 return nullptr; 16054 } else if (SkipBody && SkipBody->ShouldSkip) { 16055 return SkipBody->Previous; 16056 } else { 16057 return New; 16058 } 16059 } 16060 16061 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16062 AdjustDeclIfTemplate(TagD); 16063 TagDecl *Tag = cast<TagDecl>(TagD); 16064 16065 // Enter the tag context. 16066 PushDeclContext(S, Tag); 16067 16068 ActOnDocumentableDecl(TagD); 16069 16070 // If there's a #pragma GCC visibility in scope, set the visibility of this 16071 // record. 16072 AddPushedVisibilityAttribute(Tag); 16073 } 16074 16075 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16076 SkipBodyInfo &SkipBody) { 16077 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16078 return false; 16079 16080 // Make the previous decl visible. 16081 makeMergedDefinitionVisible(SkipBody.Previous); 16082 return true; 16083 } 16084 16085 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16086 assert(isa<ObjCContainerDecl>(IDecl) && 16087 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16088 DeclContext *OCD = cast<DeclContext>(IDecl); 16089 assert(getContainingDC(OCD) == CurContext && 16090 "The next DeclContext should be lexically contained in the current one."); 16091 CurContext = OCD; 16092 return IDecl; 16093 } 16094 16095 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16096 SourceLocation FinalLoc, 16097 bool IsFinalSpelledSealed, 16098 SourceLocation LBraceLoc) { 16099 AdjustDeclIfTemplate(TagD); 16100 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16101 16102 FieldCollector->StartClass(); 16103 16104 if (!Record->getIdentifier()) 16105 return; 16106 16107 if (FinalLoc.isValid()) 16108 Record->addAttr(FinalAttr::Create( 16109 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16110 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16111 16112 // C++ [class]p2: 16113 // [...] The class-name is also inserted into the scope of the 16114 // class itself; this is known as the injected-class-name. For 16115 // purposes of access checking, the injected-class-name is treated 16116 // as if it were a public member name. 16117 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16118 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16119 Record->getLocation(), Record->getIdentifier(), 16120 /*PrevDecl=*/nullptr, 16121 /*DelayTypeCreation=*/true); 16122 Context.getTypeDeclType(InjectedClassName, Record); 16123 InjectedClassName->setImplicit(); 16124 InjectedClassName->setAccess(AS_public); 16125 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16126 InjectedClassName->setDescribedClassTemplate(Template); 16127 PushOnScopeChains(InjectedClassName, S); 16128 assert(InjectedClassName->isInjectedClassName() && 16129 "Broken injected-class-name"); 16130 } 16131 16132 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16133 SourceRange BraceRange) { 16134 AdjustDeclIfTemplate(TagD); 16135 TagDecl *Tag = cast<TagDecl>(TagD); 16136 Tag->setBraceRange(BraceRange); 16137 16138 // Make sure we "complete" the definition even it is invalid. 16139 if (Tag->isBeingDefined()) { 16140 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16141 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16142 RD->completeDefinition(); 16143 } 16144 16145 if (isa<CXXRecordDecl>(Tag)) { 16146 FieldCollector->FinishClass(); 16147 } 16148 16149 // Exit this scope of this tag's definition. 16150 PopDeclContext(); 16151 16152 if (getCurLexicalContext()->isObjCContainer() && 16153 Tag->getDeclContext()->isFileContext()) 16154 Tag->setTopLevelDeclInObjCContainer(); 16155 16156 // Notify the consumer that we've defined a tag. 16157 if (!Tag->isInvalidDecl()) 16158 Consumer.HandleTagDeclDefinition(Tag); 16159 } 16160 16161 void Sema::ActOnObjCContainerFinishDefinition() { 16162 // Exit this scope of this interface definition. 16163 PopDeclContext(); 16164 } 16165 16166 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16167 assert(DC == CurContext && "Mismatch of container contexts"); 16168 OriginalLexicalContext = DC; 16169 ActOnObjCContainerFinishDefinition(); 16170 } 16171 16172 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16173 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16174 OriginalLexicalContext = nullptr; 16175 } 16176 16177 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16178 AdjustDeclIfTemplate(TagD); 16179 TagDecl *Tag = cast<TagDecl>(TagD); 16180 Tag->setInvalidDecl(); 16181 16182 // Make sure we "complete" the definition even it is invalid. 16183 if (Tag->isBeingDefined()) { 16184 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16185 RD->completeDefinition(); 16186 } 16187 16188 // We're undoing ActOnTagStartDefinition here, not 16189 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16190 // the FieldCollector. 16191 16192 PopDeclContext(); 16193 } 16194 16195 // Note that FieldName may be null for anonymous bitfields. 16196 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16197 IdentifierInfo *FieldName, 16198 QualType FieldTy, bool IsMsStruct, 16199 Expr *BitWidth, bool *ZeroWidth) { 16200 assert(BitWidth); 16201 if (BitWidth->containsErrors()) 16202 return ExprError(); 16203 16204 // Default to true; that shouldn't confuse checks for emptiness 16205 if (ZeroWidth) 16206 *ZeroWidth = true; 16207 16208 // C99 6.7.2.1p4 - verify the field type. 16209 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16210 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16211 // Handle incomplete and sizeless types with a specific error. 16212 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16213 diag::err_field_incomplete_or_sizeless)) 16214 return ExprError(); 16215 if (FieldName) 16216 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16217 << FieldName << FieldTy << BitWidth->getSourceRange(); 16218 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16219 << FieldTy << BitWidth->getSourceRange(); 16220 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16221 UPPC_BitFieldWidth)) 16222 return ExprError(); 16223 16224 // If the bit-width is type- or value-dependent, don't try to check 16225 // it now. 16226 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16227 return BitWidth; 16228 16229 llvm::APSInt Value; 16230 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16231 if (ICE.isInvalid()) 16232 return ICE; 16233 BitWidth = ICE.get(); 16234 16235 if (Value != 0 && ZeroWidth) 16236 *ZeroWidth = false; 16237 16238 // Zero-width bitfield is ok for anonymous field. 16239 if (Value == 0 && FieldName) 16240 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16241 16242 if (Value.isSigned() && Value.isNegative()) { 16243 if (FieldName) 16244 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16245 << FieldName << Value.toString(10); 16246 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16247 << Value.toString(10); 16248 } 16249 16250 if (!FieldTy->isDependentType()) { 16251 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16252 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16253 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16254 16255 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16256 // ABI. 16257 bool CStdConstraintViolation = 16258 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16259 bool MSBitfieldViolation = 16260 Value.ugt(TypeStorageSize) && 16261 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16262 if (CStdConstraintViolation || MSBitfieldViolation) { 16263 unsigned DiagWidth = 16264 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16265 if (FieldName) 16266 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16267 << FieldName << (unsigned)Value.getZExtValue() 16268 << !CStdConstraintViolation << DiagWidth; 16269 16270 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16271 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16272 << DiagWidth; 16273 } 16274 16275 // Warn on types where the user might conceivably expect to get all 16276 // specified bits as value bits: that's all integral types other than 16277 // 'bool'. 16278 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16279 if (FieldName) 16280 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16281 << FieldName << (unsigned)Value.getZExtValue() 16282 << (unsigned)TypeWidth; 16283 else 16284 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16285 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16286 } 16287 } 16288 16289 return BitWidth; 16290 } 16291 16292 /// ActOnField - Each field of a C struct/union is passed into this in order 16293 /// to create a FieldDecl object for it. 16294 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16295 Declarator &D, Expr *BitfieldWidth) { 16296 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16297 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16298 /*InitStyle=*/ICIS_NoInit, AS_public); 16299 return Res; 16300 } 16301 16302 /// HandleField - Analyze a field of a C struct or a C++ data member. 16303 /// 16304 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16305 SourceLocation DeclStart, 16306 Declarator &D, Expr *BitWidth, 16307 InClassInitStyle InitStyle, 16308 AccessSpecifier AS) { 16309 if (D.isDecompositionDeclarator()) { 16310 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16311 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16312 << Decomp.getSourceRange(); 16313 return nullptr; 16314 } 16315 16316 IdentifierInfo *II = D.getIdentifier(); 16317 SourceLocation Loc = DeclStart; 16318 if (II) Loc = D.getIdentifierLoc(); 16319 16320 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16321 QualType T = TInfo->getType(); 16322 if (getLangOpts().CPlusPlus) { 16323 CheckExtraCXXDefaultArguments(D); 16324 16325 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16326 UPPC_DataMemberType)) { 16327 D.setInvalidType(); 16328 T = Context.IntTy; 16329 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16330 } 16331 } 16332 16333 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16334 16335 if (D.getDeclSpec().isInlineSpecified()) 16336 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16337 << getLangOpts().CPlusPlus17; 16338 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16339 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16340 diag::err_invalid_thread) 16341 << DeclSpec::getSpecifierName(TSCS); 16342 16343 // Check to see if this name was declared as a member previously 16344 NamedDecl *PrevDecl = nullptr; 16345 LookupResult Previous(*this, II, Loc, LookupMemberName, 16346 ForVisibleRedeclaration); 16347 LookupName(Previous, S); 16348 switch (Previous.getResultKind()) { 16349 case LookupResult::Found: 16350 case LookupResult::FoundUnresolvedValue: 16351 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16352 break; 16353 16354 case LookupResult::FoundOverloaded: 16355 PrevDecl = Previous.getRepresentativeDecl(); 16356 break; 16357 16358 case LookupResult::NotFound: 16359 case LookupResult::NotFoundInCurrentInstantiation: 16360 case LookupResult::Ambiguous: 16361 break; 16362 } 16363 Previous.suppressDiagnostics(); 16364 16365 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16366 // Maybe we will complain about the shadowed template parameter. 16367 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16368 // Just pretend that we didn't see the previous declaration. 16369 PrevDecl = nullptr; 16370 } 16371 16372 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16373 PrevDecl = nullptr; 16374 16375 bool Mutable 16376 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16377 SourceLocation TSSL = D.getBeginLoc(); 16378 FieldDecl *NewFD 16379 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16380 TSSL, AS, PrevDecl, &D); 16381 16382 if (NewFD->isInvalidDecl()) 16383 Record->setInvalidDecl(); 16384 16385 if (D.getDeclSpec().isModulePrivateSpecified()) 16386 NewFD->setModulePrivate(); 16387 16388 if (NewFD->isInvalidDecl() && PrevDecl) { 16389 // Don't introduce NewFD into scope; there's already something 16390 // with the same name in the same scope. 16391 } else if (II) { 16392 PushOnScopeChains(NewFD, S); 16393 } else 16394 Record->addDecl(NewFD); 16395 16396 return NewFD; 16397 } 16398 16399 /// Build a new FieldDecl and check its well-formedness. 16400 /// 16401 /// This routine builds a new FieldDecl given the fields name, type, 16402 /// record, etc. \p PrevDecl should refer to any previous declaration 16403 /// with the same name and in the same scope as the field to be 16404 /// created. 16405 /// 16406 /// \returns a new FieldDecl. 16407 /// 16408 /// \todo The Declarator argument is a hack. It will be removed once 16409 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16410 TypeSourceInfo *TInfo, 16411 RecordDecl *Record, SourceLocation Loc, 16412 bool Mutable, Expr *BitWidth, 16413 InClassInitStyle InitStyle, 16414 SourceLocation TSSL, 16415 AccessSpecifier AS, NamedDecl *PrevDecl, 16416 Declarator *D) { 16417 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16418 bool InvalidDecl = false; 16419 if (D) InvalidDecl = D->isInvalidType(); 16420 16421 // If we receive a broken type, recover by assuming 'int' and 16422 // marking this declaration as invalid. 16423 if (T.isNull()) { 16424 InvalidDecl = true; 16425 T = Context.IntTy; 16426 } 16427 16428 QualType EltTy = Context.getBaseElementType(T); 16429 if (!EltTy->isDependentType()) { 16430 if (RequireCompleteSizedType(Loc, EltTy, 16431 diag::err_field_incomplete_or_sizeless)) { 16432 // Fields of incomplete type force their record to be invalid. 16433 Record->setInvalidDecl(); 16434 InvalidDecl = true; 16435 } else { 16436 NamedDecl *Def; 16437 EltTy->isIncompleteType(&Def); 16438 if (Def && Def->isInvalidDecl()) { 16439 Record->setInvalidDecl(); 16440 InvalidDecl = true; 16441 } 16442 } 16443 } 16444 16445 // TR 18037 does not allow fields to be declared with address space 16446 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16447 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16448 Diag(Loc, diag::err_field_with_address_space); 16449 Record->setInvalidDecl(); 16450 InvalidDecl = true; 16451 } 16452 16453 if (LangOpts.OpenCL) { 16454 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16455 // used as structure or union field: image, sampler, event or block types. 16456 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16457 T->isBlockPointerType()) { 16458 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16459 Record->setInvalidDecl(); 16460 InvalidDecl = true; 16461 } 16462 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16463 if (BitWidth) { 16464 Diag(Loc, diag::err_opencl_bitfields); 16465 InvalidDecl = true; 16466 } 16467 } 16468 16469 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16470 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16471 T.hasQualifiers()) { 16472 InvalidDecl = true; 16473 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16474 } 16475 16476 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16477 // than a variably modified type. 16478 if (!InvalidDecl && T->isVariablyModifiedType()) { 16479 bool SizeIsNegative; 16480 llvm::APSInt Oversized; 16481 16482 TypeSourceInfo *FixedTInfo = 16483 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16484 SizeIsNegative, 16485 Oversized); 16486 if (FixedTInfo) { 16487 Diag(Loc, diag::warn_illegal_constant_array_size); 16488 TInfo = FixedTInfo; 16489 T = FixedTInfo->getType(); 16490 } else { 16491 if (SizeIsNegative) 16492 Diag(Loc, diag::err_typecheck_negative_array_size); 16493 else if (Oversized.getBoolValue()) 16494 Diag(Loc, diag::err_array_too_large) 16495 << Oversized.toString(10); 16496 else 16497 Diag(Loc, diag::err_typecheck_field_variable_size); 16498 InvalidDecl = true; 16499 } 16500 } 16501 16502 // Fields can not have abstract class types 16503 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16504 diag::err_abstract_type_in_decl, 16505 AbstractFieldType)) 16506 InvalidDecl = true; 16507 16508 bool ZeroWidth = false; 16509 if (InvalidDecl) 16510 BitWidth = nullptr; 16511 // If this is declared as a bit-field, check the bit-field. 16512 if (BitWidth) { 16513 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16514 &ZeroWidth).get(); 16515 if (!BitWidth) { 16516 InvalidDecl = true; 16517 BitWidth = nullptr; 16518 ZeroWidth = false; 16519 } 16520 } 16521 16522 // Check that 'mutable' is consistent with the type of the declaration. 16523 if (!InvalidDecl && Mutable) { 16524 unsigned DiagID = 0; 16525 if (T->isReferenceType()) 16526 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16527 : diag::err_mutable_reference; 16528 else if (T.isConstQualified()) 16529 DiagID = diag::err_mutable_const; 16530 16531 if (DiagID) { 16532 SourceLocation ErrLoc = Loc; 16533 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16534 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16535 Diag(ErrLoc, DiagID); 16536 if (DiagID != diag::ext_mutable_reference) { 16537 Mutable = false; 16538 InvalidDecl = true; 16539 } 16540 } 16541 } 16542 16543 // C++11 [class.union]p8 (DR1460): 16544 // At most one variant member of a union may have a 16545 // brace-or-equal-initializer. 16546 if (InitStyle != ICIS_NoInit) 16547 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16548 16549 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16550 BitWidth, Mutable, InitStyle); 16551 if (InvalidDecl) 16552 NewFD->setInvalidDecl(); 16553 16554 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16555 Diag(Loc, diag::err_duplicate_member) << II; 16556 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16557 NewFD->setInvalidDecl(); 16558 } 16559 16560 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16561 if (Record->isUnion()) { 16562 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16563 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16564 if (RDecl->getDefinition()) { 16565 // C++ [class.union]p1: An object of a class with a non-trivial 16566 // constructor, a non-trivial copy constructor, a non-trivial 16567 // destructor, or a non-trivial copy assignment operator 16568 // cannot be a member of a union, nor can an array of such 16569 // objects. 16570 if (CheckNontrivialField(NewFD)) 16571 NewFD->setInvalidDecl(); 16572 } 16573 } 16574 16575 // C++ [class.union]p1: If a union contains a member of reference type, 16576 // the program is ill-formed, except when compiling with MSVC extensions 16577 // enabled. 16578 if (EltTy->isReferenceType()) { 16579 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16580 diag::ext_union_member_of_reference_type : 16581 diag::err_union_member_of_reference_type) 16582 << NewFD->getDeclName() << EltTy; 16583 if (!getLangOpts().MicrosoftExt) 16584 NewFD->setInvalidDecl(); 16585 } 16586 } 16587 } 16588 16589 // FIXME: We need to pass in the attributes given an AST 16590 // representation, not a parser representation. 16591 if (D) { 16592 // FIXME: The current scope is almost... but not entirely... correct here. 16593 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16594 16595 if (NewFD->hasAttrs()) 16596 CheckAlignasUnderalignment(NewFD); 16597 } 16598 16599 // In auto-retain/release, infer strong retension for fields of 16600 // retainable type. 16601 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16602 NewFD->setInvalidDecl(); 16603 16604 if (T.isObjCGCWeak()) 16605 Diag(Loc, diag::warn_attribute_weak_on_field); 16606 16607 NewFD->setAccess(AS); 16608 return NewFD; 16609 } 16610 16611 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16612 assert(FD); 16613 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16614 16615 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16616 return false; 16617 16618 QualType EltTy = Context.getBaseElementType(FD->getType()); 16619 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16620 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16621 if (RDecl->getDefinition()) { 16622 // We check for copy constructors before constructors 16623 // because otherwise we'll never get complaints about 16624 // copy constructors. 16625 16626 CXXSpecialMember member = CXXInvalid; 16627 // We're required to check for any non-trivial constructors. Since the 16628 // implicit default constructor is suppressed if there are any 16629 // user-declared constructors, we just need to check that there is a 16630 // trivial default constructor and a trivial copy constructor. (We don't 16631 // worry about move constructors here, since this is a C++98 check.) 16632 if (RDecl->hasNonTrivialCopyConstructor()) 16633 member = CXXCopyConstructor; 16634 else if (!RDecl->hasTrivialDefaultConstructor()) 16635 member = CXXDefaultConstructor; 16636 else if (RDecl->hasNonTrivialCopyAssignment()) 16637 member = CXXCopyAssignment; 16638 else if (RDecl->hasNonTrivialDestructor()) 16639 member = CXXDestructor; 16640 16641 if (member != CXXInvalid) { 16642 if (!getLangOpts().CPlusPlus11 && 16643 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16644 // Objective-C++ ARC: it is an error to have a non-trivial field of 16645 // a union. However, system headers in Objective-C programs 16646 // occasionally have Objective-C lifetime objects within unions, 16647 // and rather than cause the program to fail, we make those 16648 // members unavailable. 16649 SourceLocation Loc = FD->getLocation(); 16650 if (getSourceManager().isInSystemHeader(Loc)) { 16651 if (!FD->hasAttr<UnavailableAttr>()) 16652 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16653 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16654 return false; 16655 } 16656 } 16657 16658 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16659 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16660 diag::err_illegal_union_or_anon_struct_member) 16661 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16662 DiagnoseNontrivial(RDecl, member); 16663 return !getLangOpts().CPlusPlus11; 16664 } 16665 } 16666 } 16667 16668 return false; 16669 } 16670 16671 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16672 /// AST enum value. 16673 static ObjCIvarDecl::AccessControl 16674 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16675 switch (ivarVisibility) { 16676 default: llvm_unreachable("Unknown visitibility kind"); 16677 case tok::objc_private: return ObjCIvarDecl::Private; 16678 case tok::objc_public: return ObjCIvarDecl::Public; 16679 case tok::objc_protected: return ObjCIvarDecl::Protected; 16680 case tok::objc_package: return ObjCIvarDecl::Package; 16681 } 16682 } 16683 16684 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16685 /// in order to create an IvarDecl object for it. 16686 Decl *Sema::ActOnIvar(Scope *S, 16687 SourceLocation DeclStart, 16688 Declarator &D, Expr *BitfieldWidth, 16689 tok::ObjCKeywordKind Visibility) { 16690 16691 IdentifierInfo *II = D.getIdentifier(); 16692 Expr *BitWidth = (Expr*)BitfieldWidth; 16693 SourceLocation Loc = DeclStart; 16694 if (II) Loc = D.getIdentifierLoc(); 16695 16696 // FIXME: Unnamed fields can be handled in various different ways, for 16697 // example, unnamed unions inject all members into the struct namespace! 16698 16699 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16700 QualType T = TInfo->getType(); 16701 16702 if (BitWidth) { 16703 // 6.7.2.1p3, 6.7.2.1p4 16704 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16705 if (!BitWidth) 16706 D.setInvalidType(); 16707 } else { 16708 // Not a bitfield. 16709 16710 // validate II. 16711 16712 } 16713 if (T->isReferenceType()) { 16714 Diag(Loc, diag::err_ivar_reference_type); 16715 D.setInvalidType(); 16716 } 16717 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16718 // than a variably modified type. 16719 else if (T->isVariablyModifiedType()) { 16720 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16721 D.setInvalidType(); 16722 } 16723 16724 // Get the visibility (access control) for this ivar. 16725 ObjCIvarDecl::AccessControl ac = 16726 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16727 : ObjCIvarDecl::None; 16728 // Must set ivar's DeclContext to its enclosing interface. 16729 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16730 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16731 return nullptr; 16732 ObjCContainerDecl *EnclosingContext; 16733 if (ObjCImplementationDecl *IMPDecl = 16734 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16735 if (LangOpts.ObjCRuntime.isFragile()) { 16736 // Case of ivar declared in an implementation. Context is that of its class. 16737 EnclosingContext = IMPDecl->getClassInterface(); 16738 assert(EnclosingContext && "Implementation has no class interface!"); 16739 } 16740 else 16741 EnclosingContext = EnclosingDecl; 16742 } else { 16743 if (ObjCCategoryDecl *CDecl = 16744 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16745 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16746 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16747 return nullptr; 16748 } 16749 } 16750 EnclosingContext = EnclosingDecl; 16751 } 16752 16753 // Construct the decl. 16754 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16755 DeclStart, Loc, II, T, 16756 TInfo, ac, (Expr *)BitfieldWidth); 16757 16758 if (II) { 16759 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16760 ForVisibleRedeclaration); 16761 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16762 && !isa<TagDecl>(PrevDecl)) { 16763 Diag(Loc, diag::err_duplicate_member) << II; 16764 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16765 NewID->setInvalidDecl(); 16766 } 16767 } 16768 16769 // Process attributes attached to the ivar. 16770 ProcessDeclAttributes(S, NewID, D); 16771 16772 if (D.isInvalidType()) 16773 NewID->setInvalidDecl(); 16774 16775 // In ARC, infer 'retaining' for ivars of retainable type. 16776 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16777 NewID->setInvalidDecl(); 16778 16779 if (D.getDeclSpec().isModulePrivateSpecified()) 16780 NewID->setModulePrivate(); 16781 16782 if (II) { 16783 // FIXME: When interfaces are DeclContexts, we'll need to add 16784 // these to the interface. 16785 S->AddDecl(NewID); 16786 IdResolver.AddDecl(NewID); 16787 } 16788 16789 if (LangOpts.ObjCRuntime.isNonFragile() && 16790 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16791 Diag(Loc, diag::warn_ivars_in_interface); 16792 16793 return NewID; 16794 } 16795 16796 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16797 /// class and class extensions. For every class \@interface and class 16798 /// extension \@interface, if the last ivar is a bitfield of any type, 16799 /// then add an implicit `char :0` ivar to the end of that interface. 16800 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16801 SmallVectorImpl<Decl *> &AllIvarDecls) { 16802 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16803 return; 16804 16805 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16806 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16807 16808 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16809 return; 16810 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16811 if (!ID) { 16812 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16813 if (!CD->IsClassExtension()) 16814 return; 16815 } 16816 // No need to add this to end of @implementation. 16817 else 16818 return; 16819 } 16820 // All conditions are met. Add a new bitfield to the tail end of ivars. 16821 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16822 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16823 16824 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16825 DeclLoc, DeclLoc, nullptr, 16826 Context.CharTy, 16827 Context.getTrivialTypeSourceInfo(Context.CharTy, 16828 DeclLoc), 16829 ObjCIvarDecl::Private, BW, 16830 true); 16831 AllIvarDecls.push_back(Ivar); 16832 } 16833 16834 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16835 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16836 SourceLocation RBrac, 16837 const ParsedAttributesView &Attrs) { 16838 assert(EnclosingDecl && "missing record or interface decl"); 16839 16840 // If this is an Objective-C @implementation or category and we have 16841 // new fields here we should reset the layout of the interface since 16842 // it will now change. 16843 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16844 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16845 switch (DC->getKind()) { 16846 default: break; 16847 case Decl::ObjCCategory: 16848 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16849 break; 16850 case Decl::ObjCImplementation: 16851 Context. 16852 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16853 break; 16854 } 16855 } 16856 16857 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16858 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16859 16860 // Start counting up the number of named members; make sure to include 16861 // members of anonymous structs and unions in the total. 16862 unsigned NumNamedMembers = 0; 16863 if (Record) { 16864 for (const auto *I : Record->decls()) { 16865 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16866 if (IFD->getDeclName()) 16867 ++NumNamedMembers; 16868 } 16869 } 16870 16871 // Verify that all the fields are okay. 16872 SmallVector<FieldDecl*, 32> RecFields; 16873 16874 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16875 i != end; ++i) { 16876 FieldDecl *FD = cast<FieldDecl>(*i); 16877 16878 // Get the type for the field. 16879 const Type *FDTy = FD->getType().getTypePtr(); 16880 16881 if (!FD->isAnonymousStructOrUnion()) { 16882 // Remember all fields written by the user. 16883 RecFields.push_back(FD); 16884 } 16885 16886 // If the field is already invalid for some reason, don't emit more 16887 // diagnostics about it. 16888 if (FD->isInvalidDecl()) { 16889 EnclosingDecl->setInvalidDecl(); 16890 continue; 16891 } 16892 16893 // C99 6.7.2.1p2: 16894 // A structure or union shall not contain a member with 16895 // incomplete or function type (hence, a structure shall not 16896 // contain an instance of itself, but may contain a pointer to 16897 // an instance of itself), except that the last member of a 16898 // structure with more than one named member may have incomplete 16899 // array type; such a structure (and any union containing, 16900 // possibly recursively, a member that is such a structure) 16901 // shall not be a member of a structure or an element of an 16902 // array. 16903 bool IsLastField = (i + 1 == Fields.end()); 16904 if (FDTy->isFunctionType()) { 16905 // Field declared as a function. 16906 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16907 << FD->getDeclName(); 16908 FD->setInvalidDecl(); 16909 EnclosingDecl->setInvalidDecl(); 16910 continue; 16911 } else if (FDTy->isIncompleteArrayType() && 16912 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16913 if (Record) { 16914 // Flexible array member. 16915 // Microsoft and g++ is more permissive regarding flexible array. 16916 // It will accept flexible array in union and also 16917 // as the sole element of a struct/class. 16918 unsigned DiagID = 0; 16919 if (!Record->isUnion() && !IsLastField) { 16920 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16921 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16922 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16923 FD->setInvalidDecl(); 16924 EnclosingDecl->setInvalidDecl(); 16925 continue; 16926 } else if (Record->isUnion()) 16927 DiagID = getLangOpts().MicrosoftExt 16928 ? diag::ext_flexible_array_union_ms 16929 : getLangOpts().CPlusPlus 16930 ? diag::ext_flexible_array_union_gnu 16931 : diag::err_flexible_array_union; 16932 else if (NumNamedMembers < 1) 16933 DiagID = getLangOpts().MicrosoftExt 16934 ? diag::ext_flexible_array_empty_aggregate_ms 16935 : getLangOpts().CPlusPlus 16936 ? diag::ext_flexible_array_empty_aggregate_gnu 16937 : diag::err_flexible_array_empty_aggregate; 16938 16939 if (DiagID) 16940 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16941 << Record->getTagKind(); 16942 // While the layout of types that contain virtual bases is not specified 16943 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16944 // virtual bases after the derived members. This would make a flexible 16945 // array member declared at the end of an object not adjacent to the end 16946 // of the type. 16947 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16948 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16949 << FD->getDeclName() << Record->getTagKind(); 16950 if (!getLangOpts().C99) 16951 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16952 << FD->getDeclName() << Record->getTagKind(); 16953 16954 // If the element type has a non-trivial destructor, we would not 16955 // implicitly destroy the elements, so disallow it for now. 16956 // 16957 // FIXME: GCC allows this. We should probably either implicitly delete 16958 // the destructor of the containing class, or just allow this. 16959 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16960 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16961 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16962 << FD->getDeclName() << FD->getType(); 16963 FD->setInvalidDecl(); 16964 EnclosingDecl->setInvalidDecl(); 16965 continue; 16966 } 16967 // Okay, we have a legal flexible array member at the end of the struct. 16968 Record->setHasFlexibleArrayMember(true); 16969 } else { 16970 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16971 // unless they are followed by another ivar. That check is done 16972 // elsewhere, after synthesized ivars are known. 16973 } 16974 } else if (!FDTy->isDependentType() && 16975 RequireCompleteSizedType( 16976 FD->getLocation(), FD->getType(), 16977 diag::err_field_incomplete_or_sizeless)) { 16978 // Incomplete type 16979 FD->setInvalidDecl(); 16980 EnclosingDecl->setInvalidDecl(); 16981 continue; 16982 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16983 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16984 // A type which contains a flexible array member is considered to be a 16985 // flexible array member. 16986 Record->setHasFlexibleArrayMember(true); 16987 if (!Record->isUnion()) { 16988 // If this is a struct/class and this is not the last element, reject 16989 // it. Note that GCC supports variable sized arrays in the middle of 16990 // structures. 16991 if (!IsLastField) 16992 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16993 << FD->getDeclName() << FD->getType(); 16994 else { 16995 // We support flexible arrays at the end of structs in 16996 // other structs as an extension. 16997 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16998 << FD->getDeclName(); 16999 } 17000 } 17001 } 17002 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17003 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17004 diag::err_abstract_type_in_decl, 17005 AbstractIvarType)) { 17006 // Ivars can not have abstract class types 17007 FD->setInvalidDecl(); 17008 } 17009 if (Record && FDTTy->getDecl()->hasObjectMember()) 17010 Record->setHasObjectMember(true); 17011 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17012 Record->setHasVolatileMember(true); 17013 } else if (FDTy->isObjCObjectType()) { 17014 /// A field cannot be an Objective-c object 17015 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17016 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17017 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17018 FD->setType(T); 17019 } else if (Record && Record->isUnion() && 17020 FD->getType().hasNonTrivialObjCLifetime() && 17021 getSourceManager().isInSystemHeader(FD->getLocation()) && 17022 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17023 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17024 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17025 // For backward compatibility, fields of C unions declared in system 17026 // headers that have non-trivial ObjC ownership qualifications are marked 17027 // as unavailable unless the qualifier is explicit and __strong. This can 17028 // break ABI compatibility between programs compiled with ARC and MRR, but 17029 // is a better option than rejecting programs using those unions under 17030 // ARC. 17031 FD->addAttr(UnavailableAttr::CreateImplicit( 17032 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17033 FD->getLocation())); 17034 } else if (getLangOpts().ObjC && 17035 getLangOpts().getGC() != LangOptions::NonGC && Record && 17036 !Record->hasObjectMember()) { 17037 if (FD->getType()->isObjCObjectPointerType() || 17038 FD->getType().isObjCGCStrong()) 17039 Record->setHasObjectMember(true); 17040 else if (Context.getAsArrayType(FD->getType())) { 17041 QualType BaseType = Context.getBaseElementType(FD->getType()); 17042 if (BaseType->isRecordType() && 17043 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17044 Record->setHasObjectMember(true); 17045 else if (BaseType->isObjCObjectPointerType() || 17046 BaseType.isObjCGCStrong()) 17047 Record->setHasObjectMember(true); 17048 } 17049 } 17050 17051 if (Record && !getLangOpts().CPlusPlus && 17052 !shouldIgnoreForRecordTriviality(FD)) { 17053 QualType FT = FD->getType(); 17054 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17055 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17056 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17057 Record->isUnion()) 17058 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17059 } 17060 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17061 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17062 Record->setNonTrivialToPrimitiveCopy(true); 17063 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17064 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17065 } 17066 if (FT.isDestructedType()) { 17067 Record->setNonTrivialToPrimitiveDestroy(true); 17068 Record->setParamDestroyedInCallee(true); 17069 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17070 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17071 } 17072 17073 if (const auto *RT = FT->getAs<RecordType>()) { 17074 if (RT->getDecl()->getArgPassingRestrictions() == 17075 RecordDecl::APK_CanNeverPassInRegs) 17076 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17077 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17078 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17079 } 17080 17081 if (Record && FD->getType().isVolatileQualified()) 17082 Record->setHasVolatileMember(true); 17083 // Keep track of the number of named members. 17084 if (FD->getIdentifier()) 17085 ++NumNamedMembers; 17086 } 17087 17088 // Okay, we successfully defined 'Record'. 17089 if (Record) { 17090 bool Completed = false; 17091 if (CXXRecord) { 17092 if (!CXXRecord->isInvalidDecl()) { 17093 // Set access bits correctly on the directly-declared conversions. 17094 for (CXXRecordDecl::conversion_iterator 17095 I = CXXRecord->conversion_begin(), 17096 E = CXXRecord->conversion_end(); I != E; ++I) 17097 I.setAccess((*I)->getAccess()); 17098 } 17099 17100 if (!CXXRecord->isDependentType()) { 17101 // Add any implicitly-declared members to this class. 17102 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17103 17104 if (!CXXRecord->isInvalidDecl()) { 17105 // If we have virtual base classes, we may end up finding multiple 17106 // final overriders for a given virtual function. Check for this 17107 // problem now. 17108 if (CXXRecord->getNumVBases()) { 17109 CXXFinalOverriderMap FinalOverriders; 17110 CXXRecord->getFinalOverriders(FinalOverriders); 17111 17112 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17113 MEnd = FinalOverriders.end(); 17114 M != MEnd; ++M) { 17115 for (OverridingMethods::iterator SO = M->second.begin(), 17116 SOEnd = M->second.end(); 17117 SO != SOEnd; ++SO) { 17118 assert(SO->second.size() > 0 && 17119 "Virtual function without overriding functions?"); 17120 if (SO->second.size() == 1) 17121 continue; 17122 17123 // C++ [class.virtual]p2: 17124 // In a derived class, if a virtual member function of a base 17125 // class subobject has more than one final overrider the 17126 // program is ill-formed. 17127 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17128 << (const NamedDecl *)M->first << Record; 17129 Diag(M->first->getLocation(), 17130 diag::note_overridden_virtual_function); 17131 for (OverridingMethods::overriding_iterator 17132 OM = SO->second.begin(), 17133 OMEnd = SO->second.end(); 17134 OM != OMEnd; ++OM) 17135 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17136 << (const NamedDecl *)M->first << OM->Method->getParent(); 17137 17138 Record->setInvalidDecl(); 17139 } 17140 } 17141 CXXRecord->completeDefinition(&FinalOverriders); 17142 Completed = true; 17143 } 17144 } 17145 } 17146 } 17147 17148 if (!Completed) 17149 Record->completeDefinition(); 17150 17151 // Handle attributes before checking the layout. 17152 ProcessDeclAttributeList(S, Record, Attrs); 17153 17154 // We may have deferred checking for a deleted destructor. Check now. 17155 if (CXXRecord) { 17156 auto *Dtor = CXXRecord->getDestructor(); 17157 if (Dtor && Dtor->isImplicit() && 17158 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17159 CXXRecord->setImplicitDestructorIsDeleted(); 17160 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17161 } 17162 } 17163 17164 if (Record->hasAttrs()) { 17165 CheckAlignasUnderalignment(Record); 17166 17167 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17168 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17169 IA->getRange(), IA->getBestCase(), 17170 IA->getInheritanceModel()); 17171 } 17172 17173 // Check if the structure/union declaration is a type that can have zero 17174 // size in C. For C this is a language extension, for C++ it may cause 17175 // compatibility problems. 17176 bool CheckForZeroSize; 17177 if (!getLangOpts().CPlusPlus) { 17178 CheckForZeroSize = true; 17179 } else { 17180 // For C++ filter out types that cannot be referenced in C code. 17181 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17182 CheckForZeroSize = 17183 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17184 !CXXRecord->isDependentType() && 17185 CXXRecord->isCLike(); 17186 } 17187 if (CheckForZeroSize) { 17188 bool ZeroSize = true; 17189 bool IsEmpty = true; 17190 unsigned NonBitFields = 0; 17191 for (RecordDecl::field_iterator I = Record->field_begin(), 17192 E = Record->field_end(); 17193 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17194 IsEmpty = false; 17195 if (I->isUnnamedBitfield()) { 17196 if (!I->isZeroLengthBitField(Context)) 17197 ZeroSize = false; 17198 } else { 17199 ++NonBitFields; 17200 QualType FieldType = I->getType(); 17201 if (FieldType->isIncompleteType() || 17202 !Context.getTypeSizeInChars(FieldType).isZero()) 17203 ZeroSize = false; 17204 } 17205 } 17206 17207 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17208 // allowed in C++, but warn if its declaration is inside 17209 // extern "C" block. 17210 if (ZeroSize) { 17211 Diag(RecLoc, getLangOpts().CPlusPlus ? 17212 diag::warn_zero_size_struct_union_in_extern_c : 17213 diag::warn_zero_size_struct_union_compat) 17214 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17215 } 17216 17217 // Structs without named members are extension in C (C99 6.7.2.1p7), 17218 // but are accepted by GCC. 17219 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17220 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17221 diag::ext_no_named_members_in_struct_union) 17222 << Record->isUnion(); 17223 } 17224 } 17225 } else { 17226 ObjCIvarDecl **ClsFields = 17227 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17228 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17229 ID->setEndOfDefinitionLoc(RBrac); 17230 // Add ivar's to class's DeclContext. 17231 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17232 ClsFields[i]->setLexicalDeclContext(ID); 17233 ID->addDecl(ClsFields[i]); 17234 } 17235 // Must enforce the rule that ivars in the base classes may not be 17236 // duplicates. 17237 if (ID->getSuperClass()) 17238 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17239 } else if (ObjCImplementationDecl *IMPDecl = 17240 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17241 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17242 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17243 // Ivar declared in @implementation never belongs to the implementation. 17244 // Only it is in implementation's lexical context. 17245 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17246 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17247 IMPDecl->setIvarLBraceLoc(LBrac); 17248 IMPDecl->setIvarRBraceLoc(RBrac); 17249 } else if (ObjCCategoryDecl *CDecl = 17250 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17251 // case of ivars in class extension; all other cases have been 17252 // reported as errors elsewhere. 17253 // FIXME. Class extension does not have a LocEnd field. 17254 // CDecl->setLocEnd(RBrac); 17255 // Add ivar's to class extension's DeclContext. 17256 // Diagnose redeclaration of private ivars. 17257 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17258 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17259 if (IDecl) { 17260 if (const ObjCIvarDecl *ClsIvar = 17261 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17262 Diag(ClsFields[i]->getLocation(), 17263 diag::err_duplicate_ivar_declaration); 17264 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17265 continue; 17266 } 17267 for (const auto *Ext : IDecl->known_extensions()) { 17268 if (const ObjCIvarDecl *ClsExtIvar 17269 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17270 Diag(ClsFields[i]->getLocation(), 17271 diag::err_duplicate_ivar_declaration); 17272 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17273 continue; 17274 } 17275 } 17276 } 17277 ClsFields[i]->setLexicalDeclContext(CDecl); 17278 CDecl->addDecl(ClsFields[i]); 17279 } 17280 CDecl->setIvarLBraceLoc(LBrac); 17281 CDecl->setIvarRBraceLoc(RBrac); 17282 } 17283 } 17284 } 17285 17286 /// Determine whether the given integral value is representable within 17287 /// the given type T. 17288 static bool isRepresentableIntegerValue(ASTContext &Context, 17289 llvm::APSInt &Value, 17290 QualType T) { 17291 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17292 "Integral type required!"); 17293 unsigned BitWidth = Context.getIntWidth(T); 17294 17295 if (Value.isUnsigned() || Value.isNonNegative()) { 17296 if (T->isSignedIntegerOrEnumerationType()) 17297 --BitWidth; 17298 return Value.getActiveBits() <= BitWidth; 17299 } 17300 return Value.getMinSignedBits() <= BitWidth; 17301 } 17302 17303 // Given an integral type, return the next larger integral type 17304 // (or a NULL type of no such type exists). 17305 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17306 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17307 // enum checking below. 17308 assert((T->isIntegralType(Context) || 17309 T->isEnumeralType()) && "Integral type required!"); 17310 const unsigned NumTypes = 4; 17311 QualType SignedIntegralTypes[NumTypes] = { 17312 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17313 }; 17314 QualType UnsignedIntegralTypes[NumTypes] = { 17315 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17316 Context.UnsignedLongLongTy 17317 }; 17318 17319 unsigned BitWidth = Context.getTypeSize(T); 17320 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17321 : UnsignedIntegralTypes; 17322 for (unsigned I = 0; I != NumTypes; ++I) 17323 if (Context.getTypeSize(Types[I]) > BitWidth) 17324 return Types[I]; 17325 17326 return QualType(); 17327 } 17328 17329 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17330 EnumConstantDecl *LastEnumConst, 17331 SourceLocation IdLoc, 17332 IdentifierInfo *Id, 17333 Expr *Val) { 17334 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17335 llvm::APSInt EnumVal(IntWidth); 17336 QualType EltTy; 17337 17338 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17339 Val = nullptr; 17340 17341 if (Val) 17342 Val = DefaultLvalueConversion(Val).get(); 17343 17344 if (Val) { 17345 if (Enum->isDependentType() || Val->isTypeDependent()) 17346 EltTy = Context.DependentTy; 17347 else { 17348 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17349 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17350 // constant-expression in the enumerator-definition shall be a converted 17351 // constant expression of the underlying type. 17352 EltTy = Enum->getIntegerType(); 17353 ExprResult Converted = 17354 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17355 CCEK_Enumerator); 17356 if (Converted.isInvalid()) 17357 Val = nullptr; 17358 else 17359 Val = Converted.get(); 17360 } else if (!Val->isValueDependent() && 17361 !(Val = VerifyIntegerConstantExpression(Val, 17362 &EnumVal).get())) { 17363 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17364 } else { 17365 if (Enum->isComplete()) { 17366 EltTy = Enum->getIntegerType(); 17367 17368 // In Obj-C and Microsoft mode, require the enumeration value to be 17369 // representable in the underlying type of the enumeration. In C++11, 17370 // we perform a non-narrowing conversion as part of converted constant 17371 // expression checking. 17372 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17373 if (Context.getTargetInfo() 17374 .getTriple() 17375 .isWindowsMSVCEnvironment()) { 17376 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17377 } else { 17378 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17379 } 17380 } 17381 17382 // Cast to the underlying type. 17383 Val = ImpCastExprToType(Val, EltTy, 17384 EltTy->isBooleanType() ? CK_IntegralToBoolean 17385 : CK_IntegralCast) 17386 .get(); 17387 } else if (getLangOpts().CPlusPlus) { 17388 // C++11 [dcl.enum]p5: 17389 // If the underlying type is not fixed, the type of each enumerator 17390 // is the type of its initializing value: 17391 // - If an initializer is specified for an enumerator, the 17392 // initializing value has the same type as the expression. 17393 EltTy = Val->getType(); 17394 } else { 17395 // C99 6.7.2.2p2: 17396 // The expression that defines the value of an enumeration constant 17397 // shall be an integer constant expression that has a value 17398 // representable as an int. 17399 17400 // Complain if the value is not representable in an int. 17401 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17402 Diag(IdLoc, diag::ext_enum_value_not_int) 17403 << EnumVal.toString(10) << Val->getSourceRange() 17404 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17405 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17406 // Force the type of the expression to 'int'. 17407 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17408 } 17409 EltTy = Val->getType(); 17410 } 17411 } 17412 } 17413 } 17414 17415 if (!Val) { 17416 if (Enum->isDependentType()) 17417 EltTy = Context.DependentTy; 17418 else if (!LastEnumConst) { 17419 // C++0x [dcl.enum]p5: 17420 // If the underlying type is not fixed, the type of each enumerator 17421 // is the type of its initializing value: 17422 // - If no initializer is specified for the first enumerator, the 17423 // initializing value has an unspecified integral type. 17424 // 17425 // GCC uses 'int' for its unspecified integral type, as does 17426 // C99 6.7.2.2p3. 17427 if (Enum->isFixed()) { 17428 EltTy = Enum->getIntegerType(); 17429 } 17430 else { 17431 EltTy = Context.IntTy; 17432 } 17433 } else { 17434 // Assign the last value + 1. 17435 EnumVal = LastEnumConst->getInitVal(); 17436 ++EnumVal; 17437 EltTy = LastEnumConst->getType(); 17438 17439 // Check for overflow on increment. 17440 if (EnumVal < LastEnumConst->getInitVal()) { 17441 // C++0x [dcl.enum]p5: 17442 // If the underlying type is not fixed, the type of each enumerator 17443 // is the type of its initializing value: 17444 // 17445 // - Otherwise the type of the initializing value is the same as 17446 // the type of the initializing value of the preceding enumerator 17447 // unless the incremented value is not representable in that type, 17448 // in which case the type is an unspecified integral type 17449 // sufficient to contain the incremented value. If no such type 17450 // exists, the program is ill-formed. 17451 QualType T = getNextLargerIntegralType(Context, EltTy); 17452 if (T.isNull() || Enum->isFixed()) { 17453 // There is no integral type larger enough to represent this 17454 // value. Complain, then allow the value to wrap around. 17455 EnumVal = LastEnumConst->getInitVal(); 17456 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17457 ++EnumVal; 17458 if (Enum->isFixed()) 17459 // When the underlying type is fixed, this is ill-formed. 17460 Diag(IdLoc, diag::err_enumerator_wrapped) 17461 << EnumVal.toString(10) 17462 << EltTy; 17463 else 17464 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17465 << EnumVal.toString(10); 17466 } else { 17467 EltTy = T; 17468 } 17469 17470 // Retrieve the last enumerator's value, extent that type to the 17471 // type that is supposed to be large enough to represent the incremented 17472 // value, then increment. 17473 EnumVal = LastEnumConst->getInitVal(); 17474 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17475 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17476 ++EnumVal; 17477 17478 // If we're not in C++, diagnose the overflow of enumerator values, 17479 // which in C99 means that the enumerator value is not representable in 17480 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17481 // permits enumerator values that are representable in some larger 17482 // integral type. 17483 if (!getLangOpts().CPlusPlus && !T.isNull()) 17484 Diag(IdLoc, diag::warn_enum_value_overflow); 17485 } else if (!getLangOpts().CPlusPlus && 17486 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17487 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17488 Diag(IdLoc, diag::ext_enum_value_not_int) 17489 << EnumVal.toString(10) << 1; 17490 } 17491 } 17492 } 17493 17494 if (!EltTy->isDependentType()) { 17495 // Make the enumerator value match the signedness and size of the 17496 // enumerator's type. 17497 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17498 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17499 } 17500 17501 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17502 Val, EnumVal); 17503 } 17504 17505 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17506 SourceLocation IILoc) { 17507 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17508 !getLangOpts().CPlusPlus) 17509 return SkipBodyInfo(); 17510 17511 // We have an anonymous enum definition. Look up the first enumerator to 17512 // determine if we should merge the definition with an existing one and 17513 // skip the body. 17514 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17515 forRedeclarationInCurContext()); 17516 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17517 if (!PrevECD) 17518 return SkipBodyInfo(); 17519 17520 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17521 NamedDecl *Hidden; 17522 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17523 SkipBodyInfo Skip; 17524 Skip.Previous = Hidden; 17525 return Skip; 17526 } 17527 17528 return SkipBodyInfo(); 17529 } 17530 17531 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17532 SourceLocation IdLoc, IdentifierInfo *Id, 17533 const ParsedAttributesView &Attrs, 17534 SourceLocation EqualLoc, Expr *Val) { 17535 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17536 EnumConstantDecl *LastEnumConst = 17537 cast_or_null<EnumConstantDecl>(lastEnumConst); 17538 17539 // The scope passed in may not be a decl scope. Zip up the scope tree until 17540 // we find one that is. 17541 S = getNonFieldDeclScope(S); 17542 17543 // Verify that there isn't already something declared with this name in this 17544 // scope. 17545 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17546 LookupName(R, S); 17547 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17548 17549 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17550 // Maybe we will complain about the shadowed template parameter. 17551 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17552 // Just pretend that we didn't see the previous declaration. 17553 PrevDecl = nullptr; 17554 } 17555 17556 // C++ [class.mem]p15: 17557 // If T is the name of a class, then each of the following shall have a name 17558 // different from T: 17559 // - every enumerator of every member of class T that is an unscoped 17560 // enumerated type 17561 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17562 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17563 DeclarationNameInfo(Id, IdLoc)); 17564 17565 EnumConstantDecl *New = 17566 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17567 if (!New) 17568 return nullptr; 17569 17570 if (PrevDecl) { 17571 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17572 // Check for other kinds of shadowing not already handled. 17573 CheckShadow(New, PrevDecl, R); 17574 } 17575 17576 // When in C++, we may get a TagDecl with the same name; in this case the 17577 // enum constant will 'hide' the tag. 17578 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17579 "Received TagDecl when not in C++!"); 17580 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17581 if (isa<EnumConstantDecl>(PrevDecl)) 17582 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17583 else 17584 Diag(IdLoc, diag::err_redefinition) << Id; 17585 notePreviousDefinition(PrevDecl, IdLoc); 17586 return nullptr; 17587 } 17588 } 17589 17590 // Process attributes. 17591 ProcessDeclAttributeList(S, New, Attrs); 17592 AddPragmaAttributes(S, New); 17593 17594 // Register this decl in the current scope stack. 17595 New->setAccess(TheEnumDecl->getAccess()); 17596 PushOnScopeChains(New, S); 17597 17598 ActOnDocumentableDecl(New); 17599 17600 return New; 17601 } 17602 17603 // Returns true when the enum initial expression does not trigger the 17604 // duplicate enum warning. A few common cases are exempted as follows: 17605 // Element2 = Element1 17606 // Element2 = Element1 + 1 17607 // Element2 = Element1 - 1 17608 // Where Element2 and Element1 are from the same enum. 17609 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17610 Expr *InitExpr = ECD->getInitExpr(); 17611 if (!InitExpr) 17612 return true; 17613 InitExpr = InitExpr->IgnoreImpCasts(); 17614 17615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17616 if (!BO->isAdditiveOp()) 17617 return true; 17618 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17619 if (!IL) 17620 return true; 17621 if (IL->getValue() != 1) 17622 return true; 17623 17624 InitExpr = BO->getLHS(); 17625 } 17626 17627 // This checks if the elements are from the same enum. 17628 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17629 if (!DRE) 17630 return true; 17631 17632 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17633 if (!EnumConstant) 17634 return true; 17635 17636 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17637 Enum) 17638 return true; 17639 17640 return false; 17641 } 17642 17643 // Emits a warning when an element is implicitly set a value that 17644 // a previous element has already been set to. 17645 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17646 EnumDecl *Enum, QualType EnumType) { 17647 // Avoid anonymous enums 17648 if (!Enum->getIdentifier()) 17649 return; 17650 17651 // Only check for small enums. 17652 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17653 return; 17654 17655 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17656 return; 17657 17658 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17659 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17660 17661 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17662 17663 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17664 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17665 17666 // Use int64_t as a key to avoid needing special handling for map keys. 17667 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17668 llvm::APSInt Val = D->getInitVal(); 17669 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17670 }; 17671 17672 DuplicatesVector DupVector; 17673 ValueToVectorMap EnumMap; 17674 17675 // Populate the EnumMap with all values represented by enum constants without 17676 // an initializer. 17677 for (auto *Element : Elements) { 17678 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17679 17680 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17681 // this constant. Skip this enum since it may be ill-formed. 17682 if (!ECD) { 17683 return; 17684 } 17685 17686 // Constants with initalizers are handled in the next loop. 17687 if (ECD->getInitExpr()) 17688 continue; 17689 17690 // Duplicate values are handled in the next loop. 17691 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17692 } 17693 17694 if (EnumMap.size() == 0) 17695 return; 17696 17697 // Create vectors for any values that has duplicates. 17698 for (auto *Element : Elements) { 17699 // The last loop returned if any constant was null. 17700 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17701 if (!ValidDuplicateEnum(ECD, Enum)) 17702 continue; 17703 17704 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17705 if (Iter == EnumMap.end()) 17706 continue; 17707 17708 DeclOrVector& Entry = Iter->second; 17709 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17710 // Ensure constants are different. 17711 if (D == ECD) 17712 continue; 17713 17714 // Create new vector and push values onto it. 17715 auto Vec = std::make_unique<ECDVector>(); 17716 Vec->push_back(D); 17717 Vec->push_back(ECD); 17718 17719 // Update entry to point to the duplicates vector. 17720 Entry = Vec.get(); 17721 17722 // Store the vector somewhere we can consult later for quick emission of 17723 // diagnostics. 17724 DupVector.emplace_back(std::move(Vec)); 17725 continue; 17726 } 17727 17728 ECDVector *Vec = Entry.get<ECDVector*>(); 17729 // Make sure constants are not added more than once. 17730 if (*Vec->begin() == ECD) 17731 continue; 17732 17733 Vec->push_back(ECD); 17734 } 17735 17736 // Emit diagnostics. 17737 for (const auto &Vec : DupVector) { 17738 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17739 17740 // Emit warning for one enum constant. 17741 auto *FirstECD = Vec->front(); 17742 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17743 << FirstECD << FirstECD->getInitVal().toString(10) 17744 << FirstECD->getSourceRange(); 17745 17746 // Emit one note for each of the remaining enum constants with 17747 // the same value. 17748 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17749 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17750 << ECD << ECD->getInitVal().toString(10) 17751 << ECD->getSourceRange(); 17752 } 17753 } 17754 17755 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17756 bool AllowMask) const { 17757 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17758 assert(ED->isCompleteDefinition() && "expected enum definition"); 17759 17760 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17761 llvm::APInt &FlagBits = R.first->second; 17762 17763 if (R.second) { 17764 for (auto *E : ED->enumerators()) { 17765 const auto &EVal = E->getInitVal(); 17766 // Only single-bit enumerators introduce new flag values. 17767 if (EVal.isPowerOf2()) 17768 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17769 } 17770 } 17771 17772 // A value is in a flag enum if either its bits are a subset of the enum's 17773 // flag bits (the first condition) or we are allowing masks and the same is 17774 // true of its complement (the second condition). When masks are allowed, we 17775 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17776 // 17777 // While it's true that any value could be used as a mask, the assumption is 17778 // that a mask will have all of the insignificant bits set. Anything else is 17779 // likely a logic error. 17780 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17781 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17782 } 17783 17784 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17785 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17786 const ParsedAttributesView &Attrs) { 17787 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17788 QualType EnumType = Context.getTypeDeclType(Enum); 17789 17790 ProcessDeclAttributeList(S, Enum, Attrs); 17791 17792 if (Enum->isDependentType()) { 17793 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17794 EnumConstantDecl *ECD = 17795 cast_or_null<EnumConstantDecl>(Elements[i]); 17796 if (!ECD) continue; 17797 17798 ECD->setType(EnumType); 17799 } 17800 17801 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17802 return; 17803 } 17804 17805 // TODO: If the result value doesn't fit in an int, it must be a long or long 17806 // long value. ISO C does not support this, but GCC does as an extension, 17807 // emit a warning. 17808 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17809 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17810 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17811 17812 // Verify that all the values are okay, compute the size of the values, and 17813 // reverse the list. 17814 unsigned NumNegativeBits = 0; 17815 unsigned NumPositiveBits = 0; 17816 17817 // Keep track of whether all elements have type int. 17818 bool AllElementsInt = true; 17819 17820 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17821 EnumConstantDecl *ECD = 17822 cast_or_null<EnumConstantDecl>(Elements[i]); 17823 if (!ECD) continue; // Already issued a diagnostic. 17824 17825 const llvm::APSInt &InitVal = ECD->getInitVal(); 17826 17827 // Keep track of the size of positive and negative values. 17828 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17829 NumPositiveBits = std::max(NumPositiveBits, 17830 (unsigned)InitVal.getActiveBits()); 17831 else 17832 NumNegativeBits = std::max(NumNegativeBits, 17833 (unsigned)InitVal.getMinSignedBits()); 17834 17835 // Keep track of whether every enum element has type int (very common). 17836 if (AllElementsInt) 17837 AllElementsInt = ECD->getType() == Context.IntTy; 17838 } 17839 17840 // Figure out the type that should be used for this enum. 17841 QualType BestType; 17842 unsigned BestWidth; 17843 17844 // C++0x N3000 [conv.prom]p3: 17845 // An rvalue of an unscoped enumeration type whose underlying 17846 // type is not fixed can be converted to an rvalue of the first 17847 // of the following types that can represent all the values of 17848 // the enumeration: int, unsigned int, long int, unsigned long 17849 // int, long long int, or unsigned long long int. 17850 // C99 6.4.4.3p2: 17851 // An identifier declared as an enumeration constant has type int. 17852 // The C99 rule is modified by a gcc extension 17853 QualType BestPromotionType; 17854 17855 bool Packed = Enum->hasAttr<PackedAttr>(); 17856 // -fshort-enums is the equivalent to specifying the packed attribute on all 17857 // enum definitions. 17858 if (LangOpts.ShortEnums) 17859 Packed = true; 17860 17861 // If the enum already has a type because it is fixed or dictated by the 17862 // target, promote that type instead of analyzing the enumerators. 17863 if (Enum->isComplete()) { 17864 BestType = Enum->getIntegerType(); 17865 if (BestType->isPromotableIntegerType()) 17866 BestPromotionType = Context.getPromotedIntegerType(BestType); 17867 else 17868 BestPromotionType = BestType; 17869 17870 BestWidth = Context.getIntWidth(BestType); 17871 } 17872 else if (NumNegativeBits) { 17873 // If there is a negative value, figure out the smallest integer type (of 17874 // int/long/longlong) that fits. 17875 // If it's packed, check also if it fits a char or a short. 17876 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17877 BestType = Context.SignedCharTy; 17878 BestWidth = CharWidth; 17879 } else if (Packed && NumNegativeBits <= ShortWidth && 17880 NumPositiveBits < ShortWidth) { 17881 BestType = Context.ShortTy; 17882 BestWidth = ShortWidth; 17883 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17884 BestType = Context.IntTy; 17885 BestWidth = IntWidth; 17886 } else { 17887 BestWidth = Context.getTargetInfo().getLongWidth(); 17888 17889 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17890 BestType = Context.LongTy; 17891 } else { 17892 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17893 17894 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17895 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17896 BestType = Context.LongLongTy; 17897 } 17898 } 17899 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17900 } else { 17901 // If there is no negative value, figure out the smallest type that fits 17902 // all of the enumerator values. 17903 // If it's packed, check also if it fits a char or a short. 17904 if (Packed && NumPositiveBits <= CharWidth) { 17905 BestType = Context.UnsignedCharTy; 17906 BestPromotionType = Context.IntTy; 17907 BestWidth = CharWidth; 17908 } else if (Packed && NumPositiveBits <= ShortWidth) { 17909 BestType = Context.UnsignedShortTy; 17910 BestPromotionType = Context.IntTy; 17911 BestWidth = ShortWidth; 17912 } else if (NumPositiveBits <= IntWidth) { 17913 BestType = Context.UnsignedIntTy; 17914 BestWidth = IntWidth; 17915 BestPromotionType 17916 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17917 ? Context.UnsignedIntTy : Context.IntTy; 17918 } else if (NumPositiveBits <= 17919 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17920 BestType = Context.UnsignedLongTy; 17921 BestPromotionType 17922 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17923 ? Context.UnsignedLongTy : Context.LongTy; 17924 } else { 17925 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17926 assert(NumPositiveBits <= BestWidth && 17927 "How could an initializer get larger than ULL?"); 17928 BestType = Context.UnsignedLongLongTy; 17929 BestPromotionType 17930 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17931 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17932 } 17933 } 17934 17935 // Loop over all of the enumerator constants, changing their types to match 17936 // the type of the enum if needed. 17937 for (auto *D : Elements) { 17938 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17939 if (!ECD) continue; // Already issued a diagnostic. 17940 17941 // Standard C says the enumerators have int type, but we allow, as an 17942 // extension, the enumerators to be larger than int size. If each 17943 // enumerator value fits in an int, type it as an int, otherwise type it the 17944 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17945 // that X has type 'int', not 'unsigned'. 17946 17947 // Determine whether the value fits into an int. 17948 llvm::APSInt InitVal = ECD->getInitVal(); 17949 17950 // If it fits into an integer type, force it. Otherwise force it to match 17951 // the enum decl type. 17952 QualType NewTy; 17953 unsigned NewWidth; 17954 bool NewSign; 17955 if (!getLangOpts().CPlusPlus && 17956 !Enum->isFixed() && 17957 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17958 NewTy = Context.IntTy; 17959 NewWidth = IntWidth; 17960 NewSign = true; 17961 } else if (ECD->getType() == BestType) { 17962 // Already the right type! 17963 if (getLangOpts().CPlusPlus) 17964 // C++ [dcl.enum]p4: Following the closing brace of an 17965 // enum-specifier, each enumerator has the type of its 17966 // enumeration. 17967 ECD->setType(EnumType); 17968 continue; 17969 } else { 17970 NewTy = BestType; 17971 NewWidth = BestWidth; 17972 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17973 } 17974 17975 // Adjust the APSInt value. 17976 InitVal = InitVal.extOrTrunc(NewWidth); 17977 InitVal.setIsSigned(NewSign); 17978 ECD->setInitVal(InitVal); 17979 17980 // Adjust the Expr initializer and type. 17981 if (ECD->getInitExpr() && 17982 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17983 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17984 CK_IntegralCast, 17985 ECD->getInitExpr(), 17986 /*base paths*/ nullptr, 17987 VK_RValue)); 17988 if (getLangOpts().CPlusPlus) 17989 // C++ [dcl.enum]p4: Following the closing brace of an 17990 // enum-specifier, each enumerator has the type of its 17991 // enumeration. 17992 ECD->setType(EnumType); 17993 else 17994 ECD->setType(NewTy); 17995 } 17996 17997 Enum->completeDefinition(BestType, BestPromotionType, 17998 NumPositiveBits, NumNegativeBits); 17999 18000 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18001 18002 if (Enum->isClosedFlag()) { 18003 for (Decl *D : Elements) { 18004 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18005 if (!ECD) continue; // Already issued a diagnostic. 18006 18007 llvm::APSInt InitVal = ECD->getInitVal(); 18008 if (InitVal != 0 && !InitVal.isPowerOf2() && 18009 !IsValueInFlagEnum(Enum, InitVal, true)) 18010 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18011 << ECD << Enum; 18012 } 18013 } 18014 18015 // Now that the enum type is defined, ensure it's not been underaligned. 18016 if (Enum->hasAttrs()) 18017 CheckAlignasUnderalignment(Enum); 18018 } 18019 18020 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18021 SourceLocation StartLoc, 18022 SourceLocation EndLoc) { 18023 StringLiteral *AsmString = cast<StringLiteral>(expr); 18024 18025 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18026 AsmString, StartLoc, 18027 EndLoc); 18028 CurContext->addDecl(New); 18029 return New; 18030 } 18031 18032 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18033 IdentifierInfo* AliasName, 18034 SourceLocation PragmaLoc, 18035 SourceLocation NameLoc, 18036 SourceLocation AliasNameLoc) { 18037 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18038 LookupOrdinaryName); 18039 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18040 AttributeCommonInfo::AS_Pragma); 18041 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18042 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18043 18044 // If a declaration that: 18045 // 1) declares a function or a variable 18046 // 2) has external linkage 18047 // already exists, add a label attribute to it. 18048 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18049 if (isDeclExternC(PrevDecl)) 18050 PrevDecl->addAttr(Attr); 18051 else 18052 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18053 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18054 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18055 } else 18056 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18057 } 18058 18059 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18060 SourceLocation PragmaLoc, 18061 SourceLocation NameLoc) { 18062 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18063 18064 if (PrevDecl) { 18065 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18066 } else { 18067 (void)WeakUndeclaredIdentifiers.insert( 18068 std::pair<IdentifierInfo*,WeakInfo> 18069 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18070 } 18071 } 18072 18073 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18074 IdentifierInfo* AliasName, 18075 SourceLocation PragmaLoc, 18076 SourceLocation NameLoc, 18077 SourceLocation AliasNameLoc) { 18078 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18079 LookupOrdinaryName); 18080 WeakInfo W = WeakInfo(Name, NameLoc); 18081 18082 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18083 if (!PrevDecl->hasAttr<AliasAttr>()) 18084 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18085 DeclApplyPragmaWeak(TUScope, ND, W); 18086 } else { 18087 (void)WeakUndeclaredIdentifiers.insert( 18088 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18089 } 18090 } 18091 18092 Decl *Sema::getObjCDeclContext() const { 18093 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18094 } 18095 18096 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18097 bool Final) { 18098 // Templates are emitted when they're instantiated. 18099 if (FD->isDependentContext()) 18100 return FunctionEmissionStatus::TemplateDiscarded; 18101 18102 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18103 if (LangOpts.OpenMPIsDevice) { 18104 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18105 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18106 if (DevTy.hasValue()) { 18107 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18108 OMPES = FunctionEmissionStatus::OMPDiscarded; 18109 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18110 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18111 OMPES = FunctionEmissionStatus::Emitted; 18112 } 18113 } 18114 } else if (LangOpts.OpenMP) { 18115 // In OpenMP 4.5 all the functions are host functions. 18116 if (LangOpts.OpenMP <= 45) { 18117 OMPES = FunctionEmissionStatus::Emitted; 18118 } else { 18119 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18120 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18121 // In OpenMP 5.0 or above, DevTy may be changed later by 18122 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18123 // having no value does not imply host. The emission status will be 18124 // checked again at the end of compilation unit. 18125 if (DevTy.hasValue()) { 18126 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18127 OMPES = FunctionEmissionStatus::OMPDiscarded; 18128 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18129 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18130 OMPES = FunctionEmissionStatus::Emitted; 18131 } else if (Final) 18132 OMPES = FunctionEmissionStatus::Emitted; 18133 } 18134 } 18135 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18136 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18137 return OMPES; 18138 18139 if (LangOpts.CUDA) { 18140 // When compiling for device, host functions are never emitted. Similarly, 18141 // when compiling for host, device and global functions are never emitted. 18142 // (Technically, we do emit a host-side stub for global functions, but this 18143 // doesn't count for our purposes here.) 18144 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18145 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18146 return FunctionEmissionStatus::CUDADiscarded; 18147 if (!LangOpts.CUDAIsDevice && 18148 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18149 return FunctionEmissionStatus::CUDADiscarded; 18150 18151 // Check whether this function is externally visible -- if so, it's 18152 // known-emitted. 18153 // 18154 // We have to check the GVA linkage of the function's *definition* -- if we 18155 // only have a declaration, we don't know whether or not the function will 18156 // be emitted, because (say) the definition could include "inline". 18157 FunctionDecl *Def = FD->getDefinition(); 18158 18159 if (Def && 18160 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18161 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18162 return FunctionEmissionStatus::Emitted; 18163 } 18164 18165 // Otherwise, the function is known-emitted if it's in our set of 18166 // known-emitted functions. 18167 return FunctionEmissionStatus::Unknown; 18168 } 18169 18170 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18171 // Host-side references to a __global__ function refer to the stub, so the 18172 // function itself is never emitted and therefore should not be marked. 18173 // If we have host fn calls kernel fn calls host+device, the HD function 18174 // does not get instantiated on the host. We model this by omitting at the 18175 // call to the kernel from the callgraph. This ensures that, when compiling 18176 // for host, only HD functions actually called from the host get marked as 18177 // known-emitted. 18178 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18179 IdentifyCUDATarget(Callee) == CFT_Global; 18180 } 18181