1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 752 SuggestedType = 753 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 754 } else if (isDependentScopeSpecifier(*SS)) { 755 unsigned DiagID = diag::err_typename_missing; 756 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 757 DiagID = diag::ext_typename_missing; 758 759 Diag(SS->getRange().getBegin(), DiagID) 760 << SS->getScopeRep() << II->getName() 761 << SourceRange(SS->getRange().getBegin(), IILoc) 762 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 763 SuggestedType = ActOnTypenameType(S, SourceLocation(), 764 *SS, *II, IILoc).get(); 765 } else { 766 assert(SS && SS->isInvalid() && 767 "Invalid scope specifier has already been diagnosed"); 768 } 769 } 770 771 /// Determine whether the given result set contains either a type name 772 /// or 773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 774 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 775 NextToken.is(tok::less); 776 777 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 778 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 779 return true; 780 781 if (CheckTemplate && isa<TemplateDecl>(*I)) 782 return true; 783 } 784 785 return false; 786 } 787 788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 789 Scope *S, CXXScopeSpec &SS, 790 IdentifierInfo *&Name, 791 SourceLocation NameLoc) { 792 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 793 SemaRef.LookupParsedName(R, S, &SS); 794 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 795 StringRef FixItTagName; 796 switch (Tag->getTagKind()) { 797 case TTK_Class: 798 FixItTagName = "class "; 799 break; 800 801 case TTK_Enum: 802 FixItTagName = "enum "; 803 break; 804 805 case TTK_Struct: 806 FixItTagName = "struct "; 807 break; 808 809 case TTK_Interface: 810 FixItTagName = "__interface "; 811 break; 812 813 case TTK_Union: 814 FixItTagName = "union "; 815 break; 816 } 817 818 StringRef TagName = FixItTagName.drop_back(); 819 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 820 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 821 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 822 823 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 824 I != IEnd; ++I) 825 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 826 << Name << TagName; 827 828 // Replace lookup results with just the tag decl. 829 Result.clear(Sema::LookupTagName); 830 SemaRef.LookupParsedName(Result, S, &SS); 831 return true; 832 } 833 834 return false; 835 } 836 837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 839 QualType T, SourceLocation NameLoc) { 840 ASTContext &Context = S.Context; 841 842 TypeLocBuilder Builder; 843 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 844 845 T = S.getElaboratedType(ETK_None, SS, T); 846 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 847 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 848 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 849 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 850 } 851 852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 853 IdentifierInfo *&Name, 854 SourceLocation NameLoc, 855 const Token &NextToken, 856 CorrectionCandidateCallback *CCC) { 857 DeclarationNameInfo NameInfo(Name, NameLoc); 858 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 859 860 assert(NextToken.isNot(tok::coloncolon) && 861 "parse nested name specifiers before calling ClassifyName"); 862 if (getLangOpts().CPlusPlus && SS.isSet() && 863 isCurrentClassName(*Name, S, &SS)) { 864 // Per [class.qual]p2, this names the constructors of SS, not the 865 // injected-class-name. We don't have a classification for that. 866 // There's not much point caching this result, since the parser 867 // will reject it later. 868 return NameClassification::Unknown(); 869 } 870 871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 872 LookupParsedName(Result, S, &SS, !CurMethod); 873 874 if (SS.isInvalid()) 875 return NameClassification::Error(); 876 877 // For unqualified lookup in a class template in MSVC mode, look into 878 // dependent base classes where the primary class template is known. 879 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 880 if (ParsedType TypeInBase = 881 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 882 return TypeInBase; 883 } 884 885 // Perform lookup for Objective-C instance variables (including automatically 886 // synthesized instance variables), if we're in an Objective-C method. 887 // FIXME: This lookup really, really needs to be folded in to the normal 888 // unqualified lookup mechanism. 889 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 890 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 891 if (Ivar.isInvalid()) 892 return NameClassification::Error(); 893 if (Ivar.isUsable()) 894 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 895 896 // We defer builtin creation until after ivar lookup inside ObjC methods. 897 if (Result.empty()) 898 LookupBuiltin(Result); 899 } 900 901 bool SecondTry = false; 902 bool IsFilteredTemplateName = false; 903 904 Corrected: 905 switch (Result.getResultKind()) { 906 case LookupResult::NotFound: 907 // If an unqualified-id is followed by a '(', then we have a function 908 // call. 909 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 910 // In C++, this is an ADL-only call. 911 // FIXME: Reference? 912 if (getLangOpts().CPlusPlus) 913 return NameClassification::UndeclaredNonType(); 914 915 // C90 6.3.2.2: 916 // If the expression that precedes the parenthesized argument list in a 917 // function call consists solely of an identifier, and if no 918 // declaration is visible for this identifier, the identifier is 919 // implicitly declared exactly as if, in the innermost block containing 920 // the function call, the declaration 921 // 922 // extern int identifier (); 923 // 924 // appeared. 925 // 926 // We also allow this in C99 as an extension. 927 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 928 return NameClassification::NonType(D); 929 } 930 931 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 932 // In C++20 onwards, this could be an ADL-only call to a function 933 // template, and we're required to assume that this is a template name. 934 // 935 // FIXME: Find a way to still do typo correction in this case. 936 TemplateName Template = 937 Context.getAssumedTemplateName(NameInfo.getName()); 938 return NameClassification::UndeclaredTemplate(Template); 939 } 940 941 // In C, we first see whether there is a tag type by the same name, in 942 // which case it's likely that the user just forgot to write "enum", 943 // "struct", or "union". 944 if (!getLangOpts().CPlusPlus && !SecondTry && 945 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 946 break; 947 } 948 949 // Perform typo correction to determine if there is another name that is 950 // close to this name. 951 if (!SecondTry && CCC) { 952 SecondTry = true; 953 if (TypoCorrection Corrected = 954 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 955 &SS, *CCC, CTK_ErrorRecovery)) { 956 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 957 unsigned QualifiedDiag = diag::err_no_member_suggest; 958 959 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 960 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 961 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 962 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 963 UnqualifiedDiag = diag::err_no_template_suggest; 964 QualifiedDiag = diag::err_no_member_template_suggest; 965 } else if (UnderlyingFirstDecl && 966 (isa<TypeDecl>(UnderlyingFirstDecl) || 967 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 968 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 969 UnqualifiedDiag = diag::err_unknown_typename_suggest; 970 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 971 } 972 973 if (SS.isEmpty()) { 974 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 975 } else {// FIXME: is this even reachable? Test it. 976 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 977 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 978 Name->getName().equals(CorrectedStr); 979 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 980 << Name << computeDeclContext(SS, false) 981 << DroppedSpecifier << SS.getRange()); 982 } 983 984 // Update the name, so that the caller has the new name. 985 Name = Corrected.getCorrectionAsIdentifierInfo(); 986 987 // Typo correction corrected to a keyword. 988 if (Corrected.isKeyword()) 989 return Name; 990 991 // Also update the LookupResult... 992 // FIXME: This should probably go away at some point 993 Result.clear(); 994 Result.setLookupName(Corrected.getCorrection()); 995 if (FirstDecl) 996 Result.addDecl(FirstDecl); 997 998 // If we found an Objective-C instance variable, let 999 // LookupInObjCMethod build the appropriate expression to 1000 // reference the ivar. 1001 // FIXME: This is a gross hack. 1002 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1003 DeclResult R = 1004 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1005 if (R.isInvalid()) 1006 return NameClassification::Error(); 1007 if (R.isUsable()) 1008 return NameClassification::NonType(Ivar); 1009 } 1010 1011 goto Corrected; 1012 } 1013 } 1014 1015 // We failed to correct; just fall through and let the parser deal with it. 1016 Result.suppressDiagnostics(); 1017 return NameClassification::Unknown(); 1018 1019 case LookupResult::NotFoundInCurrentInstantiation: { 1020 // We performed name lookup into the current instantiation, and there were 1021 // dependent bases, so we treat this result the same way as any other 1022 // dependent nested-name-specifier. 1023 1024 // C++ [temp.res]p2: 1025 // A name used in a template declaration or definition and that is 1026 // dependent on a template-parameter is assumed not to name a type 1027 // unless the applicable name lookup finds a type name or the name is 1028 // qualified by the keyword typename. 1029 // 1030 // FIXME: If the next token is '<', we might want to ask the parser to 1031 // perform some heroics to see if we actually have a 1032 // template-argument-list, which would indicate a missing 'template' 1033 // keyword here. 1034 return NameClassification::DependentNonType(); 1035 } 1036 1037 case LookupResult::Found: 1038 case LookupResult::FoundOverloaded: 1039 case LookupResult::FoundUnresolvedValue: 1040 break; 1041 1042 case LookupResult::Ambiguous: 1043 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1044 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1045 /*AllowDependent=*/false)) { 1046 // C++ [temp.local]p3: 1047 // A lookup that finds an injected-class-name (10.2) can result in an 1048 // ambiguity in certain cases (for example, if it is found in more than 1049 // one base class). If all of the injected-class-names that are found 1050 // refer to specializations of the same class template, and if the name 1051 // is followed by a template-argument-list, the reference refers to the 1052 // class template itself and not a specialization thereof, and is not 1053 // ambiguous. 1054 // 1055 // This filtering can make an ambiguous result into an unambiguous one, 1056 // so try again after filtering out template names. 1057 FilterAcceptableTemplateNames(Result); 1058 if (!Result.isAmbiguous()) { 1059 IsFilteredTemplateName = true; 1060 break; 1061 } 1062 } 1063 1064 // Diagnose the ambiguity and return an error. 1065 return NameClassification::Error(); 1066 } 1067 1068 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1069 (IsFilteredTemplateName || 1070 hasAnyAcceptableTemplateNames( 1071 Result, /*AllowFunctionTemplates=*/true, 1072 /*AllowDependent=*/false, 1073 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1074 getLangOpts().CPlusPlus20))) { 1075 // C++ [temp.names]p3: 1076 // After name lookup (3.4) finds that a name is a template-name or that 1077 // an operator-function-id or a literal- operator-id refers to a set of 1078 // overloaded functions any member of which is a function template if 1079 // this is followed by a <, the < is always taken as the delimiter of a 1080 // template-argument-list and never as the less-than operator. 1081 // C++2a [temp.names]p2: 1082 // A name is also considered to refer to a template if it is an 1083 // unqualified-id followed by a < and name lookup finds either one 1084 // or more functions or finds nothing. 1085 if (!IsFilteredTemplateName) 1086 FilterAcceptableTemplateNames(Result); 1087 1088 bool IsFunctionTemplate; 1089 bool IsVarTemplate; 1090 TemplateName Template; 1091 if (Result.end() - Result.begin() > 1) { 1092 IsFunctionTemplate = true; 1093 Template = Context.getOverloadedTemplateName(Result.begin(), 1094 Result.end()); 1095 } else if (!Result.empty()) { 1096 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1097 *Result.begin(), /*AllowFunctionTemplates=*/true, 1098 /*AllowDependent=*/false)); 1099 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1100 IsVarTemplate = isa<VarTemplateDecl>(TD); 1101 1102 if (SS.isNotEmpty()) 1103 Template = 1104 Context.getQualifiedTemplateName(SS.getScopeRep(), 1105 /*TemplateKeyword=*/false, TD); 1106 else 1107 Template = TemplateName(TD); 1108 } else { 1109 // All results were non-template functions. This is a function template 1110 // name. 1111 IsFunctionTemplate = true; 1112 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1113 } 1114 1115 if (IsFunctionTemplate) { 1116 // Function templates always go through overload resolution, at which 1117 // point we'll perform the various checks (e.g., accessibility) we need 1118 // to based on which function we selected. 1119 Result.suppressDiagnostics(); 1120 1121 return NameClassification::FunctionTemplate(Template); 1122 } 1123 1124 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1125 : NameClassification::TypeTemplate(Template); 1126 } 1127 1128 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1129 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1130 DiagnoseUseOfDecl(Type, NameLoc); 1131 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1132 QualType T = Context.getTypeDeclType(Type); 1133 if (SS.isNotEmpty()) 1134 return buildNestedType(*this, SS, T, NameLoc); 1135 return ParsedType::make(T); 1136 } 1137 1138 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1139 if (!Class) { 1140 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1141 if (ObjCCompatibleAliasDecl *Alias = 1142 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1143 Class = Alias->getClassInterface(); 1144 } 1145 1146 if (Class) { 1147 DiagnoseUseOfDecl(Class, NameLoc); 1148 1149 if (NextToken.is(tok::period)) { 1150 // Interface. <something> is parsed as a property reference expression. 1151 // Just return "unknown" as a fall-through for now. 1152 Result.suppressDiagnostics(); 1153 return NameClassification::Unknown(); 1154 } 1155 1156 QualType T = Context.getObjCInterfaceType(Class); 1157 return ParsedType::make(T); 1158 } 1159 1160 if (isa<ConceptDecl>(FirstDecl)) 1161 return NameClassification::Concept( 1162 TemplateName(cast<TemplateDecl>(FirstDecl))); 1163 1164 // We can have a type template here if we're classifying a template argument. 1165 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1166 !isa<VarTemplateDecl>(FirstDecl)) 1167 return NameClassification::TypeTemplate( 1168 TemplateName(cast<TemplateDecl>(FirstDecl))); 1169 1170 // Check for a tag type hidden by a non-type decl in a few cases where it 1171 // seems likely a type is wanted instead of the non-type that was found. 1172 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1173 if ((NextToken.is(tok::identifier) || 1174 (NextIsOp && 1175 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1176 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1177 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1178 DiagnoseUseOfDecl(Type, NameLoc); 1179 QualType T = Context.getTypeDeclType(Type); 1180 if (SS.isNotEmpty()) 1181 return buildNestedType(*this, SS, T, NameLoc); 1182 return ParsedType::make(T); 1183 } 1184 1185 // If we already know which single declaration is referenced, just annotate 1186 // that declaration directly. Defer resolving even non-overloaded class 1187 // member accesses, as we need to defer certain access checks until we know 1188 // the context. 1189 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1190 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1191 return NameClassification::NonType(Result.getRepresentativeDecl()); 1192 1193 // Otherwise, this is an overload set that we will need to resolve later. 1194 Result.suppressDiagnostics(); 1195 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1196 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1197 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1198 Result.begin(), Result.end())); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1239 // For an implicit class member access, transform the result into a member 1240 // access expression if necessary. 1241 auto *ULE = cast<UnresolvedLookupExpr>(E); 1242 if ((*ULE->decls_begin())->isCXXClassMember()) { 1243 CXXScopeSpec SS; 1244 SS.Adopt(ULE->getQualifierLoc()); 1245 1246 // Reconstruct the lookup result. 1247 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1248 LookupOrdinaryName); 1249 Result.setNamingClass(ULE->getNamingClass()); 1250 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1251 Result.addDecl(*I, I.getAccess()); 1252 Result.resolveKind(); 1253 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1254 nullptr, S); 1255 } 1256 1257 // Otherwise, this is already in the form we needed, and no further checks 1258 // are necessary. 1259 return ULE; 1260 } 1261 1262 Sema::TemplateNameKindForDiagnostics 1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1264 auto *TD = Name.getAsTemplateDecl(); 1265 if (!TD) 1266 return TemplateNameKindForDiagnostics::DependentTemplate; 1267 if (isa<ClassTemplateDecl>(TD)) 1268 return TemplateNameKindForDiagnostics::ClassTemplate; 1269 if (isa<FunctionTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::FunctionTemplate; 1271 if (isa<VarTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::VarTemplate; 1273 if (isa<TypeAliasTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::AliasTemplate; 1275 if (isa<TemplateTemplateParmDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1277 if (isa<ConceptDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::Concept; 1279 return TemplateNameKindForDiagnostics::DependentTemplate; 1280 } 1281 1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1283 assert(DC->getLexicalParent() == CurContext && 1284 "The next DeclContext should be lexically contained in the current one."); 1285 CurContext = DC; 1286 S->setEntity(DC); 1287 } 1288 1289 void Sema::PopDeclContext() { 1290 assert(CurContext && "DeclContext imbalance!"); 1291 1292 CurContext = CurContext->getLexicalParent(); 1293 assert(CurContext && "Popped translation unit!"); 1294 } 1295 1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1297 Decl *D) { 1298 // Unlike PushDeclContext, the context to which we return is not necessarily 1299 // the containing DC of TD, because the new context will be some pre-existing 1300 // TagDecl definition instead of a fresh one. 1301 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1302 CurContext = cast<TagDecl>(D)->getDefinition(); 1303 assert(CurContext && "skipping definition of undefined tag"); 1304 // Start lookups from the parent of the current context; we don't want to look 1305 // into the pre-existing complete definition. 1306 S->setEntity(CurContext->getLookupParent()); 1307 return Result; 1308 } 1309 1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1311 CurContext = static_cast<decltype(CurContext)>(Context); 1312 } 1313 1314 /// EnterDeclaratorContext - Used when we must lookup names in the context 1315 /// of a declarator's nested name specifier. 1316 /// 1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1318 // C++0x [basic.lookup.unqual]p13: 1319 // A name used in the definition of a static data member of class 1320 // X (after the qualified-id of the static member) is looked up as 1321 // if the name was used in a member function of X. 1322 // C++0x [basic.lookup.unqual]p14: 1323 // If a variable member of a namespace is defined outside of the 1324 // scope of its namespace then any name used in the definition of 1325 // the variable member (after the declarator-id) is looked up as 1326 // if the definition of the variable member occurred in its 1327 // namespace. 1328 // Both of these imply that we should push a scope whose context 1329 // is the semantic context of the declaration. We can't use 1330 // PushDeclContext here because that context is not necessarily 1331 // lexically contained in the current context. Fortunately, 1332 // the containing scope should have the appropriate information. 1333 1334 assert(!S->getEntity() && "scope already has entity"); 1335 1336 #ifndef NDEBUG 1337 Scope *Ancestor = S->getParent(); 1338 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1339 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1340 #endif 1341 1342 CurContext = DC; 1343 S->setEntity(DC); 1344 1345 if (S->getParent()->isTemplateParamScope()) { 1346 // Also set the corresponding entities for all immediately-enclosing 1347 // template parameter scopes. 1348 EnterTemplatedContext(S->getParent(), DC); 1349 } 1350 } 1351 1352 void Sema::ExitDeclaratorContext(Scope *S) { 1353 assert(S->getEntity() == CurContext && "Context imbalance!"); 1354 1355 // Switch back to the lexical context. The safety of this is 1356 // enforced by an assert in EnterDeclaratorContext. 1357 Scope *Ancestor = S->getParent(); 1358 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1359 CurContext = Ancestor->getEntity(); 1360 1361 // We don't need to do anything with the scope, which is going to 1362 // disappear. 1363 } 1364 1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1366 assert(S->isTemplateParamScope() && 1367 "expected to be initializing a template parameter scope"); 1368 1369 // C++20 [temp.local]p7: 1370 // In the definition of a member of a class template that appears outside 1371 // of the class template definition, the name of a member of the class 1372 // template hides the name of a template-parameter of any enclosing class 1373 // templates (but not a template-parameter of the member if the member is a 1374 // class or function template). 1375 // C++20 [temp.local]p9: 1376 // In the definition of a class template or in the definition of a member 1377 // of such a template that appears outside of the template definition, for 1378 // each non-dependent base class (13.8.2.1), if the name of the base class 1379 // or the name of a member of the base class is the same as the name of a 1380 // template-parameter, the base class name or member name hides the 1381 // template-parameter name (6.4.10). 1382 // 1383 // This means that a template parameter scope should be searched immediately 1384 // after searching the DeclContext for which it is a template parameter 1385 // scope. For example, for 1386 // template<typename T> template<typename U> template<typename V> 1387 // void N::A<T>::B<U>::f(...) 1388 // we search V then B<U> (and base classes) then U then A<T> (and base 1389 // classes) then T then N then ::. 1390 unsigned ScopeDepth = getTemplateDepth(S); 1391 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1392 DeclContext *SearchDCAfterScope = DC; 1393 for (; DC; DC = DC->getLookupParent()) { 1394 if (const TemplateParameterList *TPL = 1395 cast<Decl>(DC)->getDescribedTemplateParams()) { 1396 unsigned DCDepth = TPL->getDepth() + 1; 1397 if (DCDepth > ScopeDepth) 1398 continue; 1399 if (ScopeDepth == DCDepth) 1400 SearchDCAfterScope = DC = DC->getLookupParent(); 1401 break; 1402 } 1403 } 1404 S->setLookupEntity(SearchDCAfterScope); 1405 } 1406 } 1407 1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1409 // We assume that the caller has already called 1410 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1411 FunctionDecl *FD = D->getAsFunction(); 1412 if (!FD) 1413 return; 1414 1415 // Same implementation as PushDeclContext, but enters the context 1416 // from the lexical parent, rather than the top-level class. 1417 assert(CurContext == FD->getLexicalParent() && 1418 "The next DeclContext should be lexically contained in the current one."); 1419 CurContext = FD; 1420 S->setEntity(CurContext); 1421 1422 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1423 ParmVarDecl *Param = FD->getParamDecl(P); 1424 // If the parameter has an identifier, then add it to the scope 1425 if (Param->getIdentifier()) { 1426 S->AddDecl(Param); 1427 IdResolver.AddDecl(Param); 1428 } 1429 } 1430 } 1431 1432 void Sema::ActOnExitFunctionContext() { 1433 // Same implementation as PopDeclContext, but returns to the lexical parent, 1434 // rather than the top-level class. 1435 assert(CurContext && "DeclContext imbalance!"); 1436 CurContext = CurContext->getLexicalParent(); 1437 assert(CurContext && "Popped translation unit!"); 1438 } 1439 1440 /// Determine whether we allow overloading of the function 1441 /// PrevDecl with another declaration. 1442 /// 1443 /// This routine determines whether overloading is possible, not 1444 /// whether some new function is actually an overload. It will return 1445 /// true in C++ (where we can always provide overloads) or, as an 1446 /// extension, in C when the previous function is already an 1447 /// overloaded function declaration or has the "overloadable" 1448 /// attribute. 1449 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1450 ASTContext &Context, 1451 const FunctionDecl *New) { 1452 if (Context.getLangOpts().CPlusPlus) 1453 return true; 1454 1455 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1456 return true; 1457 1458 return Previous.getResultKind() == LookupResult::Found && 1459 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1460 New->hasAttr<OverloadableAttr>()); 1461 } 1462 1463 /// Add this decl to the scope shadowed decl chains. 1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1465 // Move up the scope chain until we find the nearest enclosing 1466 // non-transparent context. The declaration will be introduced into this 1467 // scope. 1468 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1469 S = S->getParent(); 1470 1471 // Add scoped declarations into their context, so that they can be 1472 // found later. Declarations without a context won't be inserted 1473 // into any context. 1474 if (AddToContext) 1475 CurContext->addDecl(D); 1476 1477 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1478 // are function-local declarations. 1479 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1480 return; 1481 1482 // Template instantiations should also not be pushed into scope. 1483 if (isa<FunctionDecl>(D) && 1484 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1485 return; 1486 1487 // If this replaces anything in the current scope, 1488 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1489 IEnd = IdResolver.end(); 1490 for (; I != IEnd; ++I) { 1491 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1492 S->RemoveDecl(*I); 1493 IdResolver.RemoveDecl(*I); 1494 1495 // Should only need to replace one decl. 1496 break; 1497 } 1498 } 1499 1500 S->AddDecl(D); 1501 1502 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1503 // Implicitly-generated labels may end up getting generated in an order that 1504 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1505 // the label at the appropriate place in the identifier chain. 1506 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1507 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1508 if (IDC == CurContext) { 1509 if (!S->isDeclScope(*I)) 1510 continue; 1511 } else if (IDC->Encloses(CurContext)) 1512 break; 1513 } 1514 1515 IdResolver.InsertDeclAfter(I, D); 1516 } else { 1517 IdResolver.AddDecl(D); 1518 } 1519 } 1520 1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1522 bool AllowInlineNamespace) { 1523 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1524 } 1525 1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1527 DeclContext *TargetDC = DC->getPrimaryContext(); 1528 do { 1529 if (DeclContext *ScopeDC = S->getEntity()) 1530 if (ScopeDC->getPrimaryContext() == TargetDC) 1531 return S; 1532 } while ((S = S->getParent())); 1533 1534 return nullptr; 1535 } 1536 1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1538 DeclContext*, 1539 ASTContext&); 1540 1541 /// Filters out lookup results that don't fall within the given scope 1542 /// as determined by isDeclInScope. 1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1544 bool ConsiderLinkage, 1545 bool AllowInlineNamespace) { 1546 LookupResult::Filter F = R.makeFilter(); 1547 while (F.hasNext()) { 1548 NamedDecl *D = F.next(); 1549 1550 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1551 continue; 1552 1553 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1554 continue; 1555 1556 F.erase(); 1557 } 1558 1559 F.done(); 1560 } 1561 1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1563 /// have compatible owning modules. 1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1565 // FIXME: The Modules TS is not clear about how friend declarations are 1566 // to be treated. It's not meaningful to have different owning modules for 1567 // linkage in redeclarations of the same entity, so for now allow the 1568 // redeclaration and change the owning modules to match. 1569 if (New->getFriendObjectKind() && 1570 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1571 New->setLocalOwningModule(Old->getOwningModule()); 1572 makeMergedDefinitionVisible(New); 1573 return false; 1574 } 1575 1576 Module *NewM = New->getOwningModule(); 1577 Module *OldM = Old->getOwningModule(); 1578 1579 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1580 NewM = NewM->Parent; 1581 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1582 OldM = OldM->Parent; 1583 1584 if (NewM == OldM) 1585 return false; 1586 1587 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1588 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1589 if (NewIsModuleInterface || OldIsModuleInterface) { 1590 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1591 // if a declaration of D [...] appears in the purview of a module, all 1592 // other such declarations shall appear in the purview of the same module 1593 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1594 << New 1595 << NewIsModuleInterface 1596 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1597 << OldIsModuleInterface 1598 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1599 Diag(Old->getLocation(), diag::note_previous_declaration); 1600 New->setInvalidDecl(); 1601 return true; 1602 } 1603 1604 return false; 1605 } 1606 1607 static bool isUsingDecl(NamedDecl *D) { 1608 return isa<UsingShadowDecl>(D) || 1609 isa<UnresolvedUsingTypenameDecl>(D) || 1610 isa<UnresolvedUsingValueDecl>(D); 1611 } 1612 1613 /// Removes using shadow declarations from the lookup results. 1614 static void RemoveUsingDecls(LookupResult &R) { 1615 LookupResult::Filter F = R.makeFilter(); 1616 while (F.hasNext()) 1617 if (isUsingDecl(F.next())) 1618 F.erase(); 1619 1620 F.done(); 1621 } 1622 1623 /// Check for this common pattern: 1624 /// @code 1625 /// class S { 1626 /// S(const S&); // DO NOT IMPLEMENT 1627 /// void operator=(const S&); // DO NOT IMPLEMENT 1628 /// }; 1629 /// @endcode 1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1631 // FIXME: Should check for private access too but access is set after we get 1632 // the decl here. 1633 if (D->doesThisDeclarationHaveABody()) 1634 return false; 1635 1636 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1637 return CD->isCopyConstructor(); 1638 return D->isCopyAssignmentOperator(); 1639 } 1640 1641 // We need this to handle 1642 // 1643 // typedef struct { 1644 // void *foo() { return 0; } 1645 // } A; 1646 // 1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1648 // for example. If 'A', foo will have external linkage. If we have '*A', 1649 // foo will have no linkage. Since we can't know until we get to the end 1650 // of the typedef, this function finds out if D might have non-external linkage. 1651 // Callers should verify at the end of the TU if it D has external linkage or 1652 // not. 1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1654 const DeclContext *DC = D->getDeclContext(); 1655 while (!DC->isTranslationUnit()) { 1656 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1657 if (!RD->hasNameForLinkage()) 1658 return true; 1659 } 1660 DC = DC->getParent(); 1661 } 1662 1663 return !D->isExternallyVisible(); 1664 } 1665 1666 // FIXME: This needs to be refactored; some other isInMainFile users want 1667 // these semantics. 1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1669 if (S.TUKind != TU_Complete) 1670 return false; 1671 return S.SourceMgr.isInMainFile(Loc); 1672 } 1673 1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1675 assert(D); 1676 1677 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1678 return false; 1679 1680 // Ignore all entities declared within templates, and out-of-line definitions 1681 // of members of class templates. 1682 if (D->getDeclContext()->isDependentContext() || 1683 D->getLexicalDeclContext()->isDependentContext()) 1684 return false; 1685 1686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1687 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 // A non-out-of-line declaration of a member specialization was implicitly 1690 // instantiated; it's the out-of-line declaration that we're interested in. 1691 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1693 return false; 1694 1695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1696 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1697 return false; 1698 } else { 1699 // 'static inline' functions are defined in headers; don't warn. 1700 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1701 return false; 1702 } 1703 1704 if (FD->doesThisDeclarationHaveABody() && 1705 Context.DeclMustBeEmitted(FD)) 1706 return false; 1707 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1708 // Constants and utility variables are defined in headers with internal 1709 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1710 // like "inline".) 1711 if (!isMainFileLoc(*this, VD->getLocation())) 1712 return false; 1713 1714 if (Context.DeclMustBeEmitted(VD)) 1715 return false; 1716 1717 if (VD->isStaticDataMember() && 1718 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1719 return false; 1720 if (VD->isStaticDataMember() && 1721 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1722 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1723 return false; 1724 1725 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1726 return false; 1727 } else { 1728 return false; 1729 } 1730 1731 // Only warn for unused decls internal to the translation unit. 1732 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1733 // for inline functions defined in the main source file, for instance. 1734 return mightHaveNonExternalLinkage(D); 1735 } 1736 1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1738 if (!D) 1739 return; 1740 1741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1742 const FunctionDecl *First = FD->getFirstDecl(); 1743 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1744 return; // First should already be in the vector. 1745 } 1746 1747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1748 const VarDecl *First = VD->getFirstDecl(); 1749 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1750 return; // First should already be in the vector. 1751 } 1752 1753 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1754 UnusedFileScopedDecls.push_back(D); 1755 } 1756 1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1758 if (D->isInvalidDecl()) 1759 return false; 1760 1761 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1762 // For a decomposition declaration, warn if none of the bindings are 1763 // referenced, instead of if the variable itself is referenced (which 1764 // it is, by the bindings' expressions). 1765 for (auto *BD : DD->bindings()) 1766 if (BD->isReferenced()) 1767 return false; 1768 } else if (!D->getDeclName()) { 1769 return false; 1770 } else if (D->isReferenced() || D->isUsed()) { 1771 return false; 1772 } 1773 1774 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1775 return false; 1776 1777 if (isa<LabelDecl>(D)) 1778 return true; 1779 1780 // Except for labels, we only care about unused decls that are local to 1781 // functions. 1782 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1783 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1784 // For dependent types, the diagnostic is deferred. 1785 WithinFunction = 1786 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1787 if (!WithinFunction) 1788 return false; 1789 1790 if (isa<TypedefNameDecl>(D)) 1791 return true; 1792 1793 // White-list anything that isn't a local variable. 1794 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1795 return false; 1796 1797 // Types of valid local variables should be complete, so this should succeed. 1798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1799 1800 // White-list anything with an __attribute__((unused)) type. 1801 const auto *Ty = VD->getType().getTypePtr(); 1802 1803 // Only look at the outermost level of typedef. 1804 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1805 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1806 return false; 1807 } 1808 1809 // If we failed to complete the type for some reason, or if the type is 1810 // dependent, don't diagnose the variable. 1811 if (Ty->isIncompleteType() || Ty->isDependentType()) 1812 return false; 1813 1814 // Look at the element type to ensure that the warning behaviour is 1815 // consistent for both scalars and arrays. 1816 Ty = Ty->getBaseElementTypeUnsafe(); 1817 1818 if (const TagType *TT = Ty->getAs<TagType>()) { 1819 const TagDecl *Tag = TT->getDecl(); 1820 if (Tag->hasAttr<UnusedAttr>()) 1821 return false; 1822 1823 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1824 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1825 return false; 1826 1827 if (const Expr *Init = VD->getInit()) { 1828 if (const ExprWithCleanups *Cleanups = 1829 dyn_cast<ExprWithCleanups>(Init)) 1830 Init = Cleanups->getSubExpr(); 1831 const CXXConstructExpr *Construct = 1832 dyn_cast<CXXConstructExpr>(Init); 1833 if (Construct && !Construct->isElidable()) { 1834 CXXConstructorDecl *CD = Construct->getConstructor(); 1835 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1836 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1837 return false; 1838 } 1839 1840 // Suppress the warning if we don't know how this is constructed, and 1841 // it could possibly be non-trivial constructor. 1842 if (Init->isTypeDependent()) 1843 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1844 if (!Ctor->isTrivial()) 1845 return false; 1846 } 1847 } 1848 } 1849 1850 // TODO: __attribute__((unused)) templates? 1851 } 1852 1853 return true; 1854 } 1855 1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1857 FixItHint &Hint) { 1858 if (isa<LabelDecl>(D)) { 1859 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1860 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1861 true); 1862 if (AfterColon.isInvalid()) 1863 return; 1864 Hint = FixItHint::CreateRemoval( 1865 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1866 } 1867 } 1868 1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1870 if (D->getTypeForDecl()->isDependentType()) 1871 return; 1872 1873 for (auto *TmpD : D->decls()) { 1874 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1875 DiagnoseUnusedDecl(T); 1876 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1877 DiagnoseUnusedNestedTypedefs(R); 1878 } 1879 } 1880 1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1882 /// unless they are marked attr(unused). 1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1884 if (!ShouldDiagnoseUnusedDecl(D)) 1885 return; 1886 1887 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1888 // typedefs can be referenced later on, so the diagnostics are emitted 1889 // at end-of-translation-unit. 1890 UnusedLocalTypedefNameCandidates.insert(TD); 1891 return; 1892 } 1893 1894 FixItHint Hint; 1895 GenerateFixForUnusedDecl(D, Context, Hint); 1896 1897 unsigned DiagID; 1898 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1899 DiagID = diag::warn_unused_exception_param; 1900 else if (isa<LabelDecl>(D)) 1901 DiagID = diag::warn_unused_label; 1902 else 1903 DiagID = diag::warn_unused_variable; 1904 1905 Diag(D->getLocation(), DiagID) << D << Hint; 1906 } 1907 1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1909 // Verify that we have no forward references left. If so, there was a goto 1910 // or address of a label taken, but no definition of it. Label fwd 1911 // definitions are indicated with a null substmt which is also not a resolved 1912 // MS inline assembly label name. 1913 bool Diagnose = false; 1914 if (L->isMSAsmLabel()) 1915 Diagnose = !L->isResolvedMSAsmLabel(); 1916 else 1917 Diagnose = L->getStmt() == nullptr; 1918 if (Diagnose) 1919 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1920 } 1921 1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1923 S->mergeNRVOIntoParent(); 1924 1925 if (S->decl_empty()) return; 1926 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1927 "Scope shouldn't contain decls!"); 1928 1929 for (auto *TmpD : S->decls()) { 1930 assert(TmpD && "This decl didn't get pushed??"); 1931 1932 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1933 NamedDecl *D = cast<NamedDecl>(TmpD); 1934 1935 // Diagnose unused variables in this scope. 1936 if (!S->hasUnrecoverableErrorOccurred()) { 1937 DiagnoseUnusedDecl(D); 1938 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1939 DiagnoseUnusedNestedTypedefs(RD); 1940 } 1941 1942 if (!D->getDeclName()) continue; 1943 1944 // If this was a forward reference to a label, verify it was defined. 1945 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1946 CheckPoppedLabel(LD, *this); 1947 1948 // Remove this name from our lexical scope, and warn on it if we haven't 1949 // already. 1950 IdResolver.RemoveDecl(D); 1951 auto ShadowI = ShadowingDecls.find(D); 1952 if (ShadowI != ShadowingDecls.end()) { 1953 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1954 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1955 << D << FD << FD->getParent(); 1956 Diag(FD->getLocation(), diag::note_previous_declaration); 1957 } 1958 ShadowingDecls.erase(ShadowI); 1959 } 1960 } 1961 } 1962 1963 /// Look for an Objective-C class in the translation unit. 1964 /// 1965 /// \param Id The name of the Objective-C class we're looking for. If 1966 /// typo-correction fixes this name, the Id will be updated 1967 /// to the fixed name. 1968 /// 1969 /// \param IdLoc The location of the name in the translation unit. 1970 /// 1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1972 /// if there is no class with the given name. 1973 /// 1974 /// \returns The declaration of the named Objective-C class, or NULL if the 1975 /// class could not be found. 1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1977 SourceLocation IdLoc, 1978 bool DoTypoCorrection) { 1979 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1980 // creation from this context. 1981 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1982 1983 if (!IDecl && DoTypoCorrection) { 1984 // Perform typo correction at the given location, but only if we 1985 // find an Objective-C class name. 1986 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1987 if (TypoCorrection C = 1988 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1989 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1990 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1991 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1992 Id = IDecl->getIdentifier(); 1993 } 1994 } 1995 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1996 // This routine must always return a class definition, if any. 1997 if (Def && Def->getDefinition()) 1998 Def = Def->getDefinition(); 1999 return Def; 2000 } 2001 2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2003 /// from S, where a non-field would be declared. This routine copes 2004 /// with the difference between C and C++ scoping rules in structs and 2005 /// unions. For example, the following code is well-formed in C but 2006 /// ill-formed in C++: 2007 /// @code 2008 /// struct S6 { 2009 /// enum { BAR } e; 2010 /// }; 2011 /// 2012 /// void test_S6() { 2013 /// struct S6 a; 2014 /// a.e = BAR; 2015 /// } 2016 /// @endcode 2017 /// For the declaration of BAR, this routine will return a different 2018 /// scope. The scope S will be the scope of the unnamed enumeration 2019 /// within S6. In C++, this routine will return the scope associated 2020 /// with S6, because the enumeration's scope is a transparent 2021 /// context but structures can contain non-field names. In C, this 2022 /// routine will return the translation unit scope, since the 2023 /// enumeration's scope is a transparent context and structures cannot 2024 /// contain non-field names. 2025 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2026 while (((S->getFlags() & Scope::DeclScope) == 0) || 2027 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2028 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2029 S = S->getParent(); 2030 return S; 2031 } 2032 2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2034 ASTContext::GetBuiltinTypeError Error) { 2035 switch (Error) { 2036 case ASTContext::GE_None: 2037 return ""; 2038 case ASTContext::GE_Missing_type: 2039 return BuiltinInfo.getHeaderName(ID); 2040 case ASTContext::GE_Missing_stdio: 2041 return "stdio.h"; 2042 case ASTContext::GE_Missing_setjmp: 2043 return "setjmp.h"; 2044 case ASTContext::GE_Missing_ucontext: 2045 return "ucontext.h"; 2046 } 2047 llvm_unreachable("unhandled error kind"); 2048 } 2049 2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2051 unsigned ID, SourceLocation Loc) { 2052 DeclContext *Parent = Context.getTranslationUnitDecl(); 2053 2054 if (getLangOpts().CPlusPlus) { 2055 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2056 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2057 CLinkageDecl->setImplicit(); 2058 Parent->addDecl(CLinkageDecl); 2059 Parent = CLinkageDecl; 2060 } 2061 2062 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2063 /*TInfo=*/nullptr, SC_Extern, false, 2064 Type->isFunctionProtoType()); 2065 New->setImplicit(); 2066 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2067 2068 // Create Decl objects for each parameter, adding them to the 2069 // FunctionDecl. 2070 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2071 SmallVector<ParmVarDecl *, 16> Params; 2072 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2073 ParmVarDecl *parm = ParmVarDecl::Create( 2074 Context, New, SourceLocation(), SourceLocation(), nullptr, 2075 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2076 parm->setScopeInfo(0, i); 2077 Params.push_back(parm); 2078 } 2079 New->setParams(Params); 2080 } 2081 2082 AddKnownFunctionAttributes(New); 2083 return New; 2084 } 2085 2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2087 /// file scope. lazily create a decl for it. ForRedeclaration is true 2088 /// if we're creating this built-in in anticipation of redeclaring the 2089 /// built-in. 2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2091 Scope *S, bool ForRedeclaration, 2092 SourceLocation Loc) { 2093 LookupNecessaryTypesForBuiltin(S, ID); 2094 2095 ASTContext::GetBuiltinTypeError Error; 2096 QualType R = Context.GetBuiltinType(ID, Error); 2097 if (Error) { 2098 if (!ForRedeclaration) 2099 return nullptr; 2100 2101 // If we have a builtin without an associated type we should not emit a 2102 // warning when we were not able to find a type for it. 2103 if (Error == ASTContext::GE_Missing_type || 2104 Context.BuiltinInfo.allowTypeMismatch(ID)) 2105 return nullptr; 2106 2107 // If we could not find a type for setjmp it is because the jmp_buf type was 2108 // not defined prior to the setjmp declaration. 2109 if (Error == ASTContext::GE_Missing_setjmp) { 2110 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2111 << Context.BuiltinInfo.getName(ID); 2112 return nullptr; 2113 } 2114 2115 // Generally, we emit a warning that the declaration requires the 2116 // appropriate header. 2117 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2118 << getHeaderName(Context.BuiltinInfo, ID, Error) 2119 << Context.BuiltinInfo.getName(ID); 2120 return nullptr; 2121 } 2122 2123 if (!ForRedeclaration && 2124 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2125 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2126 Diag(Loc, diag::ext_implicit_lib_function_decl) 2127 << Context.BuiltinInfo.getName(ID) << R; 2128 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2129 Diag(Loc, diag::note_include_header_or_declare) 2130 << Header << Context.BuiltinInfo.getName(ID); 2131 } 2132 2133 if (R.isNull()) 2134 return nullptr; 2135 2136 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2137 RegisterLocallyScopedExternCDecl(New, S); 2138 2139 // TUScope is the translation-unit scope to insert this function into. 2140 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2141 // relate Scopes to DeclContexts, and probably eliminate CurContext 2142 // entirely, but we're not there yet. 2143 DeclContext *SavedContext = CurContext; 2144 CurContext = New->getDeclContext(); 2145 PushOnScopeChains(New, TUScope); 2146 CurContext = SavedContext; 2147 return New; 2148 } 2149 2150 /// Typedef declarations don't have linkage, but they still denote the same 2151 /// entity if their types are the same. 2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2153 /// isSameEntity. 2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2155 TypedefNameDecl *Decl, 2156 LookupResult &Previous) { 2157 // This is only interesting when modules are enabled. 2158 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2159 return; 2160 2161 // Empty sets are uninteresting. 2162 if (Previous.empty()) 2163 return; 2164 2165 LookupResult::Filter Filter = Previous.makeFilter(); 2166 while (Filter.hasNext()) { 2167 NamedDecl *Old = Filter.next(); 2168 2169 // Non-hidden declarations are never ignored. 2170 if (S.isVisible(Old)) 2171 continue; 2172 2173 // Declarations of the same entity are not ignored, even if they have 2174 // different linkages. 2175 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2176 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2177 Decl->getUnderlyingType())) 2178 continue; 2179 2180 // If both declarations give a tag declaration a typedef name for linkage 2181 // purposes, then they declare the same entity. 2182 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2183 Decl->getAnonDeclWithTypedefName()) 2184 continue; 2185 } 2186 2187 Filter.erase(); 2188 } 2189 2190 Filter.done(); 2191 } 2192 2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2194 QualType OldType; 2195 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2196 OldType = OldTypedef->getUnderlyingType(); 2197 else 2198 OldType = Context.getTypeDeclType(Old); 2199 QualType NewType = New->getUnderlyingType(); 2200 2201 if (NewType->isVariablyModifiedType()) { 2202 // Must not redefine a typedef with a variably-modified type. 2203 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2204 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2205 << Kind << NewType; 2206 if (Old->getLocation().isValid()) 2207 notePreviousDefinition(Old, New->getLocation()); 2208 New->setInvalidDecl(); 2209 return true; 2210 } 2211 2212 if (OldType != NewType && 2213 !OldType->isDependentType() && 2214 !NewType->isDependentType() && 2215 !Context.hasSameType(OldType, NewType)) { 2216 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2217 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2218 << Kind << NewType << OldType; 2219 if (Old->getLocation().isValid()) 2220 notePreviousDefinition(Old, New->getLocation()); 2221 New->setInvalidDecl(); 2222 return true; 2223 } 2224 return false; 2225 } 2226 2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2228 /// same name and scope as a previous declaration 'Old'. Figure out 2229 /// how to resolve this situation, merging decls or emitting 2230 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2231 /// 2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2233 LookupResult &OldDecls) { 2234 // If the new decl is known invalid already, don't bother doing any 2235 // merging checks. 2236 if (New->isInvalidDecl()) return; 2237 2238 // Allow multiple definitions for ObjC built-in typedefs. 2239 // FIXME: Verify the underlying types are equivalent! 2240 if (getLangOpts().ObjC) { 2241 const IdentifierInfo *TypeID = New->getIdentifier(); 2242 switch (TypeID->getLength()) { 2243 default: break; 2244 case 2: 2245 { 2246 if (!TypeID->isStr("id")) 2247 break; 2248 QualType T = New->getUnderlyingType(); 2249 if (!T->isPointerType()) 2250 break; 2251 if (!T->isVoidPointerType()) { 2252 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2253 if (!PT->isStructureType()) 2254 break; 2255 } 2256 Context.setObjCIdRedefinitionType(T); 2257 // Install the built-in type for 'id', ignoring the current definition. 2258 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2259 return; 2260 } 2261 case 5: 2262 if (!TypeID->isStr("Class")) 2263 break; 2264 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2265 // Install the built-in type for 'Class', ignoring the current definition. 2266 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2267 return; 2268 case 3: 2269 if (!TypeID->isStr("SEL")) 2270 break; 2271 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2272 // Install the built-in type for 'SEL', ignoring the current definition. 2273 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2274 return; 2275 } 2276 // Fall through - the typedef name was not a builtin type. 2277 } 2278 2279 // Verify the old decl was also a type. 2280 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2281 if (!Old) { 2282 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2283 << New->getDeclName(); 2284 2285 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2286 if (OldD->getLocation().isValid()) 2287 notePreviousDefinition(OldD, New->getLocation()); 2288 2289 return New->setInvalidDecl(); 2290 } 2291 2292 // If the old declaration is invalid, just give up here. 2293 if (Old->isInvalidDecl()) 2294 return New->setInvalidDecl(); 2295 2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2297 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2298 auto *NewTag = New->getAnonDeclWithTypedefName(); 2299 NamedDecl *Hidden = nullptr; 2300 if (OldTag && NewTag && 2301 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2302 !hasVisibleDefinition(OldTag, &Hidden)) { 2303 // There is a definition of this tag, but it is not visible. Use it 2304 // instead of our tag. 2305 New->setTypeForDecl(OldTD->getTypeForDecl()); 2306 if (OldTD->isModed()) 2307 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2308 OldTD->getUnderlyingType()); 2309 else 2310 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2311 2312 // Make the old tag definition visible. 2313 makeMergedDefinitionVisible(Hidden); 2314 2315 // If this was an unscoped enumeration, yank all of its enumerators 2316 // out of the scope. 2317 if (isa<EnumDecl>(NewTag)) { 2318 Scope *EnumScope = getNonFieldDeclScope(S); 2319 for (auto *D : NewTag->decls()) { 2320 auto *ED = cast<EnumConstantDecl>(D); 2321 assert(EnumScope->isDeclScope(ED)); 2322 EnumScope->RemoveDecl(ED); 2323 IdResolver.RemoveDecl(ED); 2324 ED->getLexicalDeclContext()->removeDecl(ED); 2325 } 2326 } 2327 } 2328 } 2329 2330 // If the typedef types are not identical, reject them in all languages and 2331 // with any extensions enabled. 2332 if (isIncompatibleTypedef(Old, New)) 2333 return; 2334 2335 // The types match. Link up the redeclaration chain and merge attributes if 2336 // the old declaration was a typedef. 2337 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2338 New->setPreviousDecl(Typedef); 2339 mergeDeclAttributes(New, Old); 2340 } 2341 2342 if (getLangOpts().MicrosoftExt) 2343 return; 2344 2345 if (getLangOpts().CPlusPlus) { 2346 // C++ [dcl.typedef]p2: 2347 // In a given non-class scope, a typedef specifier can be used to 2348 // redefine the name of any type declared in that scope to refer 2349 // to the type to which it already refers. 2350 if (!isa<CXXRecordDecl>(CurContext)) 2351 return; 2352 2353 // C++0x [dcl.typedef]p4: 2354 // In a given class scope, a typedef specifier can be used to redefine 2355 // any class-name declared in that scope that is not also a typedef-name 2356 // to refer to the type to which it already refers. 2357 // 2358 // This wording came in via DR424, which was a correction to the 2359 // wording in DR56, which accidentally banned code like: 2360 // 2361 // struct S { 2362 // typedef struct A { } A; 2363 // }; 2364 // 2365 // in the C++03 standard. We implement the C++0x semantics, which 2366 // allow the above but disallow 2367 // 2368 // struct S { 2369 // typedef int I; 2370 // typedef int I; 2371 // }; 2372 // 2373 // since that was the intent of DR56. 2374 if (!isa<TypedefNameDecl>(Old)) 2375 return; 2376 2377 Diag(New->getLocation(), diag::err_redefinition) 2378 << New->getDeclName(); 2379 notePreviousDefinition(Old, New->getLocation()); 2380 return New->setInvalidDecl(); 2381 } 2382 2383 // Modules always permit redefinition of typedefs, as does C11. 2384 if (getLangOpts().Modules || getLangOpts().C11) 2385 return; 2386 2387 // If we have a redefinition of a typedef in C, emit a warning. This warning 2388 // is normally mapped to an error, but can be controlled with 2389 // -Wtypedef-redefinition. If either the original or the redefinition is 2390 // in a system header, don't emit this for compatibility with GCC. 2391 if (getDiagnostics().getSuppressSystemWarnings() && 2392 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2393 (Old->isImplicit() || 2394 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2395 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2396 return; 2397 2398 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2399 << New->getDeclName(); 2400 notePreviousDefinition(Old, New->getLocation()); 2401 } 2402 2403 /// DeclhasAttr - returns true if decl Declaration already has the target 2404 /// attribute. 2405 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2406 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2407 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2408 for (const auto *i : D->attrs()) 2409 if (i->getKind() == A->getKind()) { 2410 if (Ann) { 2411 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2412 return true; 2413 continue; 2414 } 2415 // FIXME: Don't hardcode this check 2416 if (OA && isa<OwnershipAttr>(i)) 2417 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2418 return true; 2419 } 2420 2421 return false; 2422 } 2423 2424 static bool isAttributeTargetADefinition(Decl *D) { 2425 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2426 return VD->isThisDeclarationADefinition(); 2427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2428 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2429 return true; 2430 } 2431 2432 /// Merge alignment attributes from \p Old to \p New, taking into account the 2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2434 /// 2435 /// \return \c true if any attributes were added to \p New. 2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2437 // Look for alignas attributes on Old, and pick out whichever attribute 2438 // specifies the strictest alignment requirement. 2439 AlignedAttr *OldAlignasAttr = nullptr; 2440 AlignedAttr *OldStrictestAlignAttr = nullptr; 2441 unsigned OldAlign = 0; 2442 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2443 // FIXME: We have no way of representing inherited dependent alignments 2444 // in a case like: 2445 // template<int A, int B> struct alignas(A) X; 2446 // template<int A, int B> struct alignas(B) X {}; 2447 // For now, we just ignore any alignas attributes which are not on the 2448 // definition in such a case. 2449 if (I->isAlignmentDependent()) 2450 return false; 2451 2452 if (I->isAlignas()) 2453 OldAlignasAttr = I; 2454 2455 unsigned Align = I->getAlignment(S.Context); 2456 if (Align > OldAlign) { 2457 OldAlign = Align; 2458 OldStrictestAlignAttr = I; 2459 } 2460 } 2461 2462 // Look for alignas attributes on New. 2463 AlignedAttr *NewAlignasAttr = nullptr; 2464 unsigned NewAlign = 0; 2465 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2466 if (I->isAlignmentDependent()) 2467 return false; 2468 2469 if (I->isAlignas()) 2470 NewAlignasAttr = I; 2471 2472 unsigned Align = I->getAlignment(S.Context); 2473 if (Align > NewAlign) 2474 NewAlign = Align; 2475 } 2476 2477 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2478 // Both declarations have 'alignas' attributes. We require them to match. 2479 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2480 // fall short. (If two declarations both have alignas, they must both match 2481 // every definition, and so must match each other if there is a definition.) 2482 2483 // If either declaration only contains 'alignas(0)' specifiers, then it 2484 // specifies the natural alignment for the type. 2485 if (OldAlign == 0 || NewAlign == 0) { 2486 QualType Ty; 2487 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2488 Ty = VD->getType(); 2489 else 2490 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2491 2492 if (OldAlign == 0) 2493 OldAlign = S.Context.getTypeAlign(Ty); 2494 if (NewAlign == 0) 2495 NewAlign = S.Context.getTypeAlign(Ty); 2496 } 2497 2498 if (OldAlign != NewAlign) { 2499 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2500 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2501 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2502 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2503 } 2504 } 2505 2506 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2507 // C++11 [dcl.align]p6: 2508 // if any declaration of an entity has an alignment-specifier, 2509 // every defining declaration of that entity shall specify an 2510 // equivalent alignment. 2511 // C11 6.7.5/7: 2512 // If the definition of an object does not have an alignment 2513 // specifier, any other declaration of that object shall also 2514 // have no alignment specifier. 2515 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2516 << OldAlignasAttr; 2517 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2518 << OldAlignasAttr; 2519 } 2520 2521 bool AnyAdded = false; 2522 2523 // Ensure we have an attribute representing the strictest alignment. 2524 if (OldAlign > NewAlign) { 2525 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 // Ensure we have an alignas attribute if the old declaration had one. 2532 if (OldAlignasAttr && !NewAlignasAttr && 2533 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2534 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2535 Clone->setInherited(true); 2536 New->addAttr(Clone); 2537 AnyAdded = true; 2538 } 2539 2540 return AnyAdded; 2541 } 2542 2543 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2544 const InheritableAttr *Attr, 2545 Sema::AvailabilityMergeKind AMK) { 2546 // This function copies an attribute Attr from a previous declaration to the 2547 // new declaration D if the new declaration doesn't itself have that attribute 2548 // yet or if that attribute allows duplicates. 2549 // If you're adding a new attribute that requires logic different from 2550 // "use explicit attribute on decl if present, else use attribute from 2551 // previous decl", for example if the attribute needs to be consistent 2552 // between redeclarations, you need to call a custom merge function here. 2553 InheritableAttr *NewAttr = nullptr; 2554 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2555 NewAttr = S.mergeAvailabilityAttr( 2556 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2557 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2558 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2559 AA->getPriority()); 2560 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2561 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2562 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2563 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2565 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2566 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2567 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2568 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2569 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2570 FA->getFirstArg()); 2571 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2572 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2573 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2574 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2575 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2576 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2577 IA->getInheritanceModel()); 2578 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2579 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2580 &S.Context.Idents.get(AA->getSpelling())); 2581 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2582 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2583 isa<CUDAGlobalAttr>(Attr))) { 2584 // CUDA target attributes are part of function signature for 2585 // overloading purposes and must not be merged. 2586 return false; 2587 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2588 NewAttr = S.mergeMinSizeAttr(D, *MA); 2589 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2590 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2591 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2592 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2593 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2594 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2595 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2596 NewAttr = S.mergeCommonAttr(D, *CommonA); 2597 else if (isa<AlignedAttr>(Attr)) 2598 // AlignedAttrs are handled separately, because we need to handle all 2599 // such attributes on a declaration at the same time. 2600 NewAttr = nullptr; 2601 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2602 (AMK == Sema::AMK_Override || 2603 AMK == Sema::AMK_ProtocolImplementation)) 2604 NewAttr = nullptr; 2605 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2606 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2607 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2608 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2609 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2612 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2613 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2614 NewAttr = S.mergeImportNameAttr(D, *INA); 2615 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2616 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2617 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2618 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2619 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2620 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2621 2622 if (NewAttr) { 2623 NewAttr->setInherited(true); 2624 D->addAttr(NewAttr); 2625 if (isa<MSInheritanceAttr>(NewAttr)) 2626 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2627 return true; 2628 } 2629 2630 return false; 2631 } 2632 2633 static const NamedDecl *getDefinition(const Decl *D) { 2634 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2635 return TD->getDefinition(); 2636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2637 const VarDecl *Def = VD->getDefinition(); 2638 if (Def) 2639 return Def; 2640 return VD->getActingDefinition(); 2641 } 2642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2643 const FunctionDecl *Def = nullptr; 2644 if (FD->isDefined(Def, true)) 2645 return Def; 2646 } 2647 return nullptr; 2648 } 2649 2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2651 for (const auto *Attribute : D->attrs()) 2652 if (Attribute->getKind() == Kind) 2653 return true; 2654 return false; 2655 } 2656 2657 /// checkNewAttributesAfterDef - If we already have a definition, check that 2658 /// there are no new attributes in this declaration. 2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2660 if (!New->hasAttrs()) 2661 return; 2662 2663 const NamedDecl *Def = getDefinition(Old); 2664 if (!Def || Def == New) 2665 return; 2666 2667 AttrVec &NewAttributes = New->getAttrs(); 2668 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2669 const Attr *NewAttribute = NewAttributes[I]; 2670 2671 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2673 Sema::SkipBodyInfo SkipBody; 2674 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2675 2676 // If we're skipping this definition, drop the "alias" attribute. 2677 if (SkipBody.ShouldSkip) { 2678 NewAttributes.erase(NewAttributes.begin() + I); 2679 --E; 2680 continue; 2681 } 2682 } else { 2683 VarDecl *VD = cast<VarDecl>(New); 2684 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2685 VarDecl::TentativeDefinition 2686 ? diag::err_alias_after_tentative 2687 : diag::err_redefinition; 2688 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2689 if (Diag == diag::err_redefinition) 2690 S.notePreviousDefinition(Def, VD->getLocation()); 2691 else 2692 S.Diag(Def->getLocation(), diag::note_previous_definition); 2693 VD->setInvalidDecl(); 2694 } 2695 ++I; 2696 continue; 2697 } 2698 2699 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2700 // Tentative definitions are only interesting for the alias check above. 2701 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2702 ++I; 2703 continue; 2704 } 2705 } 2706 2707 if (hasAttribute(Def, NewAttribute->getKind())) { 2708 ++I; 2709 continue; // regular attr merging will take care of validating this. 2710 } 2711 2712 if (isa<C11NoReturnAttr>(NewAttribute)) { 2713 // C's _Noreturn is allowed to be added to a function after it is defined. 2714 ++I; 2715 continue; 2716 } else if (isa<UuidAttr>(NewAttribute)) { 2717 // msvc will allow a subsequent definition to add an uuid to a class 2718 ++I; 2719 continue; 2720 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2721 if (AA->isAlignas()) { 2722 // C++11 [dcl.align]p6: 2723 // if any declaration of an entity has an alignment-specifier, 2724 // every defining declaration of that entity shall specify an 2725 // equivalent alignment. 2726 // C11 6.7.5/7: 2727 // If the definition of an object does not have an alignment 2728 // specifier, any other declaration of that object shall also 2729 // have no alignment specifier. 2730 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2731 << AA; 2732 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2733 << AA; 2734 NewAttributes.erase(NewAttributes.begin() + I); 2735 --E; 2736 continue; 2737 } 2738 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2739 // If there is a C definition followed by a redeclaration with this 2740 // attribute then there are two different definitions. In C++, prefer the 2741 // standard diagnostics. 2742 if (!S.getLangOpts().CPlusPlus) { 2743 S.Diag(NewAttribute->getLocation(), 2744 diag::err_loader_uninitialized_redeclaration); 2745 S.Diag(Def->getLocation(), diag::note_previous_definition); 2746 NewAttributes.erase(NewAttributes.begin() + I); 2747 --E; 2748 continue; 2749 } 2750 } else if (isa<SelectAnyAttr>(NewAttribute) && 2751 cast<VarDecl>(New)->isInline() && 2752 !cast<VarDecl>(New)->isInlineSpecified()) { 2753 // Don't warn about applying selectany to implicitly inline variables. 2754 // Older compilers and language modes would require the use of selectany 2755 // to make such variables inline, and it would have no effect if we 2756 // honored it. 2757 ++I; 2758 continue; 2759 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2760 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2761 // declarations after defintions. 2762 ++I; 2763 continue; 2764 } 2765 2766 S.Diag(NewAttribute->getLocation(), 2767 diag::warn_attribute_precede_definition); 2768 S.Diag(Def->getLocation(), diag::note_previous_definition); 2769 NewAttributes.erase(NewAttributes.begin() + I); 2770 --E; 2771 } 2772 } 2773 2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2775 const ConstInitAttr *CIAttr, 2776 bool AttrBeforeInit) { 2777 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2778 2779 // Figure out a good way to write this specifier on the old declaration. 2780 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2781 // enough of the attribute list spelling information to extract that without 2782 // heroics. 2783 std::string SuitableSpelling; 2784 if (S.getLangOpts().CPlusPlus20) 2785 SuitableSpelling = std::string( 2786 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2787 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2788 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2789 InsertLoc, {tok::l_square, tok::l_square, 2790 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2791 S.PP.getIdentifierInfo("require_constant_initialization"), 2792 tok::r_square, tok::r_square})); 2793 if (SuitableSpelling.empty()) 2794 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2795 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2796 S.PP.getIdentifierInfo("require_constant_initialization"), 2797 tok::r_paren, tok::r_paren})); 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2799 SuitableSpelling = "constinit"; 2800 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2801 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2802 if (SuitableSpelling.empty()) 2803 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2804 SuitableSpelling += " "; 2805 2806 if (AttrBeforeInit) { 2807 // extern constinit int a; 2808 // int a = 0; // error (missing 'constinit'), accepted as extension 2809 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2810 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2811 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2812 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2813 } else { 2814 // int a = 0; 2815 // constinit extern int a; // error (missing 'constinit') 2816 S.Diag(CIAttr->getLocation(), 2817 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2818 : diag::warn_require_const_init_added_too_late) 2819 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2820 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2821 << CIAttr->isConstinit() 2822 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2823 } 2824 } 2825 2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2828 AvailabilityMergeKind AMK) { 2829 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2830 UsedAttr *NewAttr = OldAttr->clone(Context); 2831 NewAttr->setInherited(true); 2832 New->addAttr(NewAttr); 2833 } 2834 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2835 RetainAttr *NewAttr = OldAttr->clone(Context); 2836 NewAttr->setInherited(true); 2837 New->addAttr(NewAttr); 2838 } 2839 2840 if (!Old->hasAttrs() && !New->hasAttrs()) 2841 return; 2842 2843 // [dcl.constinit]p1: 2844 // If the [constinit] specifier is applied to any declaration of a 2845 // variable, it shall be applied to the initializing declaration. 2846 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2847 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2848 if (bool(OldConstInit) != bool(NewConstInit)) { 2849 const auto *OldVD = cast<VarDecl>(Old); 2850 auto *NewVD = cast<VarDecl>(New); 2851 2852 // Find the initializing declaration. Note that we might not have linked 2853 // the new declaration into the redeclaration chain yet. 2854 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2855 if (!InitDecl && 2856 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2857 InitDecl = NewVD; 2858 2859 if (InitDecl == NewVD) { 2860 // This is the initializing declaration. If it would inherit 'constinit', 2861 // that's ill-formed. (Note that we do not apply this to the attribute 2862 // form). 2863 if (OldConstInit && OldConstInit->isConstinit()) 2864 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2865 /*AttrBeforeInit=*/true); 2866 } else if (NewConstInit) { 2867 // This is the first time we've been told that this declaration should 2868 // have a constant initializer. If we already saw the initializing 2869 // declaration, this is too late. 2870 if (InitDecl && InitDecl != NewVD) { 2871 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2872 /*AttrBeforeInit=*/false); 2873 NewVD->dropAttr<ConstInitAttr>(); 2874 } 2875 } 2876 } 2877 2878 // Attributes declared post-definition are currently ignored. 2879 checkNewAttributesAfterDef(*this, New, Old); 2880 2881 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2882 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2883 if (!OldA->isEquivalent(NewA)) { 2884 // This redeclaration changes __asm__ label. 2885 Diag(New->getLocation(), diag::err_different_asm_label); 2886 Diag(OldA->getLocation(), diag::note_previous_declaration); 2887 } 2888 } else if (Old->isUsed()) { 2889 // This redeclaration adds an __asm__ label to a declaration that has 2890 // already been ODR-used. 2891 Diag(New->getLocation(), diag::err_late_asm_label_name) 2892 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2893 } 2894 } 2895 2896 // Re-declaration cannot add abi_tag's. 2897 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2898 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2899 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2900 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2901 NewTag) == OldAbiTagAttr->tags_end()) { 2902 Diag(NewAbiTagAttr->getLocation(), 2903 diag::err_new_abi_tag_on_redeclaration) 2904 << NewTag; 2905 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2906 } 2907 } 2908 } else { 2909 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2910 Diag(Old->getLocation(), diag::note_previous_declaration); 2911 } 2912 } 2913 2914 // This redeclaration adds a section attribute. 2915 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2916 if (auto *VD = dyn_cast<VarDecl>(New)) { 2917 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2918 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2919 Diag(Old->getLocation(), diag::note_previous_declaration); 2920 } 2921 } 2922 } 2923 2924 // Redeclaration adds code-seg attribute. 2925 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2926 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2927 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2928 Diag(New->getLocation(), diag::warn_mismatched_section) 2929 << 0 /*codeseg*/; 2930 Diag(Old->getLocation(), diag::note_previous_declaration); 2931 } 2932 2933 if (!Old->hasAttrs()) 2934 return; 2935 2936 bool foundAny = New->hasAttrs(); 2937 2938 // Ensure that any moving of objects within the allocated map is done before 2939 // we process them. 2940 if (!foundAny) New->setAttrs(AttrVec()); 2941 2942 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2943 // Ignore deprecated/unavailable/availability attributes if requested. 2944 AvailabilityMergeKind LocalAMK = AMK_None; 2945 if (isa<DeprecatedAttr>(I) || 2946 isa<UnavailableAttr>(I) || 2947 isa<AvailabilityAttr>(I)) { 2948 switch (AMK) { 2949 case AMK_None: 2950 continue; 2951 2952 case AMK_Redeclaration: 2953 case AMK_Override: 2954 case AMK_ProtocolImplementation: 2955 LocalAMK = AMK; 2956 break; 2957 } 2958 } 2959 2960 // Already handled. 2961 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 2962 continue; 2963 2964 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2965 foundAny = true; 2966 } 2967 2968 if (mergeAlignedAttrs(*this, New, Old)) 2969 foundAny = true; 2970 2971 if (!foundAny) New->dropAttrs(); 2972 } 2973 2974 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2975 /// to the new one. 2976 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2977 const ParmVarDecl *oldDecl, 2978 Sema &S) { 2979 // C++11 [dcl.attr.depend]p2: 2980 // The first declaration of a function shall specify the 2981 // carries_dependency attribute for its declarator-id if any declaration 2982 // of the function specifies the carries_dependency attribute. 2983 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2984 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2985 S.Diag(CDA->getLocation(), 2986 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2987 // Find the first declaration of the parameter. 2988 // FIXME: Should we build redeclaration chains for function parameters? 2989 const FunctionDecl *FirstFD = 2990 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2991 const ParmVarDecl *FirstVD = 2992 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2993 S.Diag(FirstVD->getLocation(), 2994 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2995 } 2996 2997 if (!oldDecl->hasAttrs()) 2998 return; 2999 3000 bool foundAny = newDecl->hasAttrs(); 3001 3002 // Ensure that any moving of objects within the allocated map is 3003 // done before we process them. 3004 if (!foundAny) newDecl->setAttrs(AttrVec()); 3005 3006 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3007 if (!DeclHasAttr(newDecl, I)) { 3008 InheritableAttr *newAttr = 3009 cast<InheritableParamAttr>(I->clone(S.Context)); 3010 newAttr->setInherited(true); 3011 newDecl->addAttr(newAttr); 3012 foundAny = true; 3013 } 3014 } 3015 3016 if (!foundAny) newDecl->dropAttrs(); 3017 } 3018 3019 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3020 const ParmVarDecl *OldParam, 3021 Sema &S) { 3022 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3023 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3024 if (*Oldnullability != *Newnullability) { 3025 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3026 << DiagNullabilityKind( 3027 *Newnullability, 3028 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3029 != 0)) 3030 << DiagNullabilityKind( 3031 *Oldnullability, 3032 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3033 != 0)); 3034 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3035 } 3036 } else { 3037 QualType NewT = NewParam->getType(); 3038 NewT = S.Context.getAttributedType( 3039 AttributedType::getNullabilityAttrKind(*Oldnullability), 3040 NewT, NewT); 3041 NewParam->setType(NewT); 3042 } 3043 } 3044 } 3045 3046 namespace { 3047 3048 /// Used in MergeFunctionDecl to keep track of function parameters in 3049 /// C. 3050 struct GNUCompatibleParamWarning { 3051 ParmVarDecl *OldParm; 3052 ParmVarDecl *NewParm; 3053 QualType PromotedType; 3054 }; 3055 3056 } // end anonymous namespace 3057 3058 // Determine whether the previous declaration was a definition, implicit 3059 // declaration, or a declaration. 3060 template <typename T> 3061 static std::pair<diag::kind, SourceLocation> 3062 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3063 diag::kind PrevDiag; 3064 SourceLocation OldLocation = Old->getLocation(); 3065 if (Old->isThisDeclarationADefinition()) 3066 PrevDiag = diag::note_previous_definition; 3067 else if (Old->isImplicit()) { 3068 PrevDiag = diag::note_previous_implicit_declaration; 3069 if (OldLocation.isInvalid()) 3070 OldLocation = New->getLocation(); 3071 } else 3072 PrevDiag = diag::note_previous_declaration; 3073 return std::make_pair(PrevDiag, OldLocation); 3074 } 3075 3076 /// canRedefineFunction - checks if a function can be redefined. Currently, 3077 /// only extern inline functions can be redefined, and even then only in 3078 /// GNU89 mode. 3079 static bool canRedefineFunction(const FunctionDecl *FD, 3080 const LangOptions& LangOpts) { 3081 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3082 !LangOpts.CPlusPlus && 3083 FD->isInlineSpecified() && 3084 FD->getStorageClass() == SC_Extern); 3085 } 3086 3087 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3088 const AttributedType *AT = T->getAs<AttributedType>(); 3089 while (AT && !AT->isCallingConv()) 3090 AT = AT->getModifiedType()->getAs<AttributedType>(); 3091 return AT; 3092 } 3093 3094 template <typename T> 3095 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3096 const DeclContext *DC = Old->getDeclContext(); 3097 if (DC->isRecord()) 3098 return false; 3099 3100 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3101 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3102 return true; 3103 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3104 return true; 3105 return false; 3106 } 3107 3108 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3109 static bool isExternC(VarTemplateDecl *) { return false; } 3110 3111 /// Check whether a redeclaration of an entity introduced by a 3112 /// using-declaration is valid, given that we know it's not an overload 3113 /// (nor a hidden tag declaration). 3114 template<typename ExpectedDecl> 3115 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3116 ExpectedDecl *New) { 3117 // C++11 [basic.scope.declarative]p4: 3118 // Given a set of declarations in a single declarative region, each of 3119 // which specifies the same unqualified name, 3120 // -- they shall all refer to the same entity, or all refer to functions 3121 // and function templates; or 3122 // -- exactly one declaration shall declare a class name or enumeration 3123 // name that is not a typedef name and the other declarations shall all 3124 // refer to the same variable or enumerator, or all refer to functions 3125 // and function templates; in this case the class name or enumeration 3126 // name is hidden (3.3.10). 3127 3128 // C++11 [namespace.udecl]p14: 3129 // If a function declaration in namespace scope or block scope has the 3130 // same name and the same parameter-type-list as a function introduced 3131 // by a using-declaration, and the declarations do not declare the same 3132 // function, the program is ill-formed. 3133 3134 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3135 if (Old && 3136 !Old->getDeclContext()->getRedeclContext()->Equals( 3137 New->getDeclContext()->getRedeclContext()) && 3138 !(isExternC(Old) && isExternC(New))) 3139 Old = nullptr; 3140 3141 if (!Old) { 3142 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3143 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3144 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3145 return true; 3146 } 3147 return false; 3148 } 3149 3150 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3151 const FunctionDecl *B) { 3152 assert(A->getNumParams() == B->getNumParams()); 3153 3154 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3155 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3156 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3157 if (AttrA == AttrB) 3158 return true; 3159 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3160 AttrA->isDynamic() == AttrB->isDynamic(); 3161 }; 3162 3163 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3164 } 3165 3166 /// If necessary, adjust the semantic declaration context for a qualified 3167 /// declaration to name the correct inline namespace within the qualifier. 3168 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3169 DeclaratorDecl *OldD) { 3170 // The only case where we need to update the DeclContext is when 3171 // redeclaration lookup for a qualified name finds a declaration 3172 // in an inline namespace within the context named by the qualifier: 3173 // 3174 // inline namespace N { int f(); } 3175 // int ::f(); // Sema DC needs adjusting from :: to N::. 3176 // 3177 // For unqualified declarations, the semantic context *can* change 3178 // along the redeclaration chain (for local extern declarations, 3179 // extern "C" declarations, and friend declarations in particular). 3180 if (!NewD->getQualifier()) 3181 return; 3182 3183 // NewD is probably already in the right context. 3184 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3185 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3186 if (NamedDC->Equals(SemaDC)) 3187 return; 3188 3189 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3190 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3191 "unexpected context for redeclaration"); 3192 3193 auto *LexDC = NewD->getLexicalDeclContext(); 3194 auto FixSemaDC = [=](NamedDecl *D) { 3195 if (!D) 3196 return; 3197 D->setDeclContext(SemaDC); 3198 D->setLexicalDeclContext(LexDC); 3199 }; 3200 3201 FixSemaDC(NewD); 3202 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3203 FixSemaDC(FD->getDescribedFunctionTemplate()); 3204 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3205 FixSemaDC(VD->getDescribedVarTemplate()); 3206 } 3207 3208 /// MergeFunctionDecl - We just parsed a function 'New' from 3209 /// declarator D which has the same name and scope as a previous 3210 /// declaration 'Old'. Figure out how to resolve this situation, 3211 /// merging decls or emitting diagnostics as appropriate. 3212 /// 3213 /// In C++, New and Old must be declarations that are not 3214 /// overloaded. Use IsOverload to determine whether New and Old are 3215 /// overloaded, and to select the Old declaration that New should be 3216 /// merged with. 3217 /// 3218 /// Returns true if there was an error, false otherwise. 3219 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3220 Scope *S, bool MergeTypeWithOld) { 3221 // Verify the old decl was also a function. 3222 FunctionDecl *Old = OldD->getAsFunction(); 3223 if (!Old) { 3224 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3225 if (New->getFriendObjectKind()) { 3226 Diag(New->getLocation(), diag::err_using_decl_friend); 3227 Diag(Shadow->getTargetDecl()->getLocation(), 3228 diag::note_using_decl_target); 3229 Diag(Shadow->getUsingDecl()->getLocation(), 3230 diag::note_using_decl) << 0; 3231 return true; 3232 } 3233 3234 // Check whether the two declarations might declare the same function. 3235 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3236 return true; 3237 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3238 } else { 3239 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3240 << New->getDeclName(); 3241 notePreviousDefinition(OldD, New->getLocation()); 3242 return true; 3243 } 3244 } 3245 3246 // If the old declaration was found in an inline namespace and the new 3247 // declaration was qualified, update the DeclContext to match. 3248 adjustDeclContextForDeclaratorDecl(New, Old); 3249 3250 // If the old declaration is invalid, just give up here. 3251 if (Old->isInvalidDecl()) 3252 return true; 3253 3254 // Disallow redeclaration of some builtins. 3255 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3256 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3257 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3258 << Old << Old->getType(); 3259 return true; 3260 } 3261 3262 diag::kind PrevDiag; 3263 SourceLocation OldLocation; 3264 std::tie(PrevDiag, OldLocation) = 3265 getNoteDiagForInvalidRedeclaration(Old, New); 3266 3267 // Don't complain about this if we're in GNU89 mode and the old function 3268 // is an extern inline function. 3269 // Don't complain about specializations. They are not supposed to have 3270 // storage classes. 3271 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3272 New->getStorageClass() == SC_Static && 3273 Old->hasExternalFormalLinkage() && 3274 !New->getTemplateSpecializationInfo() && 3275 !canRedefineFunction(Old, getLangOpts())) { 3276 if (getLangOpts().MicrosoftExt) { 3277 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3278 Diag(OldLocation, PrevDiag); 3279 } else { 3280 Diag(New->getLocation(), diag::err_static_non_static) << New; 3281 Diag(OldLocation, PrevDiag); 3282 return true; 3283 } 3284 } 3285 3286 if (New->hasAttr<InternalLinkageAttr>() && 3287 !Old->hasAttr<InternalLinkageAttr>()) { 3288 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3289 << New->getDeclName(); 3290 notePreviousDefinition(Old, New->getLocation()); 3291 New->dropAttr<InternalLinkageAttr>(); 3292 } 3293 3294 if (CheckRedeclarationModuleOwnership(New, Old)) 3295 return true; 3296 3297 if (!getLangOpts().CPlusPlus) { 3298 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3299 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3300 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3301 << New << OldOvl; 3302 3303 // Try our best to find a decl that actually has the overloadable 3304 // attribute for the note. In most cases (e.g. programs with only one 3305 // broken declaration/definition), this won't matter. 3306 // 3307 // FIXME: We could do this if we juggled some extra state in 3308 // OverloadableAttr, rather than just removing it. 3309 const Decl *DiagOld = Old; 3310 if (OldOvl) { 3311 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3312 const auto *A = D->getAttr<OverloadableAttr>(); 3313 return A && !A->isImplicit(); 3314 }); 3315 // If we've implicitly added *all* of the overloadable attrs to this 3316 // chain, emitting a "previous redecl" note is pointless. 3317 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3318 } 3319 3320 if (DiagOld) 3321 Diag(DiagOld->getLocation(), 3322 diag::note_attribute_overloadable_prev_overload) 3323 << OldOvl; 3324 3325 if (OldOvl) 3326 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3327 else 3328 New->dropAttr<OverloadableAttr>(); 3329 } 3330 } 3331 3332 // If a function is first declared with a calling convention, but is later 3333 // declared or defined without one, all following decls assume the calling 3334 // convention of the first. 3335 // 3336 // It's OK if a function is first declared without a calling convention, 3337 // but is later declared or defined with the default calling convention. 3338 // 3339 // To test if either decl has an explicit calling convention, we look for 3340 // AttributedType sugar nodes on the type as written. If they are missing or 3341 // were canonicalized away, we assume the calling convention was implicit. 3342 // 3343 // Note also that we DO NOT return at this point, because we still have 3344 // other tests to run. 3345 QualType OldQType = Context.getCanonicalType(Old->getType()); 3346 QualType NewQType = Context.getCanonicalType(New->getType()); 3347 const FunctionType *OldType = cast<FunctionType>(OldQType); 3348 const FunctionType *NewType = cast<FunctionType>(NewQType); 3349 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3350 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3351 bool RequiresAdjustment = false; 3352 3353 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3354 FunctionDecl *First = Old->getFirstDecl(); 3355 const FunctionType *FT = 3356 First->getType().getCanonicalType()->castAs<FunctionType>(); 3357 FunctionType::ExtInfo FI = FT->getExtInfo(); 3358 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3359 if (!NewCCExplicit) { 3360 // Inherit the CC from the previous declaration if it was specified 3361 // there but not here. 3362 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3363 RequiresAdjustment = true; 3364 } else if (Old->getBuiltinID()) { 3365 // Builtin attribute isn't propagated to the new one yet at this point, 3366 // so we check if the old one is a builtin. 3367 3368 // Calling Conventions on a Builtin aren't really useful and setting a 3369 // default calling convention and cdecl'ing some builtin redeclarations is 3370 // common, so warn and ignore the calling convention on the redeclaration. 3371 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3372 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3373 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3374 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3375 RequiresAdjustment = true; 3376 } else { 3377 // Calling conventions aren't compatible, so complain. 3378 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3379 Diag(New->getLocation(), diag::err_cconv_change) 3380 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3381 << !FirstCCExplicit 3382 << (!FirstCCExplicit ? "" : 3383 FunctionType::getNameForCallConv(FI.getCC())); 3384 3385 // Put the note on the first decl, since it is the one that matters. 3386 Diag(First->getLocation(), diag::note_previous_declaration); 3387 return true; 3388 } 3389 } 3390 3391 // FIXME: diagnose the other way around? 3392 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3393 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3394 RequiresAdjustment = true; 3395 } 3396 3397 // Merge regparm attribute. 3398 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3399 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3400 if (NewTypeInfo.getHasRegParm()) { 3401 Diag(New->getLocation(), diag::err_regparm_mismatch) 3402 << NewType->getRegParmType() 3403 << OldType->getRegParmType(); 3404 Diag(OldLocation, diag::note_previous_declaration); 3405 return true; 3406 } 3407 3408 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3409 RequiresAdjustment = true; 3410 } 3411 3412 // Merge ns_returns_retained attribute. 3413 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3414 if (NewTypeInfo.getProducesResult()) { 3415 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3416 << "'ns_returns_retained'"; 3417 Diag(OldLocation, diag::note_previous_declaration); 3418 return true; 3419 } 3420 3421 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3422 RequiresAdjustment = true; 3423 } 3424 3425 if (OldTypeInfo.getNoCallerSavedRegs() != 3426 NewTypeInfo.getNoCallerSavedRegs()) { 3427 if (NewTypeInfo.getNoCallerSavedRegs()) { 3428 AnyX86NoCallerSavedRegistersAttr *Attr = 3429 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3430 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3431 Diag(OldLocation, diag::note_previous_declaration); 3432 return true; 3433 } 3434 3435 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3436 RequiresAdjustment = true; 3437 } 3438 3439 if (RequiresAdjustment) { 3440 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3441 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3442 New->setType(QualType(AdjustedType, 0)); 3443 NewQType = Context.getCanonicalType(New->getType()); 3444 } 3445 3446 // If this redeclaration makes the function inline, we may need to add it to 3447 // UndefinedButUsed. 3448 if (!Old->isInlined() && New->isInlined() && 3449 !New->hasAttr<GNUInlineAttr>() && 3450 !getLangOpts().GNUInline && 3451 Old->isUsed(false) && 3452 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3453 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3454 SourceLocation())); 3455 3456 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3457 // about it. 3458 if (New->hasAttr<GNUInlineAttr>() && 3459 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3460 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3461 } 3462 3463 // If pass_object_size params don't match up perfectly, this isn't a valid 3464 // redeclaration. 3465 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3466 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3467 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3468 << New->getDeclName(); 3469 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3470 return true; 3471 } 3472 3473 if (getLangOpts().CPlusPlus) { 3474 // C++1z [over.load]p2 3475 // Certain function declarations cannot be overloaded: 3476 // -- Function declarations that differ only in the return type, 3477 // the exception specification, or both cannot be overloaded. 3478 3479 // Check the exception specifications match. This may recompute the type of 3480 // both Old and New if it resolved exception specifications, so grab the 3481 // types again after this. Because this updates the type, we do this before 3482 // any of the other checks below, which may update the "de facto" NewQType 3483 // but do not necessarily update the type of New. 3484 if (CheckEquivalentExceptionSpec(Old, New)) 3485 return true; 3486 OldQType = Context.getCanonicalType(Old->getType()); 3487 NewQType = Context.getCanonicalType(New->getType()); 3488 3489 // Go back to the type source info to compare the declared return types, 3490 // per C++1y [dcl.type.auto]p13: 3491 // Redeclarations or specializations of a function or function template 3492 // with a declared return type that uses a placeholder type shall also 3493 // use that placeholder, not a deduced type. 3494 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3495 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3496 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3497 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3498 OldDeclaredReturnType)) { 3499 QualType ResQT; 3500 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3501 OldDeclaredReturnType->isObjCObjectPointerType()) 3502 // FIXME: This does the wrong thing for a deduced return type. 3503 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3504 if (ResQT.isNull()) { 3505 if (New->isCXXClassMember() && New->isOutOfLine()) 3506 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3507 << New << New->getReturnTypeSourceRange(); 3508 else 3509 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3510 << New->getReturnTypeSourceRange(); 3511 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3512 << Old->getReturnTypeSourceRange(); 3513 return true; 3514 } 3515 else 3516 NewQType = ResQT; 3517 } 3518 3519 QualType OldReturnType = OldType->getReturnType(); 3520 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3521 if (OldReturnType != NewReturnType) { 3522 // If this function has a deduced return type and has already been 3523 // defined, copy the deduced value from the old declaration. 3524 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3525 if (OldAT && OldAT->isDeduced()) { 3526 New->setType( 3527 SubstAutoType(New->getType(), 3528 OldAT->isDependentType() ? Context.DependentTy 3529 : OldAT->getDeducedType())); 3530 NewQType = Context.getCanonicalType( 3531 SubstAutoType(NewQType, 3532 OldAT->isDependentType() ? Context.DependentTy 3533 : OldAT->getDeducedType())); 3534 } 3535 } 3536 3537 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3538 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3539 if (OldMethod && NewMethod) { 3540 // Preserve triviality. 3541 NewMethod->setTrivial(OldMethod->isTrivial()); 3542 3543 // MSVC allows explicit template specialization at class scope: 3544 // 2 CXXMethodDecls referring to the same function will be injected. 3545 // We don't want a redeclaration error. 3546 bool IsClassScopeExplicitSpecialization = 3547 OldMethod->isFunctionTemplateSpecialization() && 3548 NewMethod->isFunctionTemplateSpecialization(); 3549 bool isFriend = NewMethod->getFriendObjectKind(); 3550 3551 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3552 !IsClassScopeExplicitSpecialization) { 3553 // -- Member function declarations with the same name and the 3554 // same parameter types cannot be overloaded if any of them 3555 // is a static member function declaration. 3556 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3557 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3558 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3559 return true; 3560 } 3561 3562 // C++ [class.mem]p1: 3563 // [...] A member shall not be declared twice in the 3564 // member-specification, except that a nested class or member 3565 // class template can be declared and then later defined. 3566 if (!inTemplateInstantiation()) { 3567 unsigned NewDiag; 3568 if (isa<CXXConstructorDecl>(OldMethod)) 3569 NewDiag = diag::err_constructor_redeclared; 3570 else if (isa<CXXDestructorDecl>(NewMethod)) 3571 NewDiag = diag::err_destructor_redeclared; 3572 else if (isa<CXXConversionDecl>(NewMethod)) 3573 NewDiag = diag::err_conv_function_redeclared; 3574 else 3575 NewDiag = diag::err_member_redeclared; 3576 3577 Diag(New->getLocation(), NewDiag); 3578 } else { 3579 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3580 << New << New->getType(); 3581 } 3582 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3583 return true; 3584 3585 // Complain if this is an explicit declaration of a special 3586 // member that was initially declared implicitly. 3587 // 3588 // As an exception, it's okay to befriend such methods in order 3589 // to permit the implicit constructor/destructor/operator calls. 3590 } else if (OldMethod->isImplicit()) { 3591 if (isFriend) { 3592 NewMethod->setImplicit(); 3593 } else { 3594 Diag(NewMethod->getLocation(), 3595 diag::err_definition_of_implicitly_declared_member) 3596 << New << getSpecialMember(OldMethod); 3597 return true; 3598 } 3599 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3600 Diag(NewMethod->getLocation(), 3601 diag::err_definition_of_explicitly_defaulted_member) 3602 << getSpecialMember(OldMethod); 3603 return true; 3604 } 3605 } 3606 3607 // C++11 [dcl.attr.noreturn]p1: 3608 // The first declaration of a function shall specify the noreturn 3609 // attribute if any declaration of that function specifies the noreturn 3610 // attribute. 3611 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3612 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3613 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3614 Diag(Old->getFirstDecl()->getLocation(), 3615 diag::note_noreturn_missing_first_decl); 3616 } 3617 3618 // C++11 [dcl.attr.depend]p2: 3619 // The first declaration of a function shall specify the 3620 // carries_dependency attribute for its declarator-id if any declaration 3621 // of the function specifies the carries_dependency attribute. 3622 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3623 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3624 Diag(CDA->getLocation(), 3625 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3626 Diag(Old->getFirstDecl()->getLocation(), 3627 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3628 } 3629 3630 // (C++98 8.3.5p3): 3631 // All declarations for a function shall agree exactly in both the 3632 // return type and the parameter-type-list. 3633 // We also want to respect all the extended bits except noreturn. 3634 3635 // noreturn should now match unless the old type info didn't have it. 3636 QualType OldQTypeForComparison = OldQType; 3637 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3638 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3639 const FunctionType *OldTypeForComparison 3640 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3641 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3642 assert(OldQTypeForComparison.isCanonical()); 3643 } 3644 3645 if (haveIncompatibleLanguageLinkages(Old, New)) { 3646 // As a special case, retain the language linkage from previous 3647 // declarations of a friend function as an extension. 3648 // 3649 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3650 // and is useful because there's otherwise no way to specify language 3651 // linkage within class scope. 3652 // 3653 // Check cautiously as the friend object kind isn't yet complete. 3654 if (New->getFriendObjectKind() != Decl::FOK_None) { 3655 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3656 Diag(OldLocation, PrevDiag); 3657 } else { 3658 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3659 Diag(OldLocation, PrevDiag); 3660 return true; 3661 } 3662 } 3663 3664 // If the function types are compatible, merge the declarations. Ignore the 3665 // exception specifier because it was already checked above in 3666 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3667 // about incompatible types under -fms-compatibility. 3668 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3669 NewQType)) 3670 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3671 3672 // If the types are imprecise (due to dependent constructs in friends or 3673 // local extern declarations), it's OK if they differ. We'll check again 3674 // during instantiation. 3675 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3676 return false; 3677 3678 // Fall through for conflicting redeclarations and redefinitions. 3679 } 3680 3681 // C: Function types need to be compatible, not identical. This handles 3682 // duplicate function decls like "void f(int); void f(enum X);" properly. 3683 if (!getLangOpts().CPlusPlus && 3684 Context.typesAreCompatible(OldQType, NewQType)) { 3685 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3686 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3687 const FunctionProtoType *OldProto = nullptr; 3688 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3689 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3690 // The old declaration provided a function prototype, but the 3691 // new declaration does not. Merge in the prototype. 3692 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3693 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3694 NewQType = 3695 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3696 OldProto->getExtProtoInfo()); 3697 New->setType(NewQType); 3698 New->setHasInheritedPrototype(); 3699 3700 // Synthesize parameters with the same types. 3701 SmallVector<ParmVarDecl*, 16> Params; 3702 for (const auto &ParamType : OldProto->param_types()) { 3703 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3704 SourceLocation(), nullptr, 3705 ParamType, /*TInfo=*/nullptr, 3706 SC_None, nullptr); 3707 Param->setScopeInfo(0, Params.size()); 3708 Param->setImplicit(); 3709 Params.push_back(Param); 3710 } 3711 3712 New->setParams(Params); 3713 } 3714 3715 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3716 } 3717 3718 // Check if the function types are compatible when pointer size address 3719 // spaces are ignored. 3720 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3721 return false; 3722 3723 // GNU C permits a K&R definition to follow a prototype declaration 3724 // if the declared types of the parameters in the K&R definition 3725 // match the types in the prototype declaration, even when the 3726 // promoted types of the parameters from the K&R definition differ 3727 // from the types in the prototype. GCC then keeps the types from 3728 // the prototype. 3729 // 3730 // If a variadic prototype is followed by a non-variadic K&R definition, 3731 // the K&R definition becomes variadic. This is sort of an edge case, but 3732 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3733 // C99 6.9.1p8. 3734 if (!getLangOpts().CPlusPlus && 3735 Old->hasPrototype() && !New->hasPrototype() && 3736 New->getType()->getAs<FunctionProtoType>() && 3737 Old->getNumParams() == New->getNumParams()) { 3738 SmallVector<QualType, 16> ArgTypes; 3739 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3740 const FunctionProtoType *OldProto 3741 = Old->getType()->getAs<FunctionProtoType>(); 3742 const FunctionProtoType *NewProto 3743 = New->getType()->getAs<FunctionProtoType>(); 3744 3745 // Determine whether this is the GNU C extension. 3746 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3747 NewProto->getReturnType()); 3748 bool LooseCompatible = !MergedReturn.isNull(); 3749 for (unsigned Idx = 0, End = Old->getNumParams(); 3750 LooseCompatible && Idx != End; ++Idx) { 3751 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3752 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3753 if (Context.typesAreCompatible(OldParm->getType(), 3754 NewProto->getParamType(Idx))) { 3755 ArgTypes.push_back(NewParm->getType()); 3756 } else if (Context.typesAreCompatible(OldParm->getType(), 3757 NewParm->getType(), 3758 /*CompareUnqualified=*/true)) { 3759 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3760 NewProto->getParamType(Idx) }; 3761 Warnings.push_back(Warn); 3762 ArgTypes.push_back(NewParm->getType()); 3763 } else 3764 LooseCompatible = false; 3765 } 3766 3767 if (LooseCompatible) { 3768 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3769 Diag(Warnings[Warn].NewParm->getLocation(), 3770 diag::ext_param_promoted_not_compatible_with_prototype) 3771 << Warnings[Warn].PromotedType 3772 << Warnings[Warn].OldParm->getType(); 3773 if (Warnings[Warn].OldParm->getLocation().isValid()) 3774 Diag(Warnings[Warn].OldParm->getLocation(), 3775 diag::note_previous_declaration); 3776 } 3777 3778 if (MergeTypeWithOld) 3779 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3780 OldProto->getExtProtoInfo())); 3781 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3782 } 3783 3784 // Fall through to diagnose conflicting types. 3785 } 3786 3787 // A function that has already been declared has been redeclared or 3788 // defined with a different type; show an appropriate diagnostic. 3789 3790 // If the previous declaration was an implicitly-generated builtin 3791 // declaration, then at the very least we should use a specialized note. 3792 unsigned BuiltinID; 3793 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3794 // If it's actually a library-defined builtin function like 'malloc' 3795 // or 'printf', just warn about the incompatible redeclaration. 3796 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3797 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3798 Diag(OldLocation, diag::note_previous_builtin_declaration) 3799 << Old << Old->getType(); 3800 return false; 3801 } 3802 3803 PrevDiag = diag::note_previous_builtin_declaration; 3804 } 3805 3806 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3807 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3808 return true; 3809 } 3810 3811 /// Completes the merge of two function declarations that are 3812 /// known to be compatible. 3813 /// 3814 /// This routine handles the merging of attributes and other 3815 /// properties of function declarations from the old declaration to 3816 /// the new declaration, once we know that New is in fact a 3817 /// redeclaration of Old. 3818 /// 3819 /// \returns false 3820 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3821 Scope *S, bool MergeTypeWithOld) { 3822 // Merge the attributes 3823 mergeDeclAttributes(New, Old); 3824 3825 // Merge "pure" flag. 3826 if (Old->isPure()) 3827 New->setPure(); 3828 3829 // Merge "used" flag. 3830 if (Old->getMostRecentDecl()->isUsed(false)) 3831 New->setIsUsed(); 3832 3833 // Merge attributes from the parameters. These can mismatch with K&R 3834 // declarations. 3835 if (New->getNumParams() == Old->getNumParams()) 3836 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3837 ParmVarDecl *NewParam = New->getParamDecl(i); 3838 ParmVarDecl *OldParam = Old->getParamDecl(i); 3839 mergeParamDeclAttributes(NewParam, OldParam, *this); 3840 mergeParamDeclTypes(NewParam, OldParam, *this); 3841 } 3842 3843 if (getLangOpts().CPlusPlus) 3844 return MergeCXXFunctionDecl(New, Old, S); 3845 3846 // Merge the function types so the we get the composite types for the return 3847 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3848 // was visible. 3849 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3850 if (!Merged.isNull() && MergeTypeWithOld) 3851 New->setType(Merged); 3852 3853 return false; 3854 } 3855 3856 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3857 ObjCMethodDecl *oldMethod) { 3858 // Merge the attributes, including deprecated/unavailable 3859 AvailabilityMergeKind MergeKind = 3860 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3861 ? AMK_ProtocolImplementation 3862 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3863 : AMK_Override; 3864 3865 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3866 3867 // Merge attributes from the parameters. 3868 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3869 oe = oldMethod->param_end(); 3870 for (ObjCMethodDecl::param_iterator 3871 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3872 ni != ne && oi != oe; ++ni, ++oi) 3873 mergeParamDeclAttributes(*ni, *oi, *this); 3874 3875 CheckObjCMethodOverride(newMethod, oldMethod); 3876 } 3877 3878 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3879 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3880 3881 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3882 ? diag::err_redefinition_different_type 3883 : diag::err_redeclaration_different_type) 3884 << New->getDeclName() << New->getType() << Old->getType(); 3885 3886 diag::kind PrevDiag; 3887 SourceLocation OldLocation; 3888 std::tie(PrevDiag, OldLocation) 3889 = getNoteDiagForInvalidRedeclaration(Old, New); 3890 S.Diag(OldLocation, PrevDiag); 3891 New->setInvalidDecl(); 3892 } 3893 3894 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3895 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3896 /// emitting diagnostics as appropriate. 3897 /// 3898 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3899 /// to here in AddInitializerToDecl. We can't check them before the initializer 3900 /// is attached. 3901 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3902 bool MergeTypeWithOld) { 3903 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3904 return; 3905 3906 QualType MergedT; 3907 if (getLangOpts().CPlusPlus) { 3908 if (New->getType()->isUndeducedType()) { 3909 // We don't know what the new type is until the initializer is attached. 3910 return; 3911 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3912 // These could still be something that needs exception specs checked. 3913 return MergeVarDeclExceptionSpecs(New, Old); 3914 } 3915 // C++ [basic.link]p10: 3916 // [...] the types specified by all declarations referring to a given 3917 // object or function shall be identical, except that declarations for an 3918 // array object can specify array types that differ by the presence or 3919 // absence of a major array bound (8.3.4). 3920 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3921 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3922 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3923 3924 // We are merging a variable declaration New into Old. If it has an array 3925 // bound, and that bound differs from Old's bound, we should diagnose the 3926 // mismatch. 3927 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3928 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3929 PrevVD = PrevVD->getPreviousDecl()) { 3930 QualType PrevVDTy = PrevVD->getType(); 3931 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3932 continue; 3933 3934 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3935 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3936 } 3937 } 3938 3939 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3940 if (Context.hasSameType(OldArray->getElementType(), 3941 NewArray->getElementType())) 3942 MergedT = New->getType(); 3943 } 3944 // FIXME: Check visibility. New is hidden but has a complete type. If New 3945 // has no array bound, it should not inherit one from Old, if Old is not 3946 // visible. 3947 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3948 if (Context.hasSameType(OldArray->getElementType(), 3949 NewArray->getElementType())) 3950 MergedT = Old->getType(); 3951 } 3952 } 3953 else if (New->getType()->isObjCObjectPointerType() && 3954 Old->getType()->isObjCObjectPointerType()) { 3955 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3956 Old->getType()); 3957 } 3958 } else { 3959 // C 6.2.7p2: 3960 // All declarations that refer to the same object or function shall have 3961 // compatible type. 3962 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3963 } 3964 if (MergedT.isNull()) { 3965 // It's OK if we couldn't merge types if either type is dependent, for a 3966 // block-scope variable. In other cases (static data members of class 3967 // templates, variable templates, ...), we require the types to be 3968 // equivalent. 3969 // FIXME: The C++ standard doesn't say anything about this. 3970 if ((New->getType()->isDependentType() || 3971 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3972 // If the old type was dependent, we can't merge with it, so the new type 3973 // becomes dependent for now. We'll reproduce the original type when we 3974 // instantiate the TypeSourceInfo for the variable. 3975 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3976 New->setType(Context.DependentTy); 3977 return; 3978 } 3979 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3980 } 3981 3982 // Don't actually update the type on the new declaration if the old 3983 // declaration was an extern declaration in a different scope. 3984 if (MergeTypeWithOld) 3985 New->setType(MergedT); 3986 } 3987 3988 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3989 LookupResult &Previous) { 3990 // C11 6.2.7p4: 3991 // For an identifier with internal or external linkage declared 3992 // in a scope in which a prior declaration of that identifier is 3993 // visible, if the prior declaration specifies internal or 3994 // external linkage, the type of the identifier at the later 3995 // declaration becomes the composite type. 3996 // 3997 // If the variable isn't visible, we do not merge with its type. 3998 if (Previous.isShadowed()) 3999 return false; 4000 4001 if (S.getLangOpts().CPlusPlus) { 4002 // C++11 [dcl.array]p3: 4003 // If there is a preceding declaration of the entity in the same 4004 // scope in which the bound was specified, an omitted array bound 4005 // is taken to be the same as in that earlier declaration. 4006 return NewVD->isPreviousDeclInSameBlockScope() || 4007 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4008 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4009 } else { 4010 // If the old declaration was function-local, don't merge with its 4011 // type unless we're in the same function. 4012 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4013 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4014 } 4015 } 4016 4017 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4018 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4019 /// situation, merging decls or emitting diagnostics as appropriate. 4020 /// 4021 /// Tentative definition rules (C99 6.9.2p2) are checked by 4022 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4023 /// definitions here, since the initializer hasn't been attached. 4024 /// 4025 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4026 // If the new decl is already invalid, don't do any other checking. 4027 if (New->isInvalidDecl()) 4028 return; 4029 4030 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4031 return; 4032 4033 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4034 4035 // Verify the old decl was also a variable or variable template. 4036 VarDecl *Old = nullptr; 4037 VarTemplateDecl *OldTemplate = nullptr; 4038 if (Previous.isSingleResult()) { 4039 if (NewTemplate) { 4040 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4041 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4042 4043 if (auto *Shadow = 4044 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4045 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4046 return New->setInvalidDecl(); 4047 } else { 4048 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4049 4050 if (auto *Shadow = 4051 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4052 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4053 return New->setInvalidDecl(); 4054 } 4055 } 4056 if (!Old) { 4057 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4058 << New->getDeclName(); 4059 notePreviousDefinition(Previous.getRepresentativeDecl(), 4060 New->getLocation()); 4061 return New->setInvalidDecl(); 4062 } 4063 4064 // If the old declaration was found in an inline namespace and the new 4065 // declaration was qualified, update the DeclContext to match. 4066 adjustDeclContextForDeclaratorDecl(New, Old); 4067 4068 // Ensure the template parameters are compatible. 4069 if (NewTemplate && 4070 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4071 OldTemplate->getTemplateParameters(), 4072 /*Complain=*/true, TPL_TemplateMatch)) 4073 return New->setInvalidDecl(); 4074 4075 // C++ [class.mem]p1: 4076 // A member shall not be declared twice in the member-specification [...] 4077 // 4078 // Here, we need only consider static data members. 4079 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4080 Diag(New->getLocation(), diag::err_duplicate_member) 4081 << New->getIdentifier(); 4082 Diag(Old->getLocation(), diag::note_previous_declaration); 4083 New->setInvalidDecl(); 4084 } 4085 4086 mergeDeclAttributes(New, Old); 4087 // Warn if an already-declared variable is made a weak_import in a subsequent 4088 // declaration 4089 if (New->hasAttr<WeakImportAttr>() && 4090 Old->getStorageClass() == SC_None && 4091 !Old->hasAttr<WeakImportAttr>()) { 4092 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4093 notePreviousDefinition(Old, New->getLocation()); 4094 // Remove weak_import attribute on new declaration. 4095 New->dropAttr<WeakImportAttr>(); 4096 } 4097 4098 if (New->hasAttr<InternalLinkageAttr>() && 4099 !Old->hasAttr<InternalLinkageAttr>()) { 4100 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4101 << New->getDeclName(); 4102 notePreviousDefinition(Old, New->getLocation()); 4103 New->dropAttr<InternalLinkageAttr>(); 4104 } 4105 4106 // Merge the types. 4107 VarDecl *MostRecent = Old->getMostRecentDecl(); 4108 if (MostRecent != Old) { 4109 MergeVarDeclTypes(New, MostRecent, 4110 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4111 if (New->isInvalidDecl()) 4112 return; 4113 } 4114 4115 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4116 if (New->isInvalidDecl()) 4117 return; 4118 4119 diag::kind PrevDiag; 4120 SourceLocation OldLocation; 4121 std::tie(PrevDiag, OldLocation) = 4122 getNoteDiagForInvalidRedeclaration(Old, New); 4123 4124 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4125 if (New->getStorageClass() == SC_Static && 4126 !New->isStaticDataMember() && 4127 Old->hasExternalFormalLinkage()) { 4128 if (getLangOpts().MicrosoftExt) { 4129 Diag(New->getLocation(), diag::ext_static_non_static) 4130 << New->getDeclName(); 4131 Diag(OldLocation, PrevDiag); 4132 } else { 4133 Diag(New->getLocation(), diag::err_static_non_static) 4134 << New->getDeclName(); 4135 Diag(OldLocation, PrevDiag); 4136 return New->setInvalidDecl(); 4137 } 4138 } 4139 // C99 6.2.2p4: 4140 // For an identifier declared with the storage-class specifier 4141 // extern in a scope in which a prior declaration of that 4142 // identifier is visible,23) if the prior declaration specifies 4143 // internal or external linkage, the linkage of the identifier at 4144 // the later declaration is the same as the linkage specified at 4145 // the prior declaration. If no prior declaration is visible, or 4146 // if the prior declaration specifies no linkage, then the 4147 // identifier has external linkage. 4148 if (New->hasExternalStorage() && Old->hasLinkage()) 4149 /* Okay */; 4150 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4151 !New->isStaticDataMember() && 4152 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4153 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4154 Diag(OldLocation, PrevDiag); 4155 return New->setInvalidDecl(); 4156 } 4157 4158 // Check if extern is followed by non-extern and vice-versa. 4159 if (New->hasExternalStorage() && 4160 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4161 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4162 Diag(OldLocation, PrevDiag); 4163 return New->setInvalidDecl(); 4164 } 4165 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4166 !New->hasExternalStorage()) { 4167 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4168 Diag(OldLocation, PrevDiag); 4169 return New->setInvalidDecl(); 4170 } 4171 4172 if (CheckRedeclarationModuleOwnership(New, Old)) 4173 return; 4174 4175 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4176 4177 // FIXME: The test for external storage here seems wrong? We still 4178 // need to check for mismatches. 4179 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4180 // Don't complain about out-of-line definitions of static members. 4181 !(Old->getLexicalDeclContext()->isRecord() && 4182 !New->getLexicalDeclContext()->isRecord())) { 4183 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4184 Diag(OldLocation, PrevDiag); 4185 return New->setInvalidDecl(); 4186 } 4187 4188 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4189 if (VarDecl *Def = Old->getDefinition()) { 4190 // C++1z [dcl.fcn.spec]p4: 4191 // If the definition of a variable appears in a translation unit before 4192 // its first declaration as inline, the program is ill-formed. 4193 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4194 Diag(Def->getLocation(), diag::note_previous_definition); 4195 } 4196 } 4197 4198 // If this redeclaration makes the variable inline, we may need to add it to 4199 // UndefinedButUsed. 4200 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4201 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4202 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4203 SourceLocation())); 4204 4205 if (New->getTLSKind() != Old->getTLSKind()) { 4206 if (!Old->getTLSKind()) { 4207 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4208 Diag(OldLocation, PrevDiag); 4209 } else if (!New->getTLSKind()) { 4210 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4211 Diag(OldLocation, PrevDiag); 4212 } else { 4213 // Do not allow redeclaration to change the variable between requiring 4214 // static and dynamic initialization. 4215 // FIXME: GCC allows this, but uses the TLS keyword on the first 4216 // declaration to determine the kind. Do we need to be compatible here? 4217 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4218 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4219 Diag(OldLocation, PrevDiag); 4220 } 4221 } 4222 4223 // C++ doesn't have tentative definitions, so go right ahead and check here. 4224 if (getLangOpts().CPlusPlus && 4225 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4226 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4227 Old->getCanonicalDecl()->isConstexpr()) { 4228 // This definition won't be a definition any more once it's been merged. 4229 Diag(New->getLocation(), 4230 diag::warn_deprecated_redundant_constexpr_static_def); 4231 } else if (VarDecl *Def = Old->getDefinition()) { 4232 if (checkVarDeclRedefinition(Def, New)) 4233 return; 4234 } 4235 } 4236 4237 if (haveIncompatibleLanguageLinkages(Old, New)) { 4238 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4239 Diag(OldLocation, PrevDiag); 4240 New->setInvalidDecl(); 4241 return; 4242 } 4243 4244 // Merge "used" flag. 4245 if (Old->getMostRecentDecl()->isUsed(false)) 4246 New->setIsUsed(); 4247 4248 // Keep a chain of previous declarations. 4249 New->setPreviousDecl(Old); 4250 if (NewTemplate) 4251 NewTemplate->setPreviousDecl(OldTemplate); 4252 4253 // Inherit access appropriately. 4254 New->setAccess(Old->getAccess()); 4255 if (NewTemplate) 4256 NewTemplate->setAccess(New->getAccess()); 4257 4258 if (Old->isInline()) 4259 New->setImplicitlyInline(); 4260 } 4261 4262 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4263 SourceManager &SrcMgr = getSourceManager(); 4264 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4265 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4266 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4267 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4268 auto &HSI = PP.getHeaderSearchInfo(); 4269 StringRef HdrFilename = 4270 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4271 4272 auto noteFromModuleOrInclude = [&](Module *Mod, 4273 SourceLocation IncLoc) -> bool { 4274 // Redefinition errors with modules are common with non modular mapped 4275 // headers, example: a non-modular header H in module A that also gets 4276 // included directly in a TU. Pointing twice to the same header/definition 4277 // is confusing, try to get better diagnostics when modules is on. 4278 if (IncLoc.isValid()) { 4279 if (Mod) { 4280 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4281 << HdrFilename.str() << Mod->getFullModuleName(); 4282 if (!Mod->DefinitionLoc.isInvalid()) 4283 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4284 << Mod->getFullModuleName(); 4285 } else { 4286 Diag(IncLoc, diag::note_redefinition_include_same_file) 4287 << HdrFilename.str(); 4288 } 4289 return true; 4290 } 4291 4292 return false; 4293 }; 4294 4295 // Is it the same file and same offset? Provide more information on why 4296 // this leads to a redefinition error. 4297 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4298 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4299 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4300 bool EmittedDiag = 4301 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4302 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4303 4304 // If the header has no guards, emit a note suggesting one. 4305 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4306 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4307 4308 if (EmittedDiag) 4309 return; 4310 } 4311 4312 // Redefinition coming from different files or couldn't do better above. 4313 if (Old->getLocation().isValid()) 4314 Diag(Old->getLocation(), diag::note_previous_definition); 4315 } 4316 4317 /// We've just determined that \p Old and \p New both appear to be definitions 4318 /// of the same variable. Either diagnose or fix the problem. 4319 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4320 if (!hasVisibleDefinition(Old) && 4321 (New->getFormalLinkage() == InternalLinkage || 4322 New->isInline() || 4323 New->getDescribedVarTemplate() || 4324 New->getNumTemplateParameterLists() || 4325 New->getDeclContext()->isDependentContext())) { 4326 // The previous definition is hidden, and multiple definitions are 4327 // permitted (in separate TUs). Demote this to a declaration. 4328 New->demoteThisDefinitionToDeclaration(); 4329 4330 // Make the canonical definition visible. 4331 if (auto *OldTD = Old->getDescribedVarTemplate()) 4332 makeMergedDefinitionVisible(OldTD); 4333 makeMergedDefinitionVisible(Old); 4334 return false; 4335 } else { 4336 Diag(New->getLocation(), diag::err_redefinition) << New; 4337 notePreviousDefinition(Old, New->getLocation()); 4338 New->setInvalidDecl(); 4339 return true; 4340 } 4341 } 4342 4343 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4344 /// no declarator (e.g. "struct foo;") is parsed. 4345 Decl * 4346 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4347 RecordDecl *&AnonRecord) { 4348 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4349 AnonRecord); 4350 } 4351 4352 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4353 // disambiguate entities defined in different scopes. 4354 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4355 // compatibility. 4356 // We will pick our mangling number depending on which version of MSVC is being 4357 // targeted. 4358 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4359 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4360 ? S->getMSCurManglingNumber() 4361 : S->getMSLastManglingNumber(); 4362 } 4363 4364 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4365 if (!Context.getLangOpts().CPlusPlus) 4366 return; 4367 4368 if (isa<CXXRecordDecl>(Tag->getParent())) { 4369 // If this tag is the direct child of a class, number it if 4370 // it is anonymous. 4371 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4372 return; 4373 MangleNumberingContext &MCtx = 4374 Context.getManglingNumberContext(Tag->getParent()); 4375 Context.setManglingNumber( 4376 Tag, MCtx.getManglingNumber( 4377 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4378 return; 4379 } 4380 4381 // If this tag isn't a direct child of a class, number it if it is local. 4382 MangleNumberingContext *MCtx; 4383 Decl *ManglingContextDecl; 4384 std::tie(MCtx, ManglingContextDecl) = 4385 getCurrentMangleNumberContext(Tag->getDeclContext()); 4386 if (MCtx) { 4387 Context.setManglingNumber( 4388 Tag, MCtx->getManglingNumber( 4389 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4390 } 4391 } 4392 4393 namespace { 4394 struct NonCLikeKind { 4395 enum { 4396 None, 4397 BaseClass, 4398 DefaultMemberInit, 4399 Lambda, 4400 Friend, 4401 OtherMember, 4402 Invalid, 4403 } Kind = None; 4404 SourceRange Range; 4405 4406 explicit operator bool() { return Kind != None; } 4407 }; 4408 } 4409 4410 /// Determine whether a class is C-like, according to the rules of C++ 4411 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4412 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4413 if (RD->isInvalidDecl()) 4414 return {NonCLikeKind::Invalid, {}}; 4415 4416 // C++ [dcl.typedef]p9: [P1766R1] 4417 // An unnamed class with a typedef name for linkage purposes shall not 4418 // 4419 // -- have any base classes 4420 if (RD->getNumBases()) 4421 return {NonCLikeKind::BaseClass, 4422 SourceRange(RD->bases_begin()->getBeginLoc(), 4423 RD->bases_end()[-1].getEndLoc())}; 4424 bool Invalid = false; 4425 for (Decl *D : RD->decls()) { 4426 // Don't complain about things we already diagnosed. 4427 if (D->isInvalidDecl()) { 4428 Invalid = true; 4429 continue; 4430 } 4431 4432 // -- have any [...] default member initializers 4433 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4434 if (FD->hasInClassInitializer()) { 4435 auto *Init = FD->getInClassInitializer(); 4436 return {NonCLikeKind::DefaultMemberInit, 4437 Init ? Init->getSourceRange() : D->getSourceRange()}; 4438 } 4439 continue; 4440 } 4441 4442 // FIXME: We don't allow friend declarations. This violates the wording of 4443 // P1766, but not the intent. 4444 if (isa<FriendDecl>(D)) 4445 return {NonCLikeKind::Friend, D->getSourceRange()}; 4446 4447 // -- declare any members other than non-static data members, member 4448 // enumerations, or member classes, 4449 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4450 isa<EnumDecl>(D)) 4451 continue; 4452 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4453 if (!MemberRD) { 4454 if (D->isImplicit()) 4455 continue; 4456 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4457 } 4458 4459 // -- contain a lambda-expression, 4460 if (MemberRD->isLambda()) 4461 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4462 4463 // and all member classes shall also satisfy these requirements 4464 // (recursively). 4465 if (MemberRD->isThisDeclarationADefinition()) { 4466 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4467 return Kind; 4468 } 4469 } 4470 4471 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4472 } 4473 4474 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4475 TypedefNameDecl *NewTD) { 4476 if (TagFromDeclSpec->isInvalidDecl()) 4477 return; 4478 4479 // Do nothing if the tag already has a name for linkage purposes. 4480 if (TagFromDeclSpec->hasNameForLinkage()) 4481 return; 4482 4483 // A well-formed anonymous tag must always be a TUK_Definition. 4484 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4485 4486 // The type must match the tag exactly; no qualifiers allowed. 4487 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4488 Context.getTagDeclType(TagFromDeclSpec))) { 4489 if (getLangOpts().CPlusPlus) 4490 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4491 return; 4492 } 4493 4494 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4495 // An unnamed class with a typedef name for linkage purposes shall [be 4496 // C-like]. 4497 // 4498 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4499 // shouldn't happen, but there are constructs that the language rule doesn't 4500 // disallow for which we can't reasonably avoid computing linkage early. 4501 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4502 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4503 : NonCLikeKind(); 4504 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4505 if (NonCLike || ChangesLinkage) { 4506 if (NonCLike.Kind == NonCLikeKind::Invalid) 4507 return; 4508 4509 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4510 if (ChangesLinkage) { 4511 // If the linkage changes, we can't accept this as an extension. 4512 if (NonCLike.Kind == NonCLikeKind::None) 4513 DiagID = diag::err_typedef_changes_linkage; 4514 else 4515 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4516 } 4517 4518 SourceLocation FixitLoc = 4519 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4520 llvm::SmallString<40> TextToInsert; 4521 TextToInsert += ' '; 4522 TextToInsert += NewTD->getIdentifier()->getName(); 4523 4524 Diag(FixitLoc, DiagID) 4525 << isa<TypeAliasDecl>(NewTD) 4526 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4527 if (NonCLike.Kind != NonCLikeKind::None) { 4528 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4529 << NonCLike.Kind - 1 << NonCLike.Range; 4530 } 4531 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4532 << NewTD << isa<TypeAliasDecl>(NewTD); 4533 4534 if (ChangesLinkage) 4535 return; 4536 } 4537 4538 // Otherwise, set this as the anon-decl typedef for the tag. 4539 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4540 } 4541 4542 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4543 switch (T) { 4544 case DeclSpec::TST_class: 4545 return 0; 4546 case DeclSpec::TST_struct: 4547 return 1; 4548 case DeclSpec::TST_interface: 4549 return 2; 4550 case DeclSpec::TST_union: 4551 return 3; 4552 case DeclSpec::TST_enum: 4553 return 4; 4554 default: 4555 llvm_unreachable("unexpected type specifier"); 4556 } 4557 } 4558 4559 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4560 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4561 /// parameters to cope with template friend declarations. 4562 Decl * 4563 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4564 MultiTemplateParamsArg TemplateParams, 4565 bool IsExplicitInstantiation, 4566 RecordDecl *&AnonRecord) { 4567 Decl *TagD = nullptr; 4568 TagDecl *Tag = nullptr; 4569 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4570 DS.getTypeSpecType() == DeclSpec::TST_struct || 4571 DS.getTypeSpecType() == DeclSpec::TST_interface || 4572 DS.getTypeSpecType() == DeclSpec::TST_union || 4573 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4574 TagD = DS.getRepAsDecl(); 4575 4576 if (!TagD) // We probably had an error 4577 return nullptr; 4578 4579 // Note that the above type specs guarantee that the 4580 // type rep is a Decl, whereas in many of the others 4581 // it's a Type. 4582 if (isa<TagDecl>(TagD)) 4583 Tag = cast<TagDecl>(TagD); 4584 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4585 Tag = CTD->getTemplatedDecl(); 4586 } 4587 4588 if (Tag) { 4589 handleTagNumbering(Tag, S); 4590 Tag->setFreeStanding(); 4591 if (Tag->isInvalidDecl()) 4592 return Tag; 4593 } 4594 4595 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4596 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4597 // or incomplete types shall not be restrict-qualified." 4598 if (TypeQuals & DeclSpec::TQ_restrict) 4599 Diag(DS.getRestrictSpecLoc(), 4600 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4601 << DS.getSourceRange(); 4602 } 4603 4604 if (DS.isInlineSpecified()) 4605 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4606 << getLangOpts().CPlusPlus17; 4607 4608 if (DS.hasConstexprSpecifier()) { 4609 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4610 // and definitions of functions and variables. 4611 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4612 // the declaration of a function or function template 4613 if (Tag) 4614 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4615 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4616 << static_cast<int>(DS.getConstexprSpecifier()); 4617 else 4618 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4619 << static_cast<int>(DS.getConstexprSpecifier()); 4620 // Don't emit warnings after this error. 4621 return TagD; 4622 } 4623 4624 DiagnoseFunctionSpecifiers(DS); 4625 4626 if (DS.isFriendSpecified()) { 4627 // If we're dealing with a decl but not a TagDecl, assume that 4628 // whatever routines created it handled the friendship aspect. 4629 if (TagD && !Tag) 4630 return nullptr; 4631 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4632 } 4633 4634 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4635 bool IsExplicitSpecialization = 4636 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4637 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4638 !IsExplicitInstantiation && !IsExplicitSpecialization && 4639 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4640 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4641 // nested-name-specifier unless it is an explicit instantiation 4642 // or an explicit specialization. 4643 // 4644 // FIXME: We allow class template partial specializations here too, per the 4645 // obvious intent of DR1819. 4646 // 4647 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4648 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4649 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4650 return nullptr; 4651 } 4652 4653 // Track whether this decl-specifier declares anything. 4654 bool DeclaresAnything = true; 4655 4656 // Handle anonymous struct definitions. 4657 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4658 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4659 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4660 if (getLangOpts().CPlusPlus || 4661 Record->getDeclContext()->isRecord()) { 4662 // If CurContext is a DeclContext that can contain statements, 4663 // RecursiveASTVisitor won't visit the decls that 4664 // BuildAnonymousStructOrUnion() will put into CurContext. 4665 // Also store them here so that they can be part of the 4666 // DeclStmt that gets created in this case. 4667 // FIXME: Also return the IndirectFieldDecls created by 4668 // BuildAnonymousStructOr union, for the same reason? 4669 if (CurContext->isFunctionOrMethod()) 4670 AnonRecord = Record; 4671 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4672 Context.getPrintingPolicy()); 4673 } 4674 4675 DeclaresAnything = false; 4676 } 4677 } 4678 4679 // C11 6.7.2.1p2: 4680 // A struct-declaration that does not declare an anonymous structure or 4681 // anonymous union shall contain a struct-declarator-list. 4682 // 4683 // This rule also existed in C89 and C99; the grammar for struct-declaration 4684 // did not permit a struct-declaration without a struct-declarator-list. 4685 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4686 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4687 // Check for Microsoft C extension: anonymous struct/union member. 4688 // Handle 2 kinds of anonymous struct/union: 4689 // struct STRUCT; 4690 // union UNION; 4691 // and 4692 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4693 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4694 if ((Tag && Tag->getDeclName()) || 4695 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4696 RecordDecl *Record = nullptr; 4697 if (Tag) 4698 Record = dyn_cast<RecordDecl>(Tag); 4699 else if (const RecordType *RT = 4700 DS.getRepAsType().get()->getAsStructureType()) 4701 Record = RT->getDecl(); 4702 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4703 Record = UT->getDecl(); 4704 4705 if (Record && getLangOpts().MicrosoftExt) { 4706 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4707 << Record->isUnion() << DS.getSourceRange(); 4708 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4709 } 4710 4711 DeclaresAnything = false; 4712 } 4713 } 4714 4715 // Skip all the checks below if we have a type error. 4716 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4717 (TagD && TagD->isInvalidDecl())) 4718 return TagD; 4719 4720 if (getLangOpts().CPlusPlus && 4721 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4722 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4723 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4724 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4725 DeclaresAnything = false; 4726 4727 if (!DS.isMissingDeclaratorOk()) { 4728 // Customize diagnostic for a typedef missing a name. 4729 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4730 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4731 << DS.getSourceRange(); 4732 else 4733 DeclaresAnything = false; 4734 } 4735 4736 if (DS.isModulePrivateSpecified() && 4737 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4738 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4739 << Tag->getTagKind() 4740 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4741 4742 ActOnDocumentableDecl(TagD); 4743 4744 // C 6.7/2: 4745 // A declaration [...] shall declare at least a declarator [...], a tag, 4746 // or the members of an enumeration. 4747 // C++ [dcl.dcl]p3: 4748 // [If there are no declarators], and except for the declaration of an 4749 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4750 // names into the program, or shall redeclare a name introduced by a 4751 // previous declaration. 4752 if (!DeclaresAnything) { 4753 // In C, we allow this as a (popular) extension / bug. Don't bother 4754 // producing further diagnostics for redundant qualifiers after this. 4755 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4756 ? diag::err_no_declarators 4757 : diag::ext_no_declarators) 4758 << DS.getSourceRange(); 4759 return TagD; 4760 } 4761 4762 // C++ [dcl.stc]p1: 4763 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4764 // init-declarator-list of the declaration shall not be empty. 4765 // C++ [dcl.fct.spec]p1: 4766 // If a cv-qualifier appears in a decl-specifier-seq, the 4767 // init-declarator-list of the declaration shall not be empty. 4768 // 4769 // Spurious qualifiers here appear to be valid in C. 4770 unsigned DiagID = diag::warn_standalone_specifier; 4771 if (getLangOpts().CPlusPlus) 4772 DiagID = diag::ext_standalone_specifier; 4773 4774 // Note that a linkage-specification sets a storage class, but 4775 // 'extern "C" struct foo;' is actually valid and not theoretically 4776 // useless. 4777 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4778 if (SCS == DeclSpec::SCS_mutable) 4779 // Since mutable is not a viable storage class specifier in C, there is 4780 // no reason to treat it as an extension. Instead, diagnose as an error. 4781 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4782 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4783 Diag(DS.getStorageClassSpecLoc(), DiagID) 4784 << DeclSpec::getSpecifierName(SCS); 4785 } 4786 4787 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4788 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4789 << DeclSpec::getSpecifierName(TSCS); 4790 if (DS.getTypeQualifiers()) { 4791 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4792 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4793 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4794 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4795 // Restrict is covered above. 4796 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4797 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4798 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4799 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4800 } 4801 4802 // Warn about ignored type attributes, for example: 4803 // __attribute__((aligned)) struct A; 4804 // Attributes should be placed after tag to apply to type declaration. 4805 if (!DS.getAttributes().empty()) { 4806 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4807 if (TypeSpecType == DeclSpec::TST_class || 4808 TypeSpecType == DeclSpec::TST_struct || 4809 TypeSpecType == DeclSpec::TST_interface || 4810 TypeSpecType == DeclSpec::TST_union || 4811 TypeSpecType == DeclSpec::TST_enum) { 4812 for (const ParsedAttr &AL : DS.getAttributes()) 4813 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4814 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4815 } 4816 } 4817 4818 return TagD; 4819 } 4820 4821 /// We are trying to inject an anonymous member into the given scope; 4822 /// check if there's an existing declaration that can't be overloaded. 4823 /// 4824 /// \return true if this is a forbidden redeclaration 4825 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4826 Scope *S, 4827 DeclContext *Owner, 4828 DeclarationName Name, 4829 SourceLocation NameLoc, 4830 bool IsUnion) { 4831 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4832 Sema::ForVisibleRedeclaration); 4833 if (!SemaRef.LookupName(R, S)) return false; 4834 4835 // Pick a representative declaration. 4836 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4837 assert(PrevDecl && "Expected a non-null Decl"); 4838 4839 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4840 return false; 4841 4842 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4843 << IsUnion << Name; 4844 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4845 4846 return true; 4847 } 4848 4849 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4850 /// anonymous struct or union AnonRecord into the owning context Owner 4851 /// and scope S. This routine will be invoked just after we realize 4852 /// that an unnamed union or struct is actually an anonymous union or 4853 /// struct, e.g., 4854 /// 4855 /// @code 4856 /// union { 4857 /// int i; 4858 /// float f; 4859 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4860 /// // f into the surrounding scope.x 4861 /// @endcode 4862 /// 4863 /// This routine is recursive, injecting the names of nested anonymous 4864 /// structs/unions into the owning context and scope as well. 4865 static bool 4866 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4867 RecordDecl *AnonRecord, AccessSpecifier AS, 4868 SmallVectorImpl<NamedDecl *> &Chaining) { 4869 bool Invalid = false; 4870 4871 // Look every FieldDecl and IndirectFieldDecl with a name. 4872 for (auto *D : AnonRecord->decls()) { 4873 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4874 cast<NamedDecl>(D)->getDeclName()) { 4875 ValueDecl *VD = cast<ValueDecl>(D); 4876 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4877 VD->getLocation(), 4878 AnonRecord->isUnion())) { 4879 // C++ [class.union]p2: 4880 // The names of the members of an anonymous union shall be 4881 // distinct from the names of any other entity in the 4882 // scope in which the anonymous union is declared. 4883 Invalid = true; 4884 } else { 4885 // C++ [class.union]p2: 4886 // For the purpose of name lookup, after the anonymous union 4887 // definition, the members of the anonymous union are 4888 // considered to have been defined in the scope in which the 4889 // anonymous union is declared. 4890 unsigned OldChainingSize = Chaining.size(); 4891 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4892 Chaining.append(IF->chain_begin(), IF->chain_end()); 4893 else 4894 Chaining.push_back(VD); 4895 4896 assert(Chaining.size() >= 2); 4897 NamedDecl **NamedChain = 4898 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4899 for (unsigned i = 0; i < Chaining.size(); i++) 4900 NamedChain[i] = Chaining[i]; 4901 4902 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4903 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4904 VD->getType(), {NamedChain, Chaining.size()}); 4905 4906 for (const auto *Attr : VD->attrs()) 4907 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4908 4909 IndirectField->setAccess(AS); 4910 IndirectField->setImplicit(); 4911 SemaRef.PushOnScopeChains(IndirectField, S); 4912 4913 // That includes picking up the appropriate access specifier. 4914 if (AS != AS_none) IndirectField->setAccess(AS); 4915 4916 Chaining.resize(OldChainingSize); 4917 } 4918 } 4919 } 4920 4921 return Invalid; 4922 } 4923 4924 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4925 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4926 /// illegal input values are mapped to SC_None. 4927 static StorageClass 4928 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4929 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4930 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4931 "Parser allowed 'typedef' as storage class VarDecl."); 4932 switch (StorageClassSpec) { 4933 case DeclSpec::SCS_unspecified: return SC_None; 4934 case DeclSpec::SCS_extern: 4935 if (DS.isExternInLinkageSpec()) 4936 return SC_None; 4937 return SC_Extern; 4938 case DeclSpec::SCS_static: return SC_Static; 4939 case DeclSpec::SCS_auto: return SC_Auto; 4940 case DeclSpec::SCS_register: return SC_Register; 4941 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4942 // Illegal SCSs map to None: error reporting is up to the caller. 4943 case DeclSpec::SCS_mutable: // Fall through. 4944 case DeclSpec::SCS_typedef: return SC_None; 4945 } 4946 llvm_unreachable("unknown storage class specifier"); 4947 } 4948 4949 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4950 assert(Record->hasInClassInitializer()); 4951 4952 for (const auto *I : Record->decls()) { 4953 const auto *FD = dyn_cast<FieldDecl>(I); 4954 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4955 FD = IFD->getAnonField(); 4956 if (FD && FD->hasInClassInitializer()) 4957 return FD->getLocation(); 4958 } 4959 4960 llvm_unreachable("couldn't find in-class initializer"); 4961 } 4962 4963 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4964 SourceLocation DefaultInitLoc) { 4965 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4966 return; 4967 4968 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4969 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4970 } 4971 4972 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4973 CXXRecordDecl *AnonUnion) { 4974 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4975 return; 4976 4977 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4978 } 4979 4980 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4981 /// anonymous structure or union. Anonymous unions are a C++ feature 4982 /// (C++ [class.union]) and a C11 feature; anonymous structures 4983 /// are a C11 feature and GNU C++ extension. 4984 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4985 AccessSpecifier AS, 4986 RecordDecl *Record, 4987 const PrintingPolicy &Policy) { 4988 DeclContext *Owner = Record->getDeclContext(); 4989 4990 // Diagnose whether this anonymous struct/union is an extension. 4991 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4992 Diag(Record->getLocation(), diag::ext_anonymous_union); 4993 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4994 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4995 else if (!Record->isUnion() && !getLangOpts().C11) 4996 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4997 4998 // C and C++ require different kinds of checks for anonymous 4999 // structs/unions. 5000 bool Invalid = false; 5001 if (getLangOpts().CPlusPlus) { 5002 const char *PrevSpec = nullptr; 5003 if (Record->isUnion()) { 5004 // C++ [class.union]p6: 5005 // C++17 [class.union.anon]p2: 5006 // Anonymous unions declared in a named namespace or in the 5007 // global namespace shall be declared static. 5008 unsigned DiagID; 5009 DeclContext *OwnerScope = Owner->getRedeclContext(); 5010 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5011 (OwnerScope->isTranslationUnit() || 5012 (OwnerScope->isNamespace() && 5013 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5014 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5015 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5016 5017 // Recover by adding 'static'. 5018 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5019 PrevSpec, DiagID, Policy); 5020 } 5021 // C++ [class.union]p6: 5022 // A storage class is not allowed in a declaration of an 5023 // anonymous union in a class scope. 5024 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5025 isa<RecordDecl>(Owner)) { 5026 Diag(DS.getStorageClassSpecLoc(), 5027 diag::err_anonymous_union_with_storage_spec) 5028 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5029 5030 // Recover by removing the storage specifier. 5031 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5032 SourceLocation(), 5033 PrevSpec, DiagID, Context.getPrintingPolicy()); 5034 } 5035 } 5036 5037 // Ignore const/volatile/restrict qualifiers. 5038 if (DS.getTypeQualifiers()) { 5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5040 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5041 << Record->isUnion() << "const" 5042 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5044 Diag(DS.getVolatileSpecLoc(), 5045 diag::ext_anonymous_struct_union_qualified) 5046 << Record->isUnion() << "volatile" 5047 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5049 Diag(DS.getRestrictSpecLoc(), 5050 diag::ext_anonymous_struct_union_qualified) 5051 << Record->isUnion() << "restrict" 5052 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5053 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5054 Diag(DS.getAtomicSpecLoc(), 5055 diag::ext_anonymous_struct_union_qualified) 5056 << Record->isUnion() << "_Atomic" 5057 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5058 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5059 Diag(DS.getUnalignedSpecLoc(), 5060 diag::ext_anonymous_struct_union_qualified) 5061 << Record->isUnion() << "__unaligned" 5062 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5063 5064 DS.ClearTypeQualifiers(); 5065 } 5066 5067 // C++ [class.union]p2: 5068 // The member-specification of an anonymous union shall only 5069 // define non-static data members. [Note: nested types and 5070 // functions cannot be declared within an anonymous union. ] 5071 for (auto *Mem : Record->decls()) { 5072 // Ignore invalid declarations; we already diagnosed them. 5073 if (Mem->isInvalidDecl()) 5074 continue; 5075 5076 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5077 // C++ [class.union]p3: 5078 // An anonymous union shall not have private or protected 5079 // members (clause 11). 5080 assert(FD->getAccess() != AS_none); 5081 if (FD->getAccess() != AS_public) { 5082 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5083 << Record->isUnion() << (FD->getAccess() == AS_protected); 5084 Invalid = true; 5085 } 5086 5087 // C++ [class.union]p1 5088 // An object of a class with a non-trivial constructor, a non-trivial 5089 // copy constructor, a non-trivial destructor, or a non-trivial copy 5090 // assignment operator cannot be a member of a union, nor can an 5091 // array of such objects. 5092 if (CheckNontrivialField(FD)) 5093 Invalid = true; 5094 } else if (Mem->isImplicit()) { 5095 // Any implicit members are fine. 5096 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5097 // This is a type that showed up in an 5098 // elaborated-type-specifier inside the anonymous struct or 5099 // union, but which actually declares a type outside of the 5100 // anonymous struct or union. It's okay. 5101 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5102 if (!MemRecord->isAnonymousStructOrUnion() && 5103 MemRecord->getDeclName()) { 5104 // Visual C++ allows type definition in anonymous struct or union. 5105 if (getLangOpts().MicrosoftExt) 5106 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5107 << Record->isUnion(); 5108 else { 5109 // This is a nested type declaration. 5110 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5111 << Record->isUnion(); 5112 Invalid = true; 5113 } 5114 } else { 5115 // This is an anonymous type definition within another anonymous type. 5116 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5117 // not part of standard C++. 5118 Diag(MemRecord->getLocation(), 5119 diag::ext_anonymous_record_with_anonymous_type) 5120 << Record->isUnion(); 5121 } 5122 } else if (isa<AccessSpecDecl>(Mem)) { 5123 // Any access specifier is fine. 5124 } else if (isa<StaticAssertDecl>(Mem)) { 5125 // In C++1z, static_assert declarations are also fine. 5126 } else { 5127 // We have something that isn't a non-static data 5128 // member. Complain about it. 5129 unsigned DK = diag::err_anonymous_record_bad_member; 5130 if (isa<TypeDecl>(Mem)) 5131 DK = diag::err_anonymous_record_with_type; 5132 else if (isa<FunctionDecl>(Mem)) 5133 DK = diag::err_anonymous_record_with_function; 5134 else if (isa<VarDecl>(Mem)) 5135 DK = diag::err_anonymous_record_with_static; 5136 5137 // Visual C++ allows type definition in anonymous struct or union. 5138 if (getLangOpts().MicrosoftExt && 5139 DK == diag::err_anonymous_record_with_type) 5140 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5141 << Record->isUnion(); 5142 else { 5143 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5144 Invalid = true; 5145 } 5146 } 5147 } 5148 5149 // C++11 [class.union]p8 (DR1460): 5150 // At most one variant member of a union may have a 5151 // brace-or-equal-initializer. 5152 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5153 Owner->isRecord()) 5154 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5155 cast<CXXRecordDecl>(Record)); 5156 } 5157 5158 if (!Record->isUnion() && !Owner->isRecord()) { 5159 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5160 << getLangOpts().CPlusPlus; 5161 Invalid = true; 5162 } 5163 5164 // C++ [dcl.dcl]p3: 5165 // [If there are no declarators], and except for the declaration of an 5166 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5167 // names into the program 5168 // C++ [class.mem]p2: 5169 // each such member-declaration shall either declare at least one member 5170 // name of the class or declare at least one unnamed bit-field 5171 // 5172 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5173 if (getLangOpts().CPlusPlus && Record->field_empty()) 5174 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5175 5176 // Mock up a declarator. 5177 Declarator Dc(DS, DeclaratorContext::Member); 5178 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5179 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5180 5181 // Create a declaration for this anonymous struct/union. 5182 NamedDecl *Anon = nullptr; 5183 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5184 Anon = FieldDecl::Create( 5185 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5186 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5187 /*BitWidth=*/nullptr, /*Mutable=*/false, 5188 /*InitStyle=*/ICIS_NoInit); 5189 Anon->setAccess(AS); 5190 ProcessDeclAttributes(S, Anon, Dc); 5191 5192 if (getLangOpts().CPlusPlus) 5193 FieldCollector->Add(cast<FieldDecl>(Anon)); 5194 } else { 5195 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5196 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5197 if (SCSpec == DeclSpec::SCS_mutable) { 5198 // mutable can only appear on non-static class members, so it's always 5199 // an error here 5200 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5201 Invalid = true; 5202 SC = SC_None; 5203 } 5204 5205 assert(DS.getAttributes().empty() && "No attribute expected"); 5206 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5207 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5208 Context.getTypeDeclType(Record), TInfo, SC); 5209 5210 // Default-initialize the implicit variable. This initialization will be 5211 // trivial in almost all cases, except if a union member has an in-class 5212 // initializer: 5213 // union { int n = 0; }; 5214 if (!Invalid) 5215 ActOnUninitializedDecl(Anon); 5216 } 5217 Anon->setImplicit(); 5218 5219 // Mark this as an anonymous struct/union type. 5220 Record->setAnonymousStructOrUnion(true); 5221 5222 // Add the anonymous struct/union object to the current 5223 // context. We'll be referencing this object when we refer to one of 5224 // its members. 5225 Owner->addDecl(Anon); 5226 5227 // Inject the members of the anonymous struct/union into the owning 5228 // context and into the identifier resolver chain for name lookup 5229 // purposes. 5230 SmallVector<NamedDecl*, 2> Chain; 5231 Chain.push_back(Anon); 5232 5233 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5234 Invalid = true; 5235 5236 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5237 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5238 MangleNumberingContext *MCtx; 5239 Decl *ManglingContextDecl; 5240 std::tie(MCtx, ManglingContextDecl) = 5241 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5242 if (MCtx) { 5243 Context.setManglingNumber( 5244 NewVD, MCtx->getManglingNumber( 5245 NewVD, getMSManglingNumber(getLangOpts(), S))); 5246 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5247 } 5248 } 5249 } 5250 5251 if (Invalid) 5252 Anon->setInvalidDecl(); 5253 5254 return Anon; 5255 } 5256 5257 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5258 /// Microsoft C anonymous structure. 5259 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5260 /// Example: 5261 /// 5262 /// struct A { int a; }; 5263 /// struct B { struct A; int b; }; 5264 /// 5265 /// void foo() { 5266 /// B var; 5267 /// var.a = 3; 5268 /// } 5269 /// 5270 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5271 RecordDecl *Record) { 5272 assert(Record && "expected a record!"); 5273 5274 // Mock up a declarator. 5275 Declarator Dc(DS, DeclaratorContext::TypeName); 5276 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5277 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5278 5279 auto *ParentDecl = cast<RecordDecl>(CurContext); 5280 QualType RecTy = Context.getTypeDeclType(Record); 5281 5282 // Create a declaration for this anonymous struct. 5283 NamedDecl *Anon = 5284 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5285 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5286 /*BitWidth=*/nullptr, /*Mutable=*/false, 5287 /*InitStyle=*/ICIS_NoInit); 5288 Anon->setImplicit(); 5289 5290 // Add the anonymous struct object to the current context. 5291 CurContext->addDecl(Anon); 5292 5293 // Inject the members of the anonymous struct into the current 5294 // context and into the identifier resolver chain for name lookup 5295 // purposes. 5296 SmallVector<NamedDecl*, 2> Chain; 5297 Chain.push_back(Anon); 5298 5299 RecordDecl *RecordDef = Record->getDefinition(); 5300 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5301 diag::err_field_incomplete_or_sizeless) || 5302 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5303 AS_none, Chain)) { 5304 Anon->setInvalidDecl(); 5305 ParentDecl->setInvalidDecl(); 5306 } 5307 5308 return Anon; 5309 } 5310 5311 /// GetNameForDeclarator - Determine the full declaration name for the 5312 /// given Declarator. 5313 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5314 return GetNameFromUnqualifiedId(D.getName()); 5315 } 5316 5317 /// Retrieves the declaration name from a parsed unqualified-id. 5318 DeclarationNameInfo 5319 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5320 DeclarationNameInfo NameInfo; 5321 NameInfo.setLoc(Name.StartLocation); 5322 5323 switch (Name.getKind()) { 5324 5325 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5326 case UnqualifiedIdKind::IK_Identifier: 5327 NameInfo.setName(Name.Identifier); 5328 return NameInfo; 5329 5330 case UnqualifiedIdKind::IK_DeductionGuideName: { 5331 // C++ [temp.deduct.guide]p3: 5332 // The simple-template-id shall name a class template specialization. 5333 // The template-name shall be the same identifier as the template-name 5334 // of the simple-template-id. 5335 // These together intend to imply that the template-name shall name a 5336 // class template. 5337 // FIXME: template<typename T> struct X {}; 5338 // template<typename T> using Y = X<T>; 5339 // Y(int) -> Y<int>; 5340 // satisfies these rules but does not name a class template. 5341 TemplateName TN = Name.TemplateName.get().get(); 5342 auto *Template = TN.getAsTemplateDecl(); 5343 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5344 Diag(Name.StartLocation, 5345 diag::err_deduction_guide_name_not_class_template) 5346 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5347 if (Template) 5348 Diag(Template->getLocation(), diag::note_template_decl_here); 5349 return DeclarationNameInfo(); 5350 } 5351 5352 NameInfo.setName( 5353 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5354 return NameInfo; 5355 } 5356 5357 case UnqualifiedIdKind::IK_OperatorFunctionId: 5358 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5359 Name.OperatorFunctionId.Operator)); 5360 NameInfo.setCXXOperatorNameRange(SourceRange( 5361 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5362 return NameInfo; 5363 5364 case UnqualifiedIdKind::IK_LiteralOperatorId: 5365 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5366 Name.Identifier)); 5367 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5368 return NameInfo; 5369 5370 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5371 TypeSourceInfo *TInfo; 5372 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5373 if (Ty.isNull()) 5374 return DeclarationNameInfo(); 5375 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5376 Context.getCanonicalType(Ty))); 5377 NameInfo.setNamedTypeInfo(TInfo); 5378 return NameInfo; 5379 } 5380 5381 case UnqualifiedIdKind::IK_ConstructorName: { 5382 TypeSourceInfo *TInfo; 5383 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5384 if (Ty.isNull()) 5385 return DeclarationNameInfo(); 5386 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5387 Context.getCanonicalType(Ty))); 5388 NameInfo.setNamedTypeInfo(TInfo); 5389 return NameInfo; 5390 } 5391 5392 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5393 // In well-formed code, we can only have a constructor 5394 // template-id that refers to the current context, so go there 5395 // to find the actual type being constructed. 5396 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5397 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5398 return DeclarationNameInfo(); 5399 5400 // Determine the type of the class being constructed. 5401 QualType CurClassType = Context.getTypeDeclType(CurClass); 5402 5403 // FIXME: Check two things: that the template-id names the same type as 5404 // CurClassType, and that the template-id does not occur when the name 5405 // was qualified. 5406 5407 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5408 Context.getCanonicalType(CurClassType))); 5409 // FIXME: should we retrieve TypeSourceInfo? 5410 NameInfo.setNamedTypeInfo(nullptr); 5411 return NameInfo; 5412 } 5413 5414 case UnqualifiedIdKind::IK_DestructorName: { 5415 TypeSourceInfo *TInfo; 5416 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5417 if (Ty.isNull()) 5418 return DeclarationNameInfo(); 5419 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5420 Context.getCanonicalType(Ty))); 5421 NameInfo.setNamedTypeInfo(TInfo); 5422 return NameInfo; 5423 } 5424 5425 case UnqualifiedIdKind::IK_TemplateId: { 5426 TemplateName TName = Name.TemplateId->Template.get(); 5427 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5428 return Context.getNameForTemplate(TName, TNameLoc); 5429 } 5430 5431 } // switch (Name.getKind()) 5432 5433 llvm_unreachable("Unknown name kind"); 5434 } 5435 5436 static QualType getCoreType(QualType Ty) { 5437 do { 5438 if (Ty->isPointerType() || Ty->isReferenceType()) 5439 Ty = Ty->getPointeeType(); 5440 else if (Ty->isArrayType()) 5441 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5442 else 5443 return Ty.withoutLocalFastQualifiers(); 5444 } while (true); 5445 } 5446 5447 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5448 /// and Definition have "nearly" matching parameters. This heuristic is 5449 /// used to improve diagnostics in the case where an out-of-line function 5450 /// definition doesn't match any declaration within the class or namespace. 5451 /// Also sets Params to the list of indices to the parameters that differ 5452 /// between the declaration and the definition. If hasSimilarParameters 5453 /// returns true and Params is empty, then all of the parameters match. 5454 static bool hasSimilarParameters(ASTContext &Context, 5455 FunctionDecl *Declaration, 5456 FunctionDecl *Definition, 5457 SmallVectorImpl<unsigned> &Params) { 5458 Params.clear(); 5459 if (Declaration->param_size() != Definition->param_size()) 5460 return false; 5461 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5462 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5463 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5464 5465 // The parameter types are identical 5466 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5467 continue; 5468 5469 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5470 QualType DefParamBaseTy = getCoreType(DefParamTy); 5471 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5472 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5473 5474 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5475 (DeclTyName && DeclTyName == DefTyName)) 5476 Params.push_back(Idx); 5477 else // The two parameters aren't even close 5478 return false; 5479 } 5480 5481 return true; 5482 } 5483 5484 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5485 /// declarator needs to be rebuilt in the current instantiation. 5486 /// Any bits of declarator which appear before the name are valid for 5487 /// consideration here. That's specifically the type in the decl spec 5488 /// and the base type in any member-pointer chunks. 5489 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5490 DeclarationName Name) { 5491 // The types we specifically need to rebuild are: 5492 // - typenames, typeofs, and decltypes 5493 // - types which will become injected class names 5494 // Of course, we also need to rebuild any type referencing such a 5495 // type. It's safest to just say "dependent", but we call out a 5496 // few cases here. 5497 5498 DeclSpec &DS = D.getMutableDeclSpec(); 5499 switch (DS.getTypeSpecType()) { 5500 case DeclSpec::TST_typename: 5501 case DeclSpec::TST_typeofType: 5502 case DeclSpec::TST_underlyingType: 5503 case DeclSpec::TST_atomic: { 5504 // Grab the type from the parser. 5505 TypeSourceInfo *TSI = nullptr; 5506 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5507 if (T.isNull() || !T->isInstantiationDependentType()) break; 5508 5509 // Make sure there's a type source info. This isn't really much 5510 // of a waste; most dependent types should have type source info 5511 // attached already. 5512 if (!TSI) 5513 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5514 5515 // Rebuild the type in the current instantiation. 5516 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5517 if (!TSI) return true; 5518 5519 // Store the new type back in the decl spec. 5520 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5521 DS.UpdateTypeRep(LocType); 5522 break; 5523 } 5524 5525 case DeclSpec::TST_decltype: 5526 case DeclSpec::TST_typeofExpr: { 5527 Expr *E = DS.getRepAsExpr(); 5528 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5529 if (Result.isInvalid()) return true; 5530 DS.UpdateExprRep(Result.get()); 5531 break; 5532 } 5533 5534 default: 5535 // Nothing to do for these decl specs. 5536 break; 5537 } 5538 5539 // It doesn't matter what order we do this in. 5540 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5541 DeclaratorChunk &Chunk = D.getTypeObject(I); 5542 5543 // The only type information in the declarator which can come 5544 // before the declaration name is the base type of a member 5545 // pointer. 5546 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5547 continue; 5548 5549 // Rebuild the scope specifier in-place. 5550 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5551 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5552 return true; 5553 } 5554 5555 return false; 5556 } 5557 5558 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5559 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5560 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5561 5562 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5563 Dcl && Dcl->getDeclContext()->isFileContext()) 5564 Dcl->setTopLevelDeclInObjCContainer(); 5565 5566 if (getLangOpts().OpenCL) 5567 setCurrentOpenCLExtensionForDecl(Dcl); 5568 5569 return Dcl; 5570 } 5571 5572 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5573 /// If T is the name of a class, then each of the following shall have a 5574 /// name different from T: 5575 /// - every static data member of class T; 5576 /// - every member function of class T 5577 /// - every member of class T that is itself a type; 5578 /// \returns true if the declaration name violates these rules. 5579 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5580 DeclarationNameInfo NameInfo) { 5581 DeclarationName Name = NameInfo.getName(); 5582 5583 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5584 while (Record && Record->isAnonymousStructOrUnion()) 5585 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5586 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5587 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5588 return true; 5589 } 5590 5591 return false; 5592 } 5593 5594 /// Diagnose a declaration whose declarator-id has the given 5595 /// nested-name-specifier. 5596 /// 5597 /// \param SS The nested-name-specifier of the declarator-id. 5598 /// 5599 /// \param DC The declaration context to which the nested-name-specifier 5600 /// resolves. 5601 /// 5602 /// \param Name The name of the entity being declared. 5603 /// 5604 /// \param Loc The location of the name of the entity being declared. 5605 /// 5606 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5607 /// we're declaring an explicit / partial specialization / instantiation. 5608 /// 5609 /// \returns true if we cannot safely recover from this error, false otherwise. 5610 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5611 DeclarationName Name, 5612 SourceLocation Loc, bool IsTemplateId) { 5613 DeclContext *Cur = CurContext; 5614 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5615 Cur = Cur->getParent(); 5616 5617 // If the user provided a superfluous scope specifier that refers back to the 5618 // class in which the entity is already declared, diagnose and ignore it. 5619 // 5620 // class X { 5621 // void X::f(); 5622 // }; 5623 // 5624 // Note, it was once ill-formed to give redundant qualification in all 5625 // contexts, but that rule was removed by DR482. 5626 if (Cur->Equals(DC)) { 5627 if (Cur->isRecord()) { 5628 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5629 : diag::err_member_extra_qualification) 5630 << Name << FixItHint::CreateRemoval(SS.getRange()); 5631 SS.clear(); 5632 } else { 5633 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5634 } 5635 return false; 5636 } 5637 5638 // Check whether the qualifying scope encloses the scope of the original 5639 // declaration. For a template-id, we perform the checks in 5640 // CheckTemplateSpecializationScope. 5641 if (!Cur->Encloses(DC) && !IsTemplateId) { 5642 if (Cur->isRecord()) 5643 Diag(Loc, diag::err_member_qualification) 5644 << Name << SS.getRange(); 5645 else if (isa<TranslationUnitDecl>(DC)) 5646 Diag(Loc, diag::err_invalid_declarator_global_scope) 5647 << Name << SS.getRange(); 5648 else if (isa<FunctionDecl>(Cur)) 5649 Diag(Loc, diag::err_invalid_declarator_in_function) 5650 << Name << SS.getRange(); 5651 else if (isa<BlockDecl>(Cur)) 5652 Diag(Loc, diag::err_invalid_declarator_in_block) 5653 << Name << SS.getRange(); 5654 else 5655 Diag(Loc, diag::err_invalid_declarator_scope) 5656 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5657 5658 return true; 5659 } 5660 5661 if (Cur->isRecord()) { 5662 // Cannot qualify members within a class. 5663 Diag(Loc, diag::err_member_qualification) 5664 << Name << SS.getRange(); 5665 SS.clear(); 5666 5667 // C++ constructors and destructors with incorrect scopes can break 5668 // our AST invariants by having the wrong underlying types. If 5669 // that's the case, then drop this declaration entirely. 5670 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5671 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5672 !Context.hasSameType(Name.getCXXNameType(), 5673 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5674 return true; 5675 5676 return false; 5677 } 5678 5679 // C++11 [dcl.meaning]p1: 5680 // [...] "The nested-name-specifier of the qualified declarator-id shall 5681 // not begin with a decltype-specifer" 5682 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5683 while (SpecLoc.getPrefix()) 5684 SpecLoc = SpecLoc.getPrefix(); 5685 if (dyn_cast_or_null<DecltypeType>( 5686 SpecLoc.getNestedNameSpecifier()->getAsType())) 5687 Diag(Loc, diag::err_decltype_in_declarator) 5688 << SpecLoc.getTypeLoc().getSourceRange(); 5689 5690 return false; 5691 } 5692 5693 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5694 MultiTemplateParamsArg TemplateParamLists) { 5695 // TODO: consider using NameInfo for diagnostic. 5696 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5697 DeclarationName Name = NameInfo.getName(); 5698 5699 // All of these full declarators require an identifier. If it doesn't have 5700 // one, the ParsedFreeStandingDeclSpec action should be used. 5701 if (D.isDecompositionDeclarator()) { 5702 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5703 } else if (!Name) { 5704 if (!D.isInvalidType()) // Reject this if we think it is valid. 5705 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5706 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5707 return nullptr; 5708 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5709 return nullptr; 5710 5711 // The scope passed in may not be a decl scope. Zip up the scope tree until 5712 // we find one that is. 5713 while ((S->getFlags() & Scope::DeclScope) == 0 || 5714 (S->getFlags() & Scope::TemplateParamScope) != 0) 5715 S = S->getParent(); 5716 5717 DeclContext *DC = CurContext; 5718 if (D.getCXXScopeSpec().isInvalid()) 5719 D.setInvalidType(); 5720 else if (D.getCXXScopeSpec().isSet()) { 5721 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5722 UPPC_DeclarationQualifier)) 5723 return nullptr; 5724 5725 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5726 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5727 if (!DC || isa<EnumDecl>(DC)) { 5728 // If we could not compute the declaration context, it's because the 5729 // declaration context is dependent but does not refer to a class, 5730 // class template, or class template partial specialization. Complain 5731 // and return early, to avoid the coming semantic disaster. 5732 Diag(D.getIdentifierLoc(), 5733 diag::err_template_qualified_declarator_no_match) 5734 << D.getCXXScopeSpec().getScopeRep() 5735 << D.getCXXScopeSpec().getRange(); 5736 return nullptr; 5737 } 5738 bool IsDependentContext = DC->isDependentContext(); 5739 5740 if (!IsDependentContext && 5741 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5742 return nullptr; 5743 5744 // If a class is incomplete, do not parse entities inside it. 5745 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5746 Diag(D.getIdentifierLoc(), 5747 diag::err_member_def_undefined_record) 5748 << Name << DC << D.getCXXScopeSpec().getRange(); 5749 return nullptr; 5750 } 5751 if (!D.getDeclSpec().isFriendSpecified()) { 5752 if (diagnoseQualifiedDeclaration( 5753 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5754 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5755 if (DC->isRecord()) 5756 return nullptr; 5757 5758 D.setInvalidType(); 5759 } 5760 } 5761 5762 // Check whether we need to rebuild the type of the given 5763 // declaration in the current instantiation. 5764 if (EnteringContext && IsDependentContext && 5765 TemplateParamLists.size() != 0) { 5766 ContextRAII SavedContext(*this, DC); 5767 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5768 D.setInvalidType(); 5769 } 5770 } 5771 5772 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5773 QualType R = TInfo->getType(); 5774 5775 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5776 UPPC_DeclarationType)) 5777 D.setInvalidType(); 5778 5779 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5780 forRedeclarationInCurContext()); 5781 5782 // See if this is a redefinition of a variable in the same scope. 5783 if (!D.getCXXScopeSpec().isSet()) { 5784 bool IsLinkageLookup = false; 5785 bool CreateBuiltins = false; 5786 5787 // If the declaration we're planning to build will be a function 5788 // or object with linkage, then look for another declaration with 5789 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5790 // 5791 // If the declaration we're planning to build will be declared with 5792 // external linkage in the translation unit, create any builtin with 5793 // the same name. 5794 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5795 /* Do nothing*/; 5796 else if (CurContext->isFunctionOrMethod() && 5797 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5798 R->isFunctionType())) { 5799 IsLinkageLookup = true; 5800 CreateBuiltins = 5801 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5802 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5803 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5804 CreateBuiltins = true; 5805 5806 if (IsLinkageLookup) { 5807 Previous.clear(LookupRedeclarationWithLinkage); 5808 Previous.setRedeclarationKind(ForExternalRedeclaration); 5809 } 5810 5811 LookupName(Previous, S, CreateBuiltins); 5812 } else { // Something like "int foo::x;" 5813 LookupQualifiedName(Previous, DC); 5814 5815 // C++ [dcl.meaning]p1: 5816 // When the declarator-id is qualified, the declaration shall refer to a 5817 // previously declared member of the class or namespace to which the 5818 // qualifier refers (or, in the case of a namespace, of an element of the 5819 // inline namespace set of that namespace (7.3.1)) or to a specialization 5820 // thereof; [...] 5821 // 5822 // Note that we already checked the context above, and that we do not have 5823 // enough information to make sure that Previous contains the declaration 5824 // we want to match. For example, given: 5825 // 5826 // class X { 5827 // void f(); 5828 // void f(float); 5829 // }; 5830 // 5831 // void X::f(int) { } // ill-formed 5832 // 5833 // In this case, Previous will point to the overload set 5834 // containing the two f's declared in X, but neither of them 5835 // matches. 5836 5837 // C++ [dcl.meaning]p1: 5838 // [...] the member shall not merely have been introduced by a 5839 // using-declaration in the scope of the class or namespace nominated by 5840 // the nested-name-specifier of the declarator-id. 5841 RemoveUsingDecls(Previous); 5842 } 5843 5844 if (Previous.isSingleResult() && 5845 Previous.getFoundDecl()->isTemplateParameter()) { 5846 // Maybe we will complain about the shadowed template parameter. 5847 if (!D.isInvalidType()) 5848 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5849 Previous.getFoundDecl()); 5850 5851 // Just pretend that we didn't see the previous declaration. 5852 Previous.clear(); 5853 } 5854 5855 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5856 // Forget that the previous declaration is the injected-class-name. 5857 Previous.clear(); 5858 5859 // In C++, the previous declaration we find might be a tag type 5860 // (class or enum). In this case, the new declaration will hide the 5861 // tag type. Note that this applies to functions, function templates, and 5862 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5863 if (Previous.isSingleTagDecl() && 5864 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5865 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5866 Previous.clear(); 5867 5868 // Check that there are no default arguments other than in the parameters 5869 // of a function declaration (C++ only). 5870 if (getLangOpts().CPlusPlus) 5871 CheckExtraCXXDefaultArguments(D); 5872 5873 NamedDecl *New; 5874 5875 bool AddToScope = true; 5876 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5877 if (TemplateParamLists.size()) { 5878 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5879 return nullptr; 5880 } 5881 5882 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5883 } else if (R->isFunctionType()) { 5884 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5885 TemplateParamLists, 5886 AddToScope); 5887 } else { 5888 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5889 AddToScope); 5890 } 5891 5892 if (!New) 5893 return nullptr; 5894 5895 // If this has an identifier and is not a function template specialization, 5896 // add it to the scope stack. 5897 if (New->getDeclName() && AddToScope) 5898 PushOnScopeChains(New, S); 5899 5900 if (isInOpenMPDeclareTargetContext()) 5901 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5902 5903 return New; 5904 } 5905 5906 /// Helper method to turn variable array types into constant array 5907 /// types in certain situations which would otherwise be errors (for 5908 /// GCC compatibility). 5909 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5910 ASTContext &Context, 5911 bool &SizeIsNegative, 5912 llvm::APSInt &Oversized) { 5913 // This method tries to turn a variable array into a constant 5914 // array even when the size isn't an ICE. This is necessary 5915 // for compatibility with code that depends on gcc's buggy 5916 // constant expression folding, like struct {char x[(int)(char*)2];} 5917 SizeIsNegative = false; 5918 Oversized = 0; 5919 5920 if (T->isDependentType()) 5921 return QualType(); 5922 5923 QualifierCollector Qs; 5924 const Type *Ty = Qs.strip(T); 5925 5926 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5927 QualType Pointee = PTy->getPointeeType(); 5928 QualType FixedType = 5929 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5930 Oversized); 5931 if (FixedType.isNull()) return FixedType; 5932 FixedType = Context.getPointerType(FixedType); 5933 return Qs.apply(Context, FixedType); 5934 } 5935 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5936 QualType Inner = PTy->getInnerType(); 5937 QualType FixedType = 5938 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5939 Oversized); 5940 if (FixedType.isNull()) return FixedType; 5941 FixedType = Context.getParenType(FixedType); 5942 return Qs.apply(Context, FixedType); 5943 } 5944 5945 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5946 if (!VLATy) 5947 return QualType(); 5948 5949 QualType ElemTy = VLATy->getElementType(); 5950 if (ElemTy->isVariablyModifiedType()) { 5951 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5952 SizeIsNegative, Oversized); 5953 if (ElemTy.isNull()) 5954 return QualType(); 5955 } 5956 5957 Expr::EvalResult Result; 5958 if (!VLATy->getSizeExpr() || 5959 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5960 return QualType(); 5961 5962 llvm::APSInt Res = Result.Val.getInt(); 5963 5964 // Check whether the array size is negative. 5965 if (Res.isSigned() && Res.isNegative()) { 5966 SizeIsNegative = true; 5967 return QualType(); 5968 } 5969 5970 // Check whether the array is too large to be addressed. 5971 unsigned ActiveSizeBits = 5972 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5973 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5974 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5975 : Res.getActiveBits(); 5976 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5977 Oversized = Res; 5978 return QualType(); 5979 } 5980 5981 QualType FoldedArrayType = Context.getConstantArrayType( 5982 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5983 return Qs.apply(Context, FoldedArrayType); 5984 } 5985 5986 static void 5987 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5988 SrcTL = SrcTL.getUnqualifiedLoc(); 5989 DstTL = DstTL.getUnqualifiedLoc(); 5990 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5991 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5992 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5993 DstPTL.getPointeeLoc()); 5994 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5995 return; 5996 } 5997 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5998 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5999 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6000 DstPTL.getInnerLoc()); 6001 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6002 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6003 return; 6004 } 6005 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6006 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6007 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6008 TypeLoc DstElemTL = DstATL.getElementLoc(); 6009 if (VariableArrayTypeLoc SrcElemATL = 6010 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6011 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6012 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6013 } else { 6014 DstElemTL.initializeFullCopy(SrcElemTL); 6015 } 6016 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6017 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6018 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6019 } 6020 6021 /// Helper method to turn variable array types into constant array 6022 /// types in certain situations which would otherwise be errors (for 6023 /// GCC compatibility). 6024 static TypeSourceInfo* 6025 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6026 ASTContext &Context, 6027 bool &SizeIsNegative, 6028 llvm::APSInt &Oversized) { 6029 QualType FixedTy 6030 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6031 SizeIsNegative, Oversized); 6032 if (FixedTy.isNull()) 6033 return nullptr; 6034 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6035 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6036 FixedTInfo->getTypeLoc()); 6037 return FixedTInfo; 6038 } 6039 6040 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6041 /// true if we were successful. 6042 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6043 QualType &T, SourceLocation Loc, 6044 unsigned FailedFoldDiagID) { 6045 bool SizeIsNegative; 6046 llvm::APSInt Oversized; 6047 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6048 TInfo, S.Context, SizeIsNegative, Oversized); 6049 if (FixedTInfo) { 6050 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6051 TInfo = FixedTInfo; 6052 T = FixedTInfo->getType(); 6053 return true; 6054 } 6055 6056 if (SizeIsNegative) 6057 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6058 else if (Oversized.getBoolValue()) 6059 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6060 else if (FailedFoldDiagID) 6061 S.Diag(Loc, FailedFoldDiagID); 6062 return false; 6063 } 6064 6065 /// Register the given locally-scoped extern "C" declaration so 6066 /// that it can be found later for redeclarations. We include any extern "C" 6067 /// declaration that is not visible in the translation unit here, not just 6068 /// function-scope declarations. 6069 void 6070 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6071 if (!getLangOpts().CPlusPlus && 6072 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6073 // Don't need to track declarations in the TU in C. 6074 return; 6075 6076 // Note that we have a locally-scoped external with this name. 6077 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6078 } 6079 6080 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6081 // FIXME: We can have multiple results via __attribute__((overloadable)). 6082 auto Result = Context.getExternCContextDecl()->lookup(Name); 6083 return Result.empty() ? nullptr : *Result.begin(); 6084 } 6085 6086 /// Diagnose function specifiers on a declaration of an identifier that 6087 /// does not identify a function. 6088 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6089 // FIXME: We should probably indicate the identifier in question to avoid 6090 // confusion for constructs like "virtual int a(), b;" 6091 if (DS.isVirtualSpecified()) 6092 Diag(DS.getVirtualSpecLoc(), 6093 diag::err_virtual_non_function); 6094 6095 if (DS.hasExplicitSpecifier()) 6096 Diag(DS.getExplicitSpecLoc(), 6097 diag::err_explicit_non_function); 6098 6099 if (DS.isNoreturnSpecified()) 6100 Diag(DS.getNoreturnSpecLoc(), 6101 diag::err_noreturn_non_function); 6102 } 6103 6104 NamedDecl* 6105 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6106 TypeSourceInfo *TInfo, LookupResult &Previous) { 6107 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6108 if (D.getCXXScopeSpec().isSet()) { 6109 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6110 << D.getCXXScopeSpec().getRange(); 6111 D.setInvalidType(); 6112 // Pretend we didn't see the scope specifier. 6113 DC = CurContext; 6114 Previous.clear(); 6115 } 6116 6117 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6118 6119 if (D.getDeclSpec().isInlineSpecified()) 6120 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6121 << getLangOpts().CPlusPlus17; 6122 if (D.getDeclSpec().hasConstexprSpecifier()) 6123 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6124 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6125 6126 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6127 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6128 Diag(D.getName().StartLocation, 6129 diag::err_deduction_guide_invalid_specifier) 6130 << "typedef"; 6131 else 6132 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6133 << D.getName().getSourceRange(); 6134 return nullptr; 6135 } 6136 6137 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6138 if (!NewTD) return nullptr; 6139 6140 // Handle attributes prior to checking for duplicates in MergeVarDecl 6141 ProcessDeclAttributes(S, NewTD, D); 6142 6143 CheckTypedefForVariablyModifiedType(S, NewTD); 6144 6145 bool Redeclaration = D.isRedeclaration(); 6146 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6147 D.setRedeclaration(Redeclaration); 6148 return ND; 6149 } 6150 6151 void 6152 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6153 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6154 // then it shall have block scope. 6155 // Note that variably modified types must be fixed before merging the decl so 6156 // that redeclarations will match. 6157 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6158 QualType T = TInfo->getType(); 6159 if (T->isVariablyModifiedType()) { 6160 setFunctionHasBranchProtectedScope(); 6161 6162 if (S->getFnParent() == nullptr) { 6163 bool SizeIsNegative; 6164 llvm::APSInt Oversized; 6165 TypeSourceInfo *FixedTInfo = 6166 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6167 SizeIsNegative, 6168 Oversized); 6169 if (FixedTInfo) { 6170 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6171 NewTD->setTypeSourceInfo(FixedTInfo); 6172 } else { 6173 if (SizeIsNegative) 6174 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6175 else if (T->isVariableArrayType()) 6176 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6177 else if (Oversized.getBoolValue()) 6178 Diag(NewTD->getLocation(), diag::err_array_too_large) 6179 << Oversized.toString(10); 6180 else 6181 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6182 NewTD->setInvalidDecl(); 6183 } 6184 } 6185 } 6186 } 6187 6188 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6189 /// declares a typedef-name, either using the 'typedef' type specifier or via 6190 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6191 NamedDecl* 6192 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6193 LookupResult &Previous, bool &Redeclaration) { 6194 6195 // Find the shadowed declaration before filtering for scope. 6196 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6197 6198 // Merge the decl with the existing one if appropriate. If the decl is 6199 // in an outer scope, it isn't the same thing. 6200 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6201 /*AllowInlineNamespace*/false); 6202 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6203 if (!Previous.empty()) { 6204 Redeclaration = true; 6205 MergeTypedefNameDecl(S, NewTD, Previous); 6206 } else { 6207 inferGslPointerAttribute(NewTD); 6208 } 6209 6210 if (ShadowedDecl && !Redeclaration) 6211 CheckShadow(NewTD, ShadowedDecl, Previous); 6212 6213 // If this is the C FILE type, notify the AST context. 6214 if (IdentifierInfo *II = NewTD->getIdentifier()) 6215 if (!NewTD->isInvalidDecl() && 6216 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6217 if (II->isStr("FILE")) 6218 Context.setFILEDecl(NewTD); 6219 else if (II->isStr("jmp_buf")) 6220 Context.setjmp_bufDecl(NewTD); 6221 else if (II->isStr("sigjmp_buf")) 6222 Context.setsigjmp_bufDecl(NewTD); 6223 else if (II->isStr("ucontext_t")) 6224 Context.setucontext_tDecl(NewTD); 6225 } 6226 6227 return NewTD; 6228 } 6229 6230 /// Determines whether the given declaration is an out-of-scope 6231 /// previous declaration. 6232 /// 6233 /// This routine should be invoked when name lookup has found a 6234 /// previous declaration (PrevDecl) that is not in the scope where a 6235 /// new declaration by the same name is being introduced. If the new 6236 /// declaration occurs in a local scope, previous declarations with 6237 /// linkage may still be considered previous declarations (C99 6238 /// 6.2.2p4-5, C++ [basic.link]p6). 6239 /// 6240 /// \param PrevDecl the previous declaration found by name 6241 /// lookup 6242 /// 6243 /// \param DC the context in which the new declaration is being 6244 /// declared. 6245 /// 6246 /// \returns true if PrevDecl is an out-of-scope previous declaration 6247 /// for a new delcaration with the same name. 6248 static bool 6249 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6250 ASTContext &Context) { 6251 if (!PrevDecl) 6252 return false; 6253 6254 if (!PrevDecl->hasLinkage()) 6255 return false; 6256 6257 if (Context.getLangOpts().CPlusPlus) { 6258 // C++ [basic.link]p6: 6259 // If there is a visible declaration of an entity with linkage 6260 // having the same name and type, ignoring entities declared 6261 // outside the innermost enclosing namespace scope, the block 6262 // scope declaration declares that same entity and receives the 6263 // linkage of the previous declaration. 6264 DeclContext *OuterContext = DC->getRedeclContext(); 6265 if (!OuterContext->isFunctionOrMethod()) 6266 // This rule only applies to block-scope declarations. 6267 return false; 6268 6269 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6270 if (PrevOuterContext->isRecord()) 6271 // We found a member function: ignore it. 6272 return false; 6273 6274 // Find the innermost enclosing namespace for the new and 6275 // previous declarations. 6276 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6277 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6278 6279 // The previous declaration is in a different namespace, so it 6280 // isn't the same function. 6281 if (!OuterContext->Equals(PrevOuterContext)) 6282 return false; 6283 } 6284 6285 return true; 6286 } 6287 6288 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6289 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6290 if (!SS.isSet()) return; 6291 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6292 } 6293 6294 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6295 QualType type = decl->getType(); 6296 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6297 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6298 // Various kinds of declaration aren't allowed to be __autoreleasing. 6299 unsigned kind = -1U; 6300 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6301 if (var->hasAttr<BlocksAttr>()) 6302 kind = 0; // __block 6303 else if (!var->hasLocalStorage()) 6304 kind = 1; // global 6305 } else if (isa<ObjCIvarDecl>(decl)) { 6306 kind = 3; // ivar 6307 } else if (isa<FieldDecl>(decl)) { 6308 kind = 2; // field 6309 } 6310 6311 if (kind != -1U) { 6312 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6313 << kind; 6314 } 6315 } else if (lifetime == Qualifiers::OCL_None) { 6316 // Try to infer lifetime. 6317 if (!type->isObjCLifetimeType()) 6318 return false; 6319 6320 lifetime = type->getObjCARCImplicitLifetime(); 6321 type = Context.getLifetimeQualifiedType(type, lifetime); 6322 decl->setType(type); 6323 } 6324 6325 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6326 // Thread-local variables cannot have lifetime. 6327 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6328 var->getTLSKind()) { 6329 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6330 << var->getType(); 6331 return true; 6332 } 6333 } 6334 6335 return false; 6336 } 6337 6338 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6339 if (Decl->getType().hasAddressSpace()) 6340 return; 6341 if (Decl->getType()->isDependentType()) 6342 return; 6343 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6344 QualType Type = Var->getType(); 6345 if (Type->isSamplerT() || Type->isVoidType()) 6346 return; 6347 LangAS ImplAS = LangAS::opencl_private; 6348 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6349 Var->hasGlobalStorage()) 6350 ImplAS = LangAS::opencl_global; 6351 // If the original type from a decayed type is an array type and that array 6352 // type has no address space yet, deduce it now. 6353 if (auto DT = dyn_cast<DecayedType>(Type)) { 6354 auto OrigTy = DT->getOriginalType(); 6355 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6356 // Add the address space to the original array type and then propagate 6357 // that to the element type through `getAsArrayType`. 6358 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6359 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6360 // Re-generate the decayed type. 6361 Type = Context.getDecayedType(OrigTy); 6362 } 6363 } 6364 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6365 // Apply any qualifiers (including address space) from the array type to 6366 // the element type. This implements C99 6.7.3p8: "If the specification of 6367 // an array type includes any type qualifiers, the element type is so 6368 // qualified, not the array type." 6369 if (Type->isArrayType()) 6370 Type = QualType(Context.getAsArrayType(Type), 0); 6371 Decl->setType(Type); 6372 } 6373 } 6374 6375 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6376 // Ensure that an auto decl is deduced otherwise the checks below might cache 6377 // the wrong linkage. 6378 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6379 6380 // 'weak' only applies to declarations with external linkage. 6381 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6382 if (!ND.isExternallyVisible()) { 6383 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6384 ND.dropAttr<WeakAttr>(); 6385 } 6386 } 6387 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6388 if (ND.isExternallyVisible()) { 6389 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6390 ND.dropAttr<WeakRefAttr>(); 6391 ND.dropAttr<AliasAttr>(); 6392 } 6393 } 6394 6395 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6396 if (VD->hasInit()) { 6397 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6398 assert(VD->isThisDeclarationADefinition() && 6399 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6400 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6401 VD->dropAttr<AliasAttr>(); 6402 } 6403 } 6404 } 6405 6406 // 'selectany' only applies to externally visible variable declarations. 6407 // It does not apply to functions. 6408 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6409 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6410 S.Diag(Attr->getLocation(), 6411 diag::err_attribute_selectany_non_extern_data); 6412 ND.dropAttr<SelectAnyAttr>(); 6413 } 6414 } 6415 6416 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6417 auto *VD = dyn_cast<VarDecl>(&ND); 6418 bool IsAnonymousNS = false; 6419 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6420 if (VD) { 6421 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6422 while (NS && !IsAnonymousNS) { 6423 IsAnonymousNS = NS->isAnonymousNamespace(); 6424 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6425 } 6426 } 6427 // dll attributes require external linkage. Static locals may have external 6428 // linkage but still cannot be explicitly imported or exported. 6429 // In Microsoft mode, a variable defined in anonymous namespace must have 6430 // external linkage in order to be exported. 6431 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6432 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6433 (!AnonNSInMicrosoftMode && 6434 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6435 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6436 << &ND << Attr; 6437 ND.setInvalidDecl(); 6438 } 6439 } 6440 6441 // Check the attributes on the function type, if any. 6442 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6443 // Don't declare this variable in the second operand of the for-statement; 6444 // GCC miscompiles that by ending its lifetime before evaluating the 6445 // third operand. See gcc.gnu.org/PR86769. 6446 AttributedTypeLoc ATL; 6447 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6448 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6449 TL = ATL.getModifiedLoc()) { 6450 // The [[lifetimebound]] attribute can be applied to the implicit object 6451 // parameter of a non-static member function (other than a ctor or dtor) 6452 // by applying it to the function type. 6453 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6454 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6455 if (!MD || MD->isStatic()) { 6456 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6457 << !MD << A->getRange(); 6458 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6459 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6460 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6461 } 6462 } 6463 } 6464 } 6465 } 6466 6467 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6468 NamedDecl *NewDecl, 6469 bool IsSpecialization, 6470 bool IsDefinition) { 6471 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6472 return; 6473 6474 bool IsTemplate = false; 6475 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6476 OldDecl = OldTD->getTemplatedDecl(); 6477 IsTemplate = true; 6478 if (!IsSpecialization) 6479 IsDefinition = false; 6480 } 6481 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6482 NewDecl = NewTD->getTemplatedDecl(); 6483 IsTemplate = true; 6484 } 6485 6486 if (!OldDecl || !NewDecl) 6487 return; 6488 6489 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6490 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6491 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6492 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6493 6494 // dllimport and dllexport are inheritable attributes so we have to exclude 6495 // inherited attribute instances. 6496 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6497 (NewExportAttr && !NewExportAttr->isInherited()); 6498 6499 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6500 // the only exception being explicit specializations. 6501 // Implicitly generated declarations are also excluded for now because there 6502 // is no other way to switch these to use dllimport or dllexport. 6503 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6504 6505 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6506 // Allow with a warning for free functions and global variables. 6507 bool JustWarn = false; 6508 if (!OldDecl->isCXXClassMember()) { 6509 auto *VD = dyn_cast<VarDecl>(OldDecl); 6510 if (VD && !VD->getDescribedVarTemplate()) 6511 JustWarn = true; 6512 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6513 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6514 JustWarn = true; 6515 } 6516 6517 // We cannot change a declaration that's been used because IR has already 6518 // been emitted. Dllimported functions will still work though (modulo 6519 // address equality) as they can use the thunk. 6520 if (OldDecl->isUsed()) 6521 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6522 JustWarn = false; 6523 6524 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6525 : diag::err_attribute_dll_redeclaration; 6526 S.Diag(NewDecl->getLocation(), DiagID) 6527 << NewDecl 6528 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6529 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6530 if (!JustWarn) { 6531 NewDecl->setInvalidDecl(); 6532 return; 6533 } 6534 } 6535 6536 // A redeclaration is not allowed to drop a dllimport attribute, the only 6537 // exceptions being inline function definitions (except for function 6538 // templates), local extern declarations, qualified friend declarations or 6539 // special MSVC extension: in the last case, the declaration is treated as if 6540 // it were marked dllexport. 6541 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6542 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6543 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6544 // Ignore static data because out-of-line definitions are diagnosed 6545 // separately. 6546 IsStaticDataMember = VD->isStaticDataMember(); 6547 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6548 VarDecl::DeclarationOnly; 6549 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6550 IsInline = FD->isInlined(); 6551 IsQualifiedFriend = FD->getQualifier() && 6552 FD->getFriendObjectKind() == Decl::FOK_Declared; 6553 } 6554 6555 if (OldImportAttr && !HasNewAttr && 6556 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6557 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6558 if (IsMicrosoftABI && IsDefinition) { 6559 S.Diag(NewDecl->getLocation(), 6560 diag::warn_redeclaration_without_import_attribute) 6561 << NewDecl; 6562 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6563 NewDecl->dropAttr<DLLImportAttr>(); 6564 NewDecl->addAttr( 6565 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6566 } else { 6567 S.Diag(NewDecl->getLocation(), 6568 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6569 << NewDecl << OldImportAttr; 6570 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6571 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6572 OldDecl->dropAttr<DLLImportAttr>(); 6573 NewDecl->dropAttr<DLLImportAttr>(); 6574 } 6575 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6576 // In MinGW, seeing a function declared inline drops the dllimport 6577 // attribute. 6578 OldDecl->dropAttr<DLLImportAttr>(); 6579 NewDecl->dropAttr<DLLImportAttr>(); 6580 S.Diag(NewDecl->getLocation(), 6581 diag::warn_dllimport_dropped_from_inline_function) 6582 << NewDecl << OldImportAttr; 6583 } 6584 6585 // A specialization of a class template member function is processed here 6586 // since it's a redeclaration. If the parent class is dllexport, the 6587 // specialization inherits that attribute. This doesn't happen automatically 6588 // since the parent class isn't instantiated until later. 6589 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6590 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6591 !NewImportAttr && !NewExportAttr) { 6592 if (const DLLExportAttr *ParentExportAttr = 6593 MD->getParent()->getAttr<DLLExportAttr>()) { 6594 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6595 NewAttr->setInherited(true); 6596 NewDecl->addAttr(NewAttr); 6597 } 6598 } 6599 } 6600 } 6601 6602 /// Given that we are within the definition of the given function, 6603 /// will that definition behave like C99's 'inline', where the 6604 /// definition is discarded except for optimization purposes? 6605 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6606 // Try to avoid calling GetGVALinkageForFunction. 6607 6608 // All cases of this require the 'inline' keyword. 6609 if (!FD->isInlined()) return false; 6610 6611 // This is only possible in C++ with the gnu_inline attribute. 6612 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6613 return false; 6614 6615 // Okay, go ahead and call the relatively-more-expensive function. 6616 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6617 } 6618 6619 /// Determine whether a variable is extern "C" prior to attaching 6620 /// an initializer. We can't just call isExternC() here, because that 6621 /// will also compute and cache whether the declaration is externally 6622 /// visible, which might change when we attach the initializer. 6623 /// 6624 /// This can only be used if the declaration is known to not be a 6625 /// redeclaration of an internal linkage declaration. 6626 /// 6627 /// For instance: 6628 /// 6629 /// auto x = []{}; 6630 /// 6631 /// Attaching the initializer here makes this declaration not externally 6632 /// visible, because its type has internal linkage. 6633 /// 6634 /// FIXME: This is a hack. 6635 template<typename T> 6636 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6637 if (S.getLangOpts().CPlusPlus) { 6638 // In C++, the overloadable attribute negates the effects of extern "C". 6639 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6640 return false; 6641 6642 // So do CUDA's host/device attributes. 6643 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6644 D->template hasAttr<CUDAHostAttr>())) 6645 return false; 6646 } 6647 return D->isExternC(); 6648 } 6649 6650 static bool shouldConsiderLinkage(const VarDecl *VD) { 6651 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6652 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6653 isa<OMPDeclareMapperDecl>(DC)) 6654 return VD->hasExternalStorage(); 6655 if (DC->isFileContext()) 6656 return true; 6657 if (DC->isRecord()) 6658 return false; 6659 if (isa<RequiresExprBodyDecl>(DC)) 6660 return false; 6661 llvm_unreachable("Unexpected context"); 6662 } 6663 6664 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6665 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6666 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6667 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6668 return true; 6669 if (DC->isRecord()) 6670 return false; 6671 llvm_unreachable("Unexpected context"); 6672 } 6673 6674 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6675 ParsedAttr::Kind Kind) { 6676 // Check decl attributes on the DeclSpec. 6677 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6678 return true; 6679 6680 // Walk the declarator structure, checking decl attributes that were in a type 6681 // position to the decl itself. 6682 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6683 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6684 return true; 6685 } 6686 6687 // Finally, check attributes on the decl itself. 6688 return PD.getAttributes().hasAttribute(Kind); 6689 } 6690 6691 /// Adjust the \c DeclContext for a function or variable that might be a 6692 /// function-local external declaration. 6693 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6694 if (!DC->isFunctionOrMethod()) 6695 return false; 6696 6697 // If this is a local extern function or variable declared within a function 6698 // template, don't add it into the enclosing namespace scope until it is 6699 // instantiated; it might have a dependent type right now. 6700 if (DC->isDependentContext()) 6701 return true; 6702 6703 // C++11 [basic.link]p7: 6704 // When a block scope declaration of an entity with linkage is not found to 6705 // refer to some other declaration, then that entity is a member of the 6706 // innermost enclosing namespace. 6707 // 6708 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6709 // semantically-enclosing namespace, not a lexically-enclosing one. 6710 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6711 DC = DC->getParent(); 6712 return true; 6713 } 6714 6715 /// Returns true if given declaration has external C language linkage. 6716 static bool isDeclExternC(const Decl *D) { 6717 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6718 return FD->isExternC(); 6719 if (const auto *VD = dyn_cast<VarDecl>(D)) 6720 return VD->isExternC(); 6721 6722 llvm_unreachable("Unknown type of decl!"); 6723 } 6724 /// Returns true if there hasn't been any invalid type diagnosed. 6725 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6726 DeclContext *DC, QualType R) { 6727 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6728 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6729 // argument. 6730 if (R->isImageType() || R->isPipeType()) { 6731 Se.Diag(D.getIdentifierLoc(), 6732 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6733 << R; 6734 D.setInvalidType(); 6735 return false; 6736 } 6737 6738 // OpenCL v1.2 s6.9.r: 6739 // The event type cannot be used to declare a program scope variable. 6740 // OpenCL v2.0 s6.9.q: 6741 // The clk_event_t and reserve_id_t types cannot be declared in program 6742 // scope. 6743 if (NULL == S->getParent()) { 6744 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6745 Se.Diag(D.getIdentifierLoc(), 6746 diag::err_invalid_type_for_program_scope_var) 6747 << R; 6748 D.setInvalidType(); 6749 return false; 6750 } 6751 } 6752 6753 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6754 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6755 Se.getLangOpts())) { 6756 QualType NR = R.getCanonicalType(); 6757 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6758 NR->isReferenceType()) { 6759 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6760 NR->isFunctionReferenceType()) { 6761 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer) 6762 << NR->isReferenceType(); 6763 D.setInvalidType(); 6764 return false; 6765 } 6766 NR = NR->getPointeeType(); 6767 } 6768 } 6769 6770 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6771 Se.getLangOpts())) { 6772 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6773 // half array type (unless the cl_khr_fp16 extension is enabled). 6774 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6775 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6776 D.setInvalidType(); 6777 return false; 6778 } 6779 } 6780 6781 // OpenCL v1.2 s6.9.r: 6782 // The event type cannot be used with the __local, __constant and __global 6783 // address space qualifiers. 6784 if (R->isEventT()) { 6785 if (R.getAddressSpace() != LangAS::opencl_private) { 6786 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6787 D.setInvalidType(); 6788 return false; 6789 } 6790 } 6791 6792 // C++ for OpenCL does not allow the thread_local storage qualifier. 6793 // OpenCL C does not support thread_local either, and 6794 // also reject all other thread storage class specifiers. 6795 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6796 if (TSC != TSCS_unspecified) { 6797 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6798 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6799 diag::err_opencl_unknown_type_specifier) 6800 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6801 << DeclSpec::getSpecifierName(TSC) << 1; 6802 D.setInvalidType(); 6803 return false; 6804 } 6805 6806 if (R->isSamplerT()) { 6807 // OpenCL v1.2 s6.9.b p4: 6808 // The sampler type cannot be used with the __local and __global address 6809 // space qualifiers. 6810 if (R.getAddressSpace() == LangAS::opencl_local || 6811 R.getAddressSpace() == LangAS::opencl_global) { 6812 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6813 D.setInvalidType(); 6814 } 6815 6816 // OpenCL v1.2 s6.12.14.1: 6817 // A global sampler must be declared with either the constant address 6818 // space qualifier or with the const qualifier. 6819 if (DC->isTranslationUnit() && 6820 !(R.getAddressSpace() == LangAS::opencl_constant || 6821 R.isConstQualified())) { 6822 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6823 D.setInvalidType(); 6824 } 6825 if (D.isInvalidType()) 6826 return false; 6827 } 6828 return true; 6829 } 6830 6831 NamedDecl *Sema::ActOnVariableDeclarator( 6832 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6833 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6834 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6835 QualType R = TInfo->getType(); 6836 DeclarationName Name = GetNameForDeclarator(D).getName(); 6837 6838 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6839 6840 if (D.isDecompositionDeclarator()) { 6841 // Take the name of the first declarator as our name for diagnostic 6842 // purposes. 6843 auto &Decomp = D.getDecompositionDeclarator(); 6844 if (!Decomp.bindings().empty()) { 6845 II = Decomp.bindings()[0].Name; 6846 Name = II; 6847 } 6848 } else if (!II) { 6849 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6850 return nullptr; 6851 } 6852 6853 6854 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6855 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6856 6857 // dllimport globals without explicit storage class are treated as extern. We 6858 // have to change the storage class this early to get the right DeclContext. 6859 if (SC == SC_None && !DC->isRecord() && 6860 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6861 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6862 SC = SC_Extern; 6863 6864 DeclContext *OriginalDC = DC; 6865 bool IsLocalExternDecl = SC == SC_Extern && 6866 adjustContextForLocalExternDecl(DC); 6867 6868 if (SCSpec == DeclSpec::SCS_mutable) { 6869 // mutable can only appear on non-static class members, so it's always 6870 // an error here 6871 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6872 D.setInvalidType(); 6873 SC = SC_None; 6874 } 6875 6876 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6877 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6878 D.getDeclSpec().getStorageClassSpecLoc())) { 6879 // In C++11, the 'register' storage class specifier is deprecated. 6880 // Suppress the warning in system macros, it's used in macros in some 6881 // popular C system headers, such as in glibc's htonl() macro. 6882 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6883 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6884 : diag::warn_deprecated_register) 6885 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6886 } 6887 6888 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6889 6890 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6891 // C99 6.9p2: The storage-class specifiers auto and register shall not 6892 // appear in the declaration specifiers in an external declaration. 6893 // Global Register+Asm is a GNU extension we support. 6894 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6895 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6896 D.setInvalidType(); 6897 } 6898 } 6899 6900 // If this variable has a variable-modified type and an initializer, try to 6901 // fold to a constant-sized type. This is otherwise invalid. 6902 if (D.hasInitializer() && R->isVariablyModifiedType()) 6903 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6904 /*DiagID=*/0); 6905 6906 bool IsMemberSpecialization = false; 6907 bool IsVariableTemplateSpecialization = false; 6908 bool IsPartialSpecialization = false; 6909 bool IsVariableTemplate = false; 6910 VarDecl *NewVD = nullptr; 6911 VarTemplateDecl *NewTemplate = nullptr; 6912 TemplateParameterList *TemplateParams = nullptr; 6913 if (!getLangOpts().CPlusPlus) { 6914 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6915 II, R, TInfo, SC); 6916 6917 if (R->getContainedDeducedType()) 6918 ParsingInitForAutoVars.insert(NewVD); 6919 6920 if (D.isInvalidType()) 6921 NewVD->setInvalidDecl(); 6922 6923 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6924 NewVD->hasLocalStorage()) 6925 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6926 NTCUC_AutoVar, NTCUK_Destruct); 6927 } else { 6928 bool Invalid = false; 6929 6930 if (DC->isRecord() && !CurContext->isRecord()) { 6931 // This is an out-of-line definition of a static data member. 6932 switch (SC) { 6933 case SC_None: 6934 break; 6935 case SC_Static: 6936 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6937 diag::err_static_out_of_line) 6938 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6939 break; 6940 case SC_Auto: 6941 case SC_Register: 6942 case SC_Extern: 6943 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6944 // to names of variables declared in a block or to function parameters. 6945 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6946 // of class members 6947 6948 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6949 diag::err_storage_class_for_static_member) 6950 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6951 break; 6952 case SC_PrivateExtern: 6953 llvm_unreachable("C storage class in c++!"); 6954 } 6955 } 6956 6957 if (SC == SC_Static && CurContext->isRecord()) { 6958 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6959 // Walk up the enclosing DeclContexts to check for any that are 6960 // incompatible with static data members. 6961 const DeclContext *FunctionOrMethod = nullptr; 6962 const CXXRecordDecl *AnonStruct = nullptr; 6963 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6964 if (Ctxt->isFunctionOrMethod()) { 6965 FunctionOrMethod = Ctxt; 6966 break; 6967 } 6968 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6969 if (ParentDecl && !ParentDecl->getDeclName()) { 6970 AnonStruct = ParentDecl; 6971 break; 6972 } 6973 } 6974 if (FunctionOrMethod) { 6975 // C++ [class.static.data]p5: A local class shall not have static data 6976 // members. 6977 Diag(D.getIdentifierLoc(), 6978 diag::err_static_data_member_not_allowed_in_local_class) 6979 << Name << RD->getDeclName() << RD->getTagKind(); 6980 } else if (AnonStruct) { 6981 // C++ [class.static.data]p4: Unnamed classes and classes contained 6982 // directly or indirectly within unnamed classes shall not contain 6983 // static data members. 6984 Diag(D.getIdentifierLoc(), 6985 diag::err_static_data_member_not_allowed_in_anon_struct) 6986 << Name << AnonStruct->getTagKind(); 6987 Invalid = true; 6988 } else if (RD->isUnion()) { 6989 // C++98 [class.union]p1: If a union contains a static data member, 6990 // the program is ill-formed. C++11 drops this restriction. 6991 Diag(D.getIdentifierLoc(), 6992 getLangOpts().CPlusPlus11 6993 ? diag::warn_cxx98_compat_static_data_member_in_union 6994 : diag::ext_static_data_member_in_union) << Name; 6995 } 6996 } 6997 } 6998 6999 // Match up the template parameter lists with the scope specifier, then 7000 // determine whether we have a template or a template specialization. 7001 bool InvalidScope = false; 7002 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7003 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7004 D.getCXXScopeSpec(), 7005 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7006 ? D.getName().TemplateId 7007 : nullptr, 7008 TemplateParamLists, 7009 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7010 Invalid |= InvalidScope; 7011 7012 if (TemplateParams) { 7013 if (!TemplateParams->size() && 7014 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7015 // There is an extraneous 'template<>' for this variable. Complain 7016 // about it, but allow the declaration of the variable. 7017 Diag(TemplateParams->getTemplateLoc(), 7018 diag::err_template_variable_noparams) 7019 << II 7020 << SourceRange(TemplateParams->getTemplateLoc(), 7021 TemplateParams->getRAngleLoc()); 7022 TemplateParams = nullptr; 7023 } else { 7024 // Check that we can declare a template here. 7025 if (CheckTemplateDeclScope(S, TemplateParams)) 7026 return nullptr; 7027 7028 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7029 // This is an explicit specialization or a partial specialization. 7030 IsVariableTemplateSpecialization = true; 7031 IsPartialSpecialization = TemplateParams->size() > 0; 7032 } else { // if (TemplateParams->size() > 0) 7033 // This is a template declaration. 7034 IsVariableTemplate = true; 7035 7036 // Only C++1y supports variable templates (N3651). 7037 Diag(D.getIdentifierLoc(), 7038 getLangOpts().CPlusPlus14 7039 ? diag::warn_cxx11_compat_variable_template 7040 : diag::ext_variable_template); 7041 } 7042 } 7043 } else { 7044 // Check that we can declare a member specialization here. 7045 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7046 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7047 return nullptr; 7048 assert((Invalid || 7049 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7050 "should have a 'template<>' for this decl"); 7051 } 7052 7053 if (IsVariableTemplateSpecialization) { 7054 SourceLocation TemplateKWLoc = 7055 TemplateParamLists.size() > 0 7056 ? TemplateParamLists[0]->getTemplateLoc() 7057 : SourceLocation(); 7058 DeclResult Res = ActOnVarTemplateSpecialization( 7059 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7060 IsPartialSpecialization); 7061 if (Res.isInvalid()) 7062 return nullptr; 7063 NewVD = cast<VarDecl>(Res.get()); 7064 AddToScope = false; 7065 } else if (D.isDecompositionDeclarator()) { 7066 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7067 D.getIdentifierLoc(), R, TInfo, SC, 7068 Bindings); 7069 } else 7070 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7071 D.getIdentifierLoc(), II, R, TInfo, SC); 7072 7073 // If this is supposed to be a variable template, create it as such. 7074 if (IsVariableTemplate) { 7075 NewTemplate = 7076 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7077 TemplateParams, NewVD); 7078 NewVD->setDescribedVarTemplate(NewTemplate); 7079 } 7080 7081 // If this decl has an auto type in need of deduction, make a note of the 7082 // Decl so we can diagnose uses of it in its own initializer. 7083 if (R->getContainedDeducedType()) 7084 ParsingInitForAutoVars.insert(NewVD); 7085 7086 if (D.isInvalidType() || Invalid) { 7087 NewVD->setInvalidDecl(); 7088 if (NewTemplate) 7089 NewTemplate->setInvalidDecl(); 7090 } 7091 7092 SetNestedNameSpecifier(*this, NewVD, D); 7093 7094 // If we have any template parameter lists that don't directly belong to 7095 // the variable (matching the scope specifier), store them. 7096 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7097 if (TemplateParamLists.size() > VDTemplateParamLists) 7098 NewVD->setTemplateParameterListsInfo( 7099 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7100 } 7101 7102 if (D.getDeclSpec().isInlineSpecified()) { 7103 if (!getLangOpts().CPlusPlus) { 7104 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7105 << 0; 7106 } else if (CurContext->isFunctionOrMethod()) { 7107 // 'inline' is not allowed on block scope variable declaration. 7108 Diag(D.getDeclSpec().getInlineSpecLoc(), 7109 diag::err_inline_declaration_block_scope) << Name 7110 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7111 } else { 7112 Diag(D.getDeclSpec().getInlineSpecLoc(), 7113 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7114 : diag::ext_inline_variable); 7115 NewVD->setInlineSpecified(); 7116 } 7117 } 7118 7119 // Set the lexical context. If the declarator has a C++ scope specifier, the 7120 // lexical context will be different from the semantic context. 7121 NewVD->setLexicalDeclContext(CurContext); 7122 if (NewTemplate) 7123 NewTemplate->setLexicalDeclContext(CurContext); 7124 7125 if (IsLocalExternDecl) { 7126 if (D.isDecompositionDeclarator()) 7127 for (auto *B : Bindings) 7128 B->setLocalExternDecl(); 7129 else 7130 NewVD->setLocalExternDecl(); 7131 } 7132 7133 bool EmitTLSUnsupportedError = false; 7134 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7135 // C++11 [dcl.stc]p4: 7136 // When thread_local is applied to a variable of block scope the 7137 // storage-class-specifier static is implied if it does not appear 7138 // explicitly. 7139 // Core issue: 'static' is not implied if the variable is declared 7140 // 'extern'. 7141 if (NewVD->hasLocalStorage() && 7142 (SCSpec != DeclSpec::SCS_unspecified || 7143 TSCS != DeclSpec::TSCS_thread_local || 7144 !DC->isFunctionOrMethod())) 7145 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7146 diag::err_thread_non_global) 7147 << DeclSpec::getSpecifierName(TSCS); 7148 else if (!Context.getTargetInfo().isTLSSupported()) { 7149 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7150 getLangOpts().SYCLIsDevice) { 7151 // Postpone error emission until we've collected attributes required to 7152 // figure out whether it's a host or device variable and whether the 7153 // error should be ignored. 7154 EmitTLSUnsupportedError = true; 7155 // We still need to mark the variable as TLS so it shows up in AST with 7156 // proper storage class for other tools to use even if we're not going 7157 // to emit any code for it. 7158 NewVD->setTSCSpec(TSCS); 7159 } else 7160 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7161 diag::err_thread_unsupported); 7162 } else 7163 NewVD->setTSCSpec(TSCS); 7164 } 7165 7166 switch (D.getDeclSpec().getConstexprSpecifier()) { 7167 case ConstexprSpecKind::Unspecified: 7168 break; 7169 7170 case ConstexprSpecKind::Consteval: 7171 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7172 diag::err_constexpr_wrong_decl_kind) 7173 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7174 LLVM_FALLTHROUGH; 7175 7176 case ConstexprSpecKind::Constexpr: 7177 NewVD->setConstexpr(true); 7178 MaybeAddCUDAConstantAttr(NewVD); 7179 // C++1z [dcl.spec.constexpr]p1: 7180 // A static data member declared with the constexpr specifier is 7181 // implicitly an inline variable. 7182 if (NewVD->isStaticDataMember() && 7183 (getLangOpts().CPlusPlus17 || 7184 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7185 NewVD->setImplicitlyInline(); 7186 break; 7187 7188 case ConstexprSpecKind::Constinit: 7189 if (!NewVD->hasGlobalStorage()) 7190 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7191 diag::err_constinit_local_variable); 7192 else 7193 NewVD->addAttr(ConstInitAttr::Create( 7194 Context, D.getDeclSpec().getConstexprSpecLoc(), 7195 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7196 break; 7197 } 7198 7199 // C99 6.7.4p3 7200 // An inline definition of a function with external linkage shall 7201 // not contain a definition of a modifiable object with static or 7202 // thread storage duration... 7203 // We only apply this when the function is required to be defined 7204 // elsewhere, i.e. when the function is not 'extern inline'. Note 7205 // that a local variable with thread storage duration still has to 7206 // be marked 'static'. Also note that it's possible to get these 7207 // semantics in C++ using __attribute__((gnu_inline)). 7208 if (SC == SC_Static && S->getFnParent() != nullptr && 7209 !NewVD->getType().isConstQualified()) { 7210 FunctionDecl *CurFD = getCurFunctionDecl(); 7211 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7212 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7213 diag::warn_static_local_in_extern_inline); 7214 MaybeSuggestAddingStaticToDecl(CurFD); 7215 } 7216 } 7217 7218 if (D.getDeclSpec().isModulePrivateSpecified()) { 7219 if (IsVariableTemplateSpecialization) 7220 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7221 << (IsPartialSpecialization ? 1 : 0) 7222 << FixItHint::CreateRemoval( 7223 D.getDeclSpec().getModulePrivateSpecLoc()); 7224 else if (IsMemberSpecialization) 7225 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7226 << 2 7227 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7228 else if (NewVD->hasLocalStorage()) 7229 Diag(NewVD->getLocation(), diag::err_module_private_local) 7230 << 0 << NewVD 7231 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7232 << FixItHint::CreateRemoval( 7233 D.getDeclSpec().getModulePrivateSpecLoc()); 7234 else { 7235 NewVD->setModulePrivate(); 7236 if (NewTemplate) 7237 NewTemplate->setModulePrivate(); 7238 for (auto *B : Bindings) 7239 B->setModulePrivate(); 7240 } 7241 } 7242 7243 if (getLangOpts().OpenCL) { 7244 7245 deduceOpenCLAddressSpace(NewVD); 7246 7247 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7248 } 7249 7250 // Handle attributes prior to checking for duplicates in MergeVarDecl 7251 ProcessDeclAttributes(S, NewVD, D); 7252 7253 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7254 getLangOpts().SYCLIsDevice) { 7255 if (EmitTLSUnsupportedError && 7256 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7257 (getLangOpts().OpenMPIsDevice && 7258 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7259 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7260 diag::err_thread_unsupported); 7261 7262 if (EmitTLSUnsupportedError && 7263 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7264 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7265 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7266 // storage [duration]." 7267 if (SC == SC_None && S->getFnParent() != nullptr && 7268 (NewVD->hasAttr<CUDASharedAttr>() || 7269 NewVD->hasAttr<CUDAConstantAttr>())) { 7270 NewVD->setStorageClass(SC_Static); 7271 } 7272 } 7273 7274 // Ensure that dllimport globals without explicit storage class are treated as 7275 // extern. The storage class is set above using parsed attributes. Now we can 7276 // check the VarDecl itself. 7277 assert(!NewVD->hasAttr<DLLImportAttr>() || 7278 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7279 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7280 7281 // In auto-retain/release, infer strong retension for variables of 7282 // retainable type. 7283 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7284 NewVD->setInvalidDecl(); 7285 7286 // Handle GNU asm-label extension (encoded as an attribute). 7287 if (Expr *E = (Expr*)D.getAsmLabel()) { 7288 // The parser guarantees this is a string. 7289 StringLiteral *SE = cast<StringLiteral>(E); 7290 StringRef Label = SE->getString(); 7291 if (S->getFnParent() != nullptr) { 7292 switch (SC) { 7293 case SC_None: 7294 case SC_Auto: 7295 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7296 break; 7297 case SC_Register: 7298 // Local Named register 7299 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7300 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7301 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7302 break; 7303 case SC_Static: 7304 case SC_Extern: 7305 case SC_PrivateExtern: 7306 break; 7307 } 7308 } else if (SC == SC_Register) { 7309 // Global Named register 7310 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7311 const auto &TI = Context.getTargetInfo(); 7312 bool HasSizeMismatch; 7313 7314 if (!TI.isValidGCCRegisterName(Label)) 7315 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7316 else if (!TI.validateGlobalRegisterVariable(Label, 7317 Context.getTypeSize(R), 7318 HasSizeMismatch)) 7319 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7320 else if (HasSizeMismatch) 7321 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7322 } 7323 7324 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7325 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7326 NewVD->setInvalidDecl(true); 7327 } 7328 } 7329 7330 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7331 /*IsLiteralLabel=*/true, 7332 SE->getStrTokenLoc(0))); 7333 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7334 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7335 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7336 if (I != ExtnameUndeclaredIdentifiers.end()) { 7337 if (isDeclExternC(NewVD)) { 7338 NewVD->addAttr(I->second); 7339 ExtnameUndeclaredIdentifiers.erase(I); 7340 } else 7341 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7342 << /*Variable*/1 << NewVD; 7343 } 7344 } 7345 7346 // Find the shadowed declaration before filtering for scope. 7347 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7348 ? getShadowedDeclaration(NewVD, Previous) 7349 : nullptr; 7350 7351 // Don't consider existing declarations that are in a different 7352 // scope and are out-of-semantic-context declarations (if the new 7353 // declaration has linkage). 7354 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7355 D.getCXXScopeSpec().isNotEmpty() || 7356 IsMemberSpecialization || 7357 IsVariableTemplateSpecialization); 7358 7359 // Check whether the previous declaration is in the same block scope. This 7360 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7361 if (getLangOpts().CPlusPlus && 7362 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7363 NewVD->setPreviousDeclInSameBlockScope( 7364 Previous.isSingleResult() && !Previous.isShadowed() && 7365 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7366 7367 if (!getLangOpts().CPlusPlus) { 7368 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7369 } else { 7370 // If this is an explicit specialization of a static data member, check it. 7371 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7372 CheckMemberSpecialization(NewVD, Previous)) 7373 NewVD->setInvalidDecl(); 7374 7375 // Merge the decl with the existing one if appropriate. 7376 if (!Previous.empty()) { 7377 if (Previous.isSingleResult() && 7378 isa<FieldDecl>(Previous.getFoundDecl()) && 7379 D.getCXXScopeSpec().isSet()) { 7380 // The user tried to define a non-static data member 7381 // out-of-line (C++ [dcl.meaning]p1). 7382 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7383 << D.getCXXScopeSpec().getRange(); 7384 Previous.clear(); 7385 NewVD->setInvalidDecl(); 7386 } 7387 } else if (D.getCXXScopeSpec().isSet()) { 7388 // No previous declaration in the qualifying scope. 7389 Diag(D.getIdentifierLoc(), diag::err_no_member) 7390 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7391 << D.getCXXScopeSpec().getRange(); 7392 NewVD->setInvalidDecl(); 7393 } 7394 7395 if (!IsVariableTemplateSpecialization) 7396 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7397 7398 if (NewTemplate) { 7399 VarTemplateDecl *PrevVarTemplate = 7400 NewVD->getPreviousDecl() 7401 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7402 : nullptr; 7403 7404 // Check the template parameter list of this declaration, possibly 7405 // merging in the template parameter list from the previous variable 7406 // template declaration. 7407 if (CheckTemplateParameterList( 7408 TemplateParams, 7409 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7410 : nullptr, 7411 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7412 DC->isDependentContext()) 7413 ? TPC_ClassTemplateMember 7414 : TPC_VarTemplate)) 7415 NewVD->setInvalidDecl(); 7416 7417 // If we are providing an explicit specialization of a static variable 7418 // template, make a note of that. 7419 if (PrevVarTemplate && 7420 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7421 PrevVarTemplate->setMemberSpecialization(); 7422 } 7423 } 7424 7425 // Diagnose shadowed variables iff this isn't a redeclaration. 7426 if (ShadowedDecl && !D.isRedeclaration()) 7427 CheckShadow(NewVD, ShadowedDecl, Previous); 7428 7429 ProcessPragmaWeak(S, NewVD); 7430 7431 // If this is the first declaration of an extern C variable, update 7432 // the map of such variables. 7433 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7434 isIncompleteDeclExternC(*this, NewVD)) 7435 RegisterLocallyScopedExternCDecl(NewVD, S); 7436 7437 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7438 MangleNumberingContext *MCtx; 7439 Decl *ManglingContextDecl; 7440 std::tie(MCtx, ManglingContextDecl) = 7441 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7442 if (MCtx) { 7443 Context.setManglingNumber( 7444 NewVD, MCtx->getManglingNumber( 7445 NewVD, getMSManglingNumber(getLangOpts(), S))); 7446 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7447 } 7448 } 7449 7450 // Special handling of variable named 'main'. 7451 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7452 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7453 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7454 7455 // C++ [basic.start.main]p3 7456 // A program that declares a variable main at global scope is ill-formed. 7457 if (getLangOpts().CPlusPlus) 7458 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7459 7460 // In C, and external-linkage variable named main results in undefined 7461 // behavior. 7462 else if (NewVD->hasExternalFormalLinkage()) 7463 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7464 } 7465 7466 if (D.isRedeclaration() && !Previous.empty()) { 7467 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7468 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7469 D.isFunctionDefinition()); 7470 } 7471 7472 if (NewTemplate) { 7473 if (NewVD->isInvalidDecl()) 7474 NewTemplate->setInvalidDecl(); 7475 ActOnDocumentableDecl(NewTemplate); 7476 return NewTemplate; 7477 } 7478 7479 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7480 CompleteMemberSpecialization(NewVD, Previous); 7481 7482 return NewVD; 7483 } 7484 7485 /// Enum describing the %select options in diag::warn_decl_shadow. 7486 enum ShadowedDeclKind { 7487 SDK_Local, 7488 SDK_Global, 7489 SDK_StaticMember, 7490 SDK_Field, 7491 SDK_Typedef, 7492 SDK_Using, 7493 SDK_StructuredBinding 7494 }; 7495 7496 /// Determine what kind of declaration we're shadowing. 7497 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7498 const DeclContext *OldDC) { 7499 if (isa<TypeAliasDecl>(ShadowedDecl)) 7500 return SDK_Using; 7501 else if (isa<TypedefDecl>(ShadowedDecl)) 7502 return SDK_Typedef; 7503 else if (isa<BindingDecl>(ShadowedDecl)) 7504 return SDK_StructuredBinding; 7505 else if (isa<RecordDecl>(OldDC)) 7506 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7507 7508 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7509 } 7510 7511 /// Return the location of the capture if the given lambda captures the given 7512 /// variable \p VD, or an invalid source location otherwise. 7513 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7514 const VarDecl *VD) { 7515 for (const Capture &Capture : LSI->Captures) { 7516 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7517 return Capture.getLocation(); 7518 } 7519 return SourceLocation(); 7520 } 7521 7522 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7523 const LookupResult &R) { 7524 // Only diagnose if we're shadowing an unambiguous field or variable. 7525 if (R.getResultKind() != LookupResult::Found) 7526 return false; 7527 7528 // Return false if warning is ignored. 7529 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7530 } 7531 7532 /// Return the declaration shadowed by the given variable \p D, or null 7533 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7534 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7535 const LookupResult &R) { 7536 if (!shouldWarnIfShadowedDecl(Diags, R)) 7537 return nullptr; 7538 7539 // Don't diagnose declarations at file scope. 7540 if (D->hasGlobalStorage()) 7541 return nullptr; 7542 7543 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7544 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7545 : nullptr; 7546 } 7547 7548 /// Return the declaration shadowed by the given typedef \p D, or null 7549 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7550 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7551 const LookupResult &R) { 7552 // Don't warn if typedef declaration is part of a class 7553 if (D->getDeclContext()->isRecord()) 7554 return nullptr; 7555 7556 if (!shouldWarnIfShadowedDecl(Diags, R)) 7557 return nullptr; 7558 7559 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7560 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7561 } 7562 7563 /// Return the declaration shadowed by the given variable \p D, or null 7564 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7565 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7566 const LookupResult &R) { 7567 if (!shouldWarnIfShadowedDecl(Diags, R)) 7568 return nullptr; 7569 7570 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7571 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7572 : nullptr; 7573 } 7574 7575 /// Diagnose variable or built-in function shadowing. Implements 7576 /// -Wshadow. 7577 /// 7578 /// This method is called whenever a VarDecl is added to a "useful" 7579 /// scope. 7580 /// 7581 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7582 /// \param R the lookup of the name 7583 /// 7584 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7585 const LookupResult &R) { 7586 DeclContext *NewDC = D->getDeclContext(); 7587 7588 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7589 // Fields are not shadowed by variables in C++ static methods. 7590 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7591 if (MD->isStatic()) 7592 return; 7593 7594 // Fields shadowed by constructor parameters are a special case. Usually 7595 // the constructor initializes the field with the parameter. 7596 if (isa<CXXConstructorDecl>(NewDC)) 7597 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7598 // Remember that this was shadowed so we can either warn about its 7599 // modification or its existence depending on warning settings. 7600 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7601 return; 7602 } 7603 } 7604 7605 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7606 if (shadowedVar->isExternC()) { 7607 // For shadowing external vars, make sure that we point to the global 7608 // declaration, not a locally scoped extern declaration. 7609 for (auto I : shadowedVar->redecls()) 7610 if (I->isFileVarDecl()) { 7611 ShadowedDecl = I; 7612 break; 7613 } 7614 } 7615 7616 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7617 7618 unsigned WarningDiag = diag::warn_decl_shadow; 7619 SourceLocation CaptureLoc; 7620 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7621 isa<CXXMethodDecl>(NewDC)) { 7622 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7623 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7624 if (RD->getLambdaCaptureDefault() == LCD_None) { 7625 // Try to avoid warnings for lambdas with an explicit capture list. 7626 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7627 // Warn only when the lambda captures the shadowed decl explicitly. 7628 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7629 if (CaptureLoc.isInvalid()) 7630 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7631 } else { 7632 // Remember that this was shadowed so we can avoid the warning if the 7633 // shadowed decl isn't captured and the warning settings allow it. 7634 cast<LambdaScopeInfo>(getCurFunction()) 7635 ->ShadowingDecls.push_back( 7636 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7637 return; 7638 } 7639 } 7640 7641 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7642 // A variable can't shadow a local variable in an enclosing scope, if 7643 // they are separated by a non-capturing declaration context. 7644 for (DeclContext *ParentDC = NewDC; 7645 ParentDC && !ParentDC->Equals(OldDC); 7646 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7647 // Only block literals, captured statements, and lambda expressions 7648 // can capture; other scopes don't. 7649 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7650 !isLambdaCallOperator(ParentDC)) { 7651 return; 7652 } 7653 } 7654 } 7655 } 7656 } 7657 7658 // Only warn about certain kinds of shadowing for class members. 7659 if (NewDC && NewDC->isRecord()) { 7660 // In particular, don't warn about shadowing non-class members. 7661 if (!OldDC->isRecord()) 7662 return; 7663 7664 // TODO: should we warn about static data members shadowing 7665 // static data members from base classes? 7666 7667 // TODO: don't diagnose for inaccessible shadowed members. 7668 // This is hard to do perfectly because we might friend the 7669 // shadowing context, but that's just a false negative. 7670 } 7671 7672 7673 DeclarationName Name = R.getLookupName(); 7674 7675 // Emit warning and note. 7676 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7677 return; 7678 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7679 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7680 if (!CaptureLoc.isInvalid()) 7681 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7682 << Name << /*explicitly*/ 1; 7683 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7684 } 7685 7686 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7687 /// when these variables are captured by the lambda. 7688 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7689 for (const auto &Shadow : LSI->ShadowingDecls) { 7690 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7691 // Try to avoid the warning when the shadowed decl isn't captured. 7692 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7693 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7694 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7695 ? diag::warn_decl_shadow_uncaptured_local 7696 : diag::warn_decl_shadow) 7697 << Shadow.VD->getDeclName() 7698 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7699 if (!CaptureLoc.isInvalid()) 7700 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7701 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7702 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7703 } 7704 } 7705 7706 /// Check -Wshadow without the advantage of a previous lookup. 7707 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7708 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7709 return; 7710 7711 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7712 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7713 LookupName(R, S); 7714 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7715 CheckShadow(D, ShadowedDecl, R); 7716 } 7717 7718 /// Check if 'E', which is an expression that is about to be modified, refers 7719 /// to a constructor parameter that shadows a field. 7720 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7721 // Quickly ignore expressions that can't be shadowing ctor parameters. 7722 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7723 return; 7724 E = E->IgnoreParenImpCasts(); 7725 auto *DRE = dyn_cast<DeclRefExpr>(E); 7726 if (!DRE) 7727 return; 7728 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7729 auto I = ShadowingDecls.find(D); 7730 if (I == ShadowingDecls.end()) 7731 return; 7732 const NamedDecl *ShadowedDecl = I->second; 7733 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7734 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7735 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7736 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7737 7738 // Avoid issuing multiple warnings about the same decl. 7739 ShadowingDecls.erase(I); 7740 } 7741 7742 /// Check for conflict between this global or extern "C" declaration and 7743 /// previous global or extern "C" declarations. This is only used in C++. 7744 template<typename T> 7745 static bool checkGlobalOrExternCConflict( 7746 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7747 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7748 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7749 7750 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7751 // The common case: this global doesn't conflict with any extern "C" 7752 // declaration. 7753 return false; 7754 } 7755 7756 if (Prev) { 7757 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7758 // Both the old and new declarations have C language linkage. This is a 7759 // redeclaration. 7760 Previous.clear(); 7761 Previous.addDecl(Prev); 7762 return true; 7763 } 7764 7765 // This is a global, non-extern "C" declaration, and there is a previous 7766 // non-global extern "C" declaration. Diagnose if this is a variable 7767 // declaration. 7768 if (!isa<VarDecl>(ND)) 7769 return false; 7770 } else { 7771 // The declaration is extern "C". Check for any declaration in the 7772 // translation unit which might conflict. 7773 if (IsGlobal) { 7774 // We have already performed the lookup into the translation unit. 7775 IsGlobal = false; 7776 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7777 I != E; ++I) { 7778 if (isa<VarDecl>(*I)) { 7779 Prev = *I; 7780 break; 7781 } 7782 } 7783 } else { 7784 DeclContext::lookup_result R = 7785 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7786 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7787 I != E; ++I) { 7788 if (isa<VarDecl>(*I)) { 7789 Prev = *I; 7790 break; 7791 } 7792 // FIXME: If we have any other entity with this name in global scope, 7793 // the declaration is ill-formed, but that is a defect: it breaks the 7794 // 'stat' hack, for instance. Only variables can have mangled name 7795 // clashes with extern "C" declarations, so only they deserve a 7796 // diagnostic. 7797 } 7798 } 7799 7800 if (!Prev) 7801 return false; 7802 } 7803 7804 // Use the first declaration's location to ensure we point at something which 7805 // is lexically inside an extern "C" linkage-spec. 7806 assert(Prev && "should have found a previous declaration to diagnose"); 7807 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7808 Prev = FD->getFirstDecl(); 7809 else 7810 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7811 7812 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7813 << IsGlobal << ND; 7814 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7815 << IsGlobal; 7816 return false; 7817 } 7818 7819 /// Apply special rules for handling extern "C" declarations. Returns \c true 7820 /// if we have found that this is a redeclaration of some prior entity. 7821 /// 7822 /// Per C++ [dcl.link]p6: 7823 /// Two declarations [for a function or variable] with C language linkage 7824 /// with the same name that appear in different scopes refer to the same 7825 /// [entity]. An entity with C language linkage shall not be declared with 7826 /// the same name as an entity in global scope. 7827 template<typename T> 7828 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7829 LookupResult &Previous) { 7830 if (!S.getLangOpts().CPlusPlus) { 7831 // In C, when declaring a global variable, look for a corresponding 'extern' 7832 // variable declared in function scope. We don't need this in C++, because 7833 // we find local extern decls in the surrounding file-scope DeclContext. 7834 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7835 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7836 Previous.clear(); 7837 Previous.addDecl(Prev); 7838 return true; 7839 } 7840 } 7841 return false; 7842 } 7843 7844 // A declaration in the translation unit can conflict with an extern "C" 7845 // declaration. 7846 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7847 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7848 7849 // An extern "C" declaration can conflict with a declaration in the 7850 // translation unit or can be a redeclaration of an extern "C" declaration 7851 // in another scope. 7852 if (isIncompleteDeclExternC(S,ND)) 7853 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7854 7855 // Neither global nor extern "C": nothing to do. 7856 return false; 7857 } 7858 7859 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7860 // If the decl is already known invalid, don't check it. 7861 if (NewVD->isInvalidDecl()) 7862 return; 7863 7864 QualType T = NewVD->getType(); 7865 7866 // Defer checking an 'auto' type until its initializer is attached. 7867 if (T->isUndeducedType()) 7868 return; 7869 7870 if (NewVD->hasAttrs()) 7871 CheckAlignasUnderalignment(NewVD); 7872 7873 if (T->isObjCObjectType()) { 7874 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7875 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7876 T = Context.getObjCObjectPointerType(T); 7877 NewVD->setType(T); 7878 } 7879 7880 // Emit an error if an address space was applied to decl with local storage. 7881 // This includes arrays of objects with address space qualifiers, but not 7882 // automatic variables that point to other address spaces. 7883 // ISO/IEC TR 18037 S5.1.2 7884 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7885 T.getAddressSpace() != LangAS::Default) { 7886 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7887 NewVD->setInvalidDecl(); 7888 return; 7889 } 7890 7891 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7892 // scope. 7893 if (getLangOpts().OpenCLVersion == 120 && 7894 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 7895 getLangOpts()) && 7896 NewVD->isStaticLocal()) { 7897 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7898 NewVD->setInvalidDecl(); 7899 return; 7900 } 7901 7902 if (getLangOpts().OpenCL) { 7903 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7904 if (NewVD->hasAttr<BlocksAttr>()) { 7905 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7906 return; 7907 } 7908 7909 if (T->isBlockPointerType()) { 7910 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7911 // can't use 'extern' storage class. 7912 if (!T.isConstQualified()) { 7913 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7914 << 0 /*const*/; 7915 NewVD->setInvalidDecl(); 7916 return; 7917 } 7918 if (NewVD->hasExternalStorage()) { 7919 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7920 NewVD->setInvalidDecl(); 7921 return; 7922 } 7923 } 7924 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7925 // __constant address space. 7926 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7927 // variables inside a function can also be declared in the global 7928 // address space. 7929 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7930 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7931 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7932 NewVD->hasExternalStorage()) { 7933 if (!T->isSamplerT() && 7934 !T->isDependentType() && 7935 !(T.getAddressSpace() == LangAS::opencl_constant || 7936 (T.getAddressSpace() == LangAS::opencl_global && 7937 (getLangOpts().OpenCLVersion == 200 || 7938 getLangOpts().OpenCLCPlusPlus)))) { 7939 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7940 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7941 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7942 << Scope << "global or constant"; 7943 else 7944 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7945 << Scope << "constant"; 7946 NewVD->setInvalidDecl(); 7947 return; 7948 } 7949 } else { 7950 if (T.getAddressSpace() == LangAS::opencl_global) { 7951 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7952 << 1 /*is any function*/ << "global"; 7953 NewVD->setInvalidDecl(); 7954 return; 7955 } 7956 if (T.getAddressSpace() == LangAS::opencl_constant || 7957 T.getAddressSpace() == LangAS::opencl_local) { 7958 FunctionDecl *FD = getCurFunctionDecl(); 7959 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7960 // in functions. 7961 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7962 if (T.getAddressSpace() == LangAS::opencl_constant) 7963 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7964 << 0 /*non-kernel only*/ << "constant"; 7965 else 7966 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7967 << 0 /*non-kernel only*/ << "local"; 7968 NewVD->setInvalidDecl(); 7969 return; 7970 } 7971 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7972 // in the outermost scope of a kernel function. 7973 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7974 if (!getCurScope()->isFunctionScope()) { 7975 if (T.getAddressSpace() == LangAS::opencl_constant) 7976 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7977 << "constant"; 7978 else 7979 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7980 << "local"; 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 } 7985 } else if (T.getAddressSpace() != LangAS::opencl_private && 7986 // If we are parsing a template we didn't deduce an addr 7987 // space yet. 7988 T.getAddressSpace() != LangAS::Default) { 7989 // Do not allow other address spaces on automatic variable. 7990 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7991 NewVD->setInvalidDecl(); 7992 return; 7993 } 7994 } 7995 } 7996 7997 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7998 && !NewVD->hasAttr<BlocksAttr>()) { 7999 if (getLangOpts().getGC() != LangOptions::NonGC) 8000 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8001 else { 8002 assert(!getLangOpts().ObjCAutoRefCount); 8003 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8004 } 8005 } 8006 8007 bool isVM = T->isVariablyModifiedType(); 8008 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8009 NewVD->hasAttr<BlocksAttr>()) 8010 setFunctionHasBranchProtectedScope(); 8011 8012 if ((isVM && NewVD->hasLinkage()) || 8013 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8014 bool SizeIsNegative; 8015 llvm::APSInt Oversized; 8016 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8017 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8018 QualType FixedT; 8019 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8020 FixedT = FixedTInfo->getType(); 8021 else if (FixedTInfo) { 8022 // Type and type-as-written are canonically different. We need to fix up 8023 // both types separately. 8024 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8025 Oversized); 8026 } 8027 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8028 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8029 // FIXME: This won't give the correct result for 8030 // int a[10][n]; 8031 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8032 8033 if (NewVD->isFileVarDecl()) 8034 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8035 << SizeRange; 8036 else if (NewVD->isStaticLocal()) 8037 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8038 << SizeRange; 8039 else 8040 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8041 << SizeRange; 8042 NewVD->setInvalidDecl(); 8043 return; 8044 } 8045 8046 if (!FixedTInfo) { 8047 if (NewVD->isFileVarDecl()) 8048 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8049 else 8050 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8051 NewVD->setInvalidDecl(); 8052 return; 8053 } 8054 8055 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8056 NewVD->setType(FixedT); 8057 NewVD->setTypeSourceInfo(FixedTInfo); 8058 } 8059 8060 if (T->isVoidType()) { 8061 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8062 // of objects and functions. 8063 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8064 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8065 << T; 8066 NewVD->setInvalidDecl(); 8067 return; 8068 } 8069 } 8070 8071 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8072 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8073 NewVD->setInvalidDecl(); 8074 return; 8075 } 8076 8077 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8078 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8079 NewVD->setInvalidDecl(); 8080 return; 8081 } 8082 8083 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8084 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8085 NewVD->setInvalidDecl(); 8086 return; 8087 } 8088 8089 if (NewVD->isConstexpr() && !T->isDependentType() && 8090 RequireLiteralType(NewVD->getLocation(), T, 8091 diag::err_constexpr_var_non_literal)) { 8092 NewVD->setInvalidDecl(); 8093 return; 8094 } 8095 8096 // PPC MMA non-pointer types are not allowed as non-local variable types. 8097 if (Context.getTargetInfo().getTriple().isPPC64() && 8098 !NewVD->isLocalVarDecl() && 8099 CheckPPCMMAType(T, NewVD->getLocation())) { 8100 NewVD->setInvalidDecl(); 8101 return; 8102 } 8103 } 8104 8105 /// Perform semantic checking on a newly-created variable 8106 /// declaration. 8107 /// 8108 /// This routine performs all of the type-checking required for a 8109 /// variable declaration once it has been built. It is used both to 8110 /// check variables after they have been parsed and their declarators 8111 /// have been translated into a declaration, and to check variables 8112 /// that have been instantiated from a template. 8113 /// 8114 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8115 /// 8116 /// Returns true if the variable declaration is a redeclaration. 8117 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8118 CheckVariableDeclarationType(NewVD); 8119 8120 // If the decl is already known invalid, don't check it. 8121 if (NewVD->isInvalidDecl()) 8122 return false; 8123 8124 // If we did not find anything by this name, look for a non-visible 8125 // extern "C" declaration with the same name. 8126 if (Previous.empty() && 8127 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8128 Previous.setShadowed(); 8129 8130 if (!Previous.empty()) { 8131 MergeVarDecl(NewVD, Previous); 8132 return true; 8133 } 8134 return false; 8135 } 8136 8137 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8138 /// and if so, check that it's a valid override and remember it. 8139 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8140 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8141 8142 // Look for methods in base classes that this method might override. 8143 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8144 /*DetectVirtual=*/false); 8145 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8146 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8147 DeclarationName Name = MD->getDeclName(); 8148 8149 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8150 // We really want to find the base class destructor here. 8151 QualType T = Context.getTypeDeclType(BaseRecord); 8152 CanQualType CT = Context.getCanonicalType(T); 8153 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8154 } 8155 8156 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8157 CXXMethodDecl *BaseMD = 8158 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8159 if (!BaseMD || !BaseMD->isVirtual() || 8160 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8161 /*ConsiderCudaAttrs=*/true, 8162 // C++2a [class.virtual]p2 does not consider requires 8163 // clauses when overriding. 8164 /*ConsiderRequiresClauses=*/false)) 8165 continue; 8166 8167 if (Overridden.insert(BaseMD).second) { 8168 MD->addOverriddenMethod(BaseMD); 8169 CheckOverridingFunctionReturnType(MD, BaseMD); 8170 CheckOverridingFunctionAttributes(MD, BaseMD); 8171 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8172 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8173 } 8174 8175 // A method can only override one function from each base class. We 8176 // don't track indirectly overridden methods from bases of bases. 8177 return true; 8178 } 8179 8180 return false; 8181 }; 8182 8183 DC->lookupInBases(VisitBase, Paths); 8184 return !Overridden.empty(); 8185 } 8186 8187 namespace { 8188 // Struct for holding all of the extra arguments needed by 8189 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8190 struct ActOnFDArgs { 8191 Scope *S; 8192 Declarator &D; 8193 MultiTemplateParamsArg TemplateParamLists; 8194 bool AddToScope; 8195 }; 8196 } // end anonymous namespace 8197 8198 namespace { 8199 8200 // Callback to only accept typo corrections that have a non-zero edit distance. 8201 // Also only accept corrections that have the same parent decl. 8202 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8203 public: 8204 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8205 CXXRecordDecl *Parent) 8206 : Context(Context), OriginalFD(TypoFD), 8207 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8208 8209 bool ValidateCandidate(const TypoCorrection &candidate) override { 8210 if (candidate.getEditDistance() == 0) 8211 return false; 8212 8213 SmallVector<unsigned, 1> MismatchedParams; 8214 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8215 CDeclEnd = candidate.end(); 8216 CDecl != CDeclEnd; ++CDecl) { 8217 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8218 8219 if (FD && !FD->hasBody() && 8220 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8221 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8222 CXXRecordDecl *Parent = MD->getParent(); 8223 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8224 return true; 8225 } else if (!ExpectedParent) { 8226 return true; 8227 } 8228 } 8229 } 8230 8231 return false; 8232 } 8233 8234 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8235 return std::make_unique<DifferentNameValidatorCCC>(*this); 8236 } 8237 8238 private: 8239 ASTContext &Context; 8240 FunctionDecl *OriginalFD; 8241 CXXRecordDecl *ExpectedParent; 8242 }; 8243 8244 } // end anonymous namespace 8245 8246 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8247 TypoCorrectedFunctionDefinitions.insert(F); 8248 } 8249 8250 /// Generate diagnostics for an invalid function redeclaration. 8251 /// 8252 /// This routine handles generating the diagnostic messages for an invalid 8253 /// function redeclaration, including finding possible similar declarations 8254 /// or performing typo correction if there are no previous declarations with 8255 /// the same name. 8256 /// 8257 /// Returns a NamedDecl iff typo correction was performed and substituting in 8258 /// the new declaration name does not cause new errors. 8259 static NamedDecl *DiagnoseInvalidRedeclaration( 8260 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8261 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8262 DeclarationName Name = NewFD->getDeclName(); 8263 DeclContext *NewDC = NewFD->getDeclContext(); 8264 SmallVector<unsigned, 1> MismatchedParams; 8265 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8266 TypoCorrection Correction; 8267 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8268 unsigned DiagMsg = 8269 IsLocalFriend ? diag::err_no_matching_local_friend : 8270 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8271 diag::err_member_decl_does_not_match; 8272 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8273 IsLocalFriend ? Sema::LookupLocalFriendName 8274 : Sema::LookupOrdinaryName, 8275 Sema::ForVisibleRedeclaration); 8276 8277 NewFD->setInvalidDecl(); 8278 if (IsLocalFriend) 8279 SemaRef.LookupName(Prev, S); 8280 else 8281 SemaRef.LookupQualifiedName(Prev, NewDC); 8282 assert(!Prev.isAmbiguous() && 8283 "Cannot have an ambiguity in previous-declaration lookup"); 8284 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8285 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8286 MD ? MD->getParent() : nullptr); 8287 if (!Prev.empty()) { 8288 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8289 Func != FuncEnd; ++Func) { 8290 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8291 if (FD && 8292 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8293 // Add 1 to the index so that 0 can mean the mismatch didn't 8294 // involve a parameter 8295 unsigned ParamNum = 8296 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8297 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8298 } 8299 } 8300 // If the qualified name lookup yielded nothing, try typo correction 8301 } else if ((Correction = SemaRef.CorrectTypo( 8302 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8303 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8304 IsLocalFriend ? nullptr : NewDC))) { 8305 // Set up everything for the call to ActOnFunctionDeclarator 8306 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8307 ExtraArgs.D.getIdentifierLoc()); 8308 Previous.clear(); 8309 Previous.setLookupName(Correction.getCorrection()); 8310 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8311 CDeclEnd = Correction.end(); 8312 CDecl != CDeclEnd; ++CDecl) { 8313 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8314 if (FD && !FD->hasBody() && 8315 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8316 Previous.addDecl(FD); 8317 } 8318 } 8319 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8320 8321 NamedDecl *Result; 8322 // Retry building the function declaration with the new previous 8323 // declarations, and with errors suppressed. 8324 { 8325 // Trap errors. 8326 Sema::SFINAETrap Trap(SemaRef); 8327 8328 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8329 // pieces need to verify the typo-corrected C++ declaration and hopefully 8330 // eliminate the need for the parameter pack ExtraArgs. 8331 Result = SemaRef.ActOnFunctionDeclarator( 8332 ExtraArgs.S, ExtraArgs.D, 8333 Correction.getCorrectionDecl()->getDeclContext(), 8334 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8335 ExtraArgs.AddToScope); 8336 8337 if (Trap.hasErrorOccurred()) 8338 Result = nullptr; 8339 } 8340 8341 if (Result) { 8342 // Determine which correction we picked. 8343 Decl *Canonical = Result->getCanonicalDecl(); 8344 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8345 I != E; ++I) 8346 if ((*I)->getCanonicalDecl() == Canonical) 8347 Correction.setCorrectionDecl(*I); 8348 8349 // Let Sema know about the correction. 8350 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8351 SemaRef.diagnoseTypo( 8352 Correction, 8353 SemaRef.PDiag(IsLocalFriend 8354 ? diag::err_no_matching_local_friend_suggest 8355 : diag::err_member_decl_does_not_match_suggest) 8356 << Name << NewDC << IsDefinition); 8357 return Result; 8358 } 8359 8360 // Pretend the typo correction never occurred 8361 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8362 ExtraArgs.D.getIdentifierLoc()); 8363 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8364 Previous.clear(); 8365 Previous.setLookupName(Name); 8366 } 8367 8368 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8369 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8370 8371 bool NewFDisConst = false; 8372 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8373 NewFDisConst = NewMD->isConst(); 8374 8375 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8376 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8377 NearMatch != NearMatchEnd; ++NearMatch) { 8378 FunctionDecl *FD = NearMatch->first; 8379 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8380 bool FDisConst = MD && MD->isConst(); 8381 bool IsMember = MD || !IsLocalFriend; 8382 8383 // FIXME: These notes are poorly worded for the local friend case. 8384 if (unsigned Idx = NearMatch->second) { 8385 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8386 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8387 if (Loc.isInvalid()) Loc = FD->getLocation(); 8388 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8389 : diag::note_local_decl_close_param_match) 8390 << Idx << FDParam->getType() 8391 << NewFD->getParamDecl(Idx - 1)->getType(); 8392 } else if (FDisConst != NewFDisConst) { 8393 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8394 << NewFDisConst << FD->getSourceRange().getEnd(); 8395 } else 8396 SemaRef.Diag(FD->getLocation(), 8397 IsMember ? diag::note_member_def_close_match 8398 : diag::note_local_decl_close_match); 8399 } 8400 return nullptr; 8401 } 8402 8403 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8404 switch (D.getDeclSpec().getStorageClassSpec()) { 8405 default: llvm_unreachable("Unknown storage class!"); 8406 case DeclSpec::SCS_auto: 8407 case DeclSpec::SCS_register: 8408 case DeclSpec::SCS_mutable: 8409 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8410 diag::err_typecheck_sclass_func); 8411 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8412 D.setInvalidType(); 8413 break; 8414 case DeclSpec::SCS_unspecified: break; 8415 case DeclSpec::SCS_extern: 8416 if (D.getDeclSpec().isExternInLinkageSpec()) 8417 return SC_None; 8418 return SC_Extern; 8419 case DeclSpec::SCS_static: { 8420 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8421 // C99 6.7.1p5: 8422 // The declaration of an identifier for a function that has 8423 // block scope shall have no explicit storage-class specifier 8424 // other than extern 8425 // See also (C++ [dcl.stc]p4). 8426 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8427 diag::err_static_block_func); 8428 break; 8429 } else 8430 return SC_Static; 8431 } 8432 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8433 } 8434 8435 // No explicit storage class has already been returned 8436 return SC_None; 8437 } 8438 8439 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8440 DeclContext *DC, QualType &R, 8441 TypeSourceInfo *TInfo, 8442 StorageClass SC, 8443 bool &IsVirtualOkay) { 8444 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8445 DeclarationName Name = NameInfo.getName(); 8446 8447 FunctionDecl *NewFD = nullptr; 8448 bool isInline = D.getDeclSpec().isInlineSpecified(); 8449 8450 if (!SemaRef.getLangOpts().CPlusPlus) { 8451 // Determine whether the function was written with a 8452 // prototype. This true when: 8453 // - there is a prototype in the declarator, or 8454 // - the type R of the function is some kind of typedef or other non- 8455 // attributed reference to a type name (which eventually refers to a 8456 // function type). 8457 bool HasPrototype = 8458 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8459 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8460 8461 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8462 R, TInfo, SC, isInline, HasPrototype, 8463 ConstexprSpecKind::Unspecified, 8464 /*TrailingRequiresClause=*/nullptr); 8465 if (D.isInvalidType()) 8466 NewFD->setInvalidDecl(); 8467 8468 return NewFD; 8469 } 8470 8471 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8472 8473 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8474 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8475 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8476 diag::err_constexpr_wrong_decl_kind) 8477 << static_cast<int>(ConstexprKind); 8478 ConstexprKind = ConstexprSpecKind::Unspecified; 8479 D.getMutableDeclSpec().ClearConstexprSpec(); 8480 } 8481 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8482 8483 // Check that the return type is not an abstract class type. 8484 // For record types, this is done by the AbstractClassUsageDiagnoser once 8485 // the class has been completely parsed. 8486 if (!DC->isRecord() && 8487 SemaRef.RequireNonAbstractType( 8488 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8489 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8490 D.setInvalidType(); 8491 8492 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8493 // This is a C++ constructor declaration. 8494 assert(DC->isRecord() && 8495 "Constructors can only be declared in a member context"); 8496 8497 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8498 return CXXConstructorDecl::Create( 8499 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8500 TInfo, ExplicitSpecifier, isInline, 8501 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8502 TrailingRequiresClause); 8503 8504 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8505 // This is a C++ destructor declaration. 8506 if (DC->isRecord()) { 8507 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8508 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8509 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8510 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8511 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8512 TrailingRequiresClause); 8513 8514 // If the destructor needs an implicit exception specification, set it 8515 // now. FIXME: It'd be nice to be able to create the right type to start 8516 // with, but the type needs to reference the destructor declaration. 8517 if (SemaRef.getLangOpts().CPlusPlus11) 8518 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8519 8520 IsVirtualOkay = true; 8521 return NewDD; 8522 8523 } else { 8524 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8525 D.setInvalidType(); 8526 8527 // Create a FunctionDecl to satisfy the function definition parsing 8528 // code path. 8529 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8530 D.getIdentifierLoc(), Name, R, TInfo, SC, 8531 isInline, 8532 /*hasPrototype=*/true, ConstexprKind, 8533 TrailingRequiresClause); 8534 } 8535 8536 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8537 if (!DC->isRecord()) { 8538 SemaRef.Diag(D.getIdentifierLoc(), 8539 diag::err_conv_function_not_member); 8540 return nullptr; 8541 } 8542 8543 SemaRef.CheckConversionDeclarator(D, R, SC); 8544 if (D.isInvalidType()) 8545 return nullptr; 8546 8547 IsVirtualOkay = true; 8548 return CXXConversionDecl::Create( 8549 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8550 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8551 TrailingRequiresClause); 8552 8553 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8554 if (TrailingRequiresClause) 8555 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8556 diag::err_trailing_requires_clause_on_deduction_guide) 8557 << TrailingRequiresClause->getSourceRange(); 8558 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8559 8560 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8561 ExplicitSpecifier, NameInfo, R, TInfo, 8562 D.getEndLoc()); 8563 } else if (DC->isRecord()) { 8564 // If the name of the function is the same as the name of the record, 8565 // then this must be an invalid constructor that has a return type. 8566 // (The parser checks for a return type and makes the declarator a 8567 // constructor if it has no return type). 8568 if (Name.getAsIdentifierInfo() && 8569 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8570 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8571 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8572 << SourceRange(D.getIdentifierLoc()); 8573 return nullptr; 8574 } 8575 8576 // This is a C++ method declaration. 8577 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8578 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8579 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8580 TrailingRequiresClause); 8581 IsVirtualOkay = !Ret->isStatic(); 8582 return Ret; 8583 } else { 8584 bool isFriend = 8585 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8586 if (!isFriend && SemaRef.CurContext->isRecord()) 8587 return nullptr; 8588 8589 // Determine whether the function was written with a 8590 // prototype. This true when: 8591 // - we're in C++ (where every function has a prototype), 8592 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8593 R, TInfo, SC, isInline, true /*HasPrototype*/, 8594 ConstexprKind, TrailingRequiresClause); 8595 } 8596 } 8597 8598 enum OpenCLParamType { 8599 ValidKernelParam, 8600 PtrPtrKernelParam, 8601 PtrKernelParam, 8602 InvalidAddrSpacePtrKernelParam, 8603 InvalidKernelParam, 8604 RecordKernelParam 8605 }; 8606 8607 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8608 // Size dependent types are just typedefs to normal integer types 8609 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8610 // integers other than by their names. 8611 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8612 8613 // Remove typedefs one by one until we reach a typedef 8614 // for a size dependent type. 8615 QualType DesugaredTy = Ty; 8616 do { 8617 ArrayRef<StringRef> Names(SizeTypeNames); 8618 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8619 if (Names.end() != Match) 8620 return true; 8621 8622 Ty = DesugaredTy; 8623 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8624 } while (DesugaredTy != Ty); 8625 8626 return false; 8627 } 8628 8629 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8630 if (PT->isPointerType()) { 8631 QualType PointeeType = PT->getPointeeType(); 8632 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8633 PointeeType.getAddressSpace() == LangAS::opencl_private || 8634 PointeeType.getAddressSpace() == LangAS::Default) 8635 return InvalidAddrSpacePtrKernelParam; 8636 8637 if (PointeeType->isPointerType()) { 8638 // This is a pointer to pointer parameter. 8639 // Recursively check inner type. 8640 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8641 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8642 ParamKind == InvalidKernelParam) 8643 return ParamKind; 8644 8645 return PtrPtrKernelParam; 8646 } 8647 return PtrKernelParam; 8648 } 8649 8650 // OpenCL v1.2 s6.9.k: 8651 // Arguments to kernel functions in a program cannot be declared with the 8652 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8653 // uintptr_t or a struct and/or union that contain fields declared to be one 8654 // of these built-in scalar types. 8655 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8656 return InvalidKernelParam; 8657 8658 if (PT->isImageType()) 8659 return PtrKernelParam; 8660 8661 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8662 return InvalidKernelParam; 8663 8664 // OpenCL extension spec v1.2 s9.5: 8665 // This extension adds support for half scalar and vector types as built-in 8666 // types that can be used for arithmetic operations, conversions etc. 8667 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8668 PT->isHalfType()) 8669 return InvalidKernelParam; 8670 8671 if (PT->isRecordType()) 8672 return RecordKernelParam; 8673 8674 // Look into an array argument to check if it has a forbidden type. 8675 if (PT->isArrayType()) { 8676 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8677 // Call ourself to check an underlying type of an array. Since the 8678 // getPointeeOrArrayElementType returns an innermost type which is not an 8679 // array, this recursive call only happens once. 8680 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8681 } 8682 8683 return ValidKernelParam; 8684 } 8685 8686 static void checkIsValidOpenCLKernelParameter( 8687 Sema &S, 8688 Declarator &D, 8689 ParmVarDecl *Param, 8690 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8691 QualType PT = Param->getType(); 8692 8693 // Cache the valid types we encounter to avoid rechecking structs that are 8694 // used again 8695 if (ValidTypes.count(PT.getTypePtr())) 8696 return; 8697 8698 switch (getOpenCLKernelParameterType(S, PT)) { 8699 case PtrPtrKernelParam: 8700 // OpenCL v3.0 s6.11.a: 8701 // A kernel function argument cannot be declared as a pointer to a pointer 8702 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8703 if (S.getLangOpts().OpenCLVersion < 120 && 8704 !S.getLangOpts().OpenCLCPlusPlus) { 8705 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8706 D.setInvalidType(); 8707 return; 8708 } 8709 8710 ValidTypes.insert(PT.getTypePtr()); 8711 return; 8712 8713 case InvalidAddrSpacePtrKernelParam: 8714 // OpenCL v1.0 s6.5: 8715 // __kernel function arguments declared to be a pointer of a type can point 8716 // to one of the following address spaces only : __global, __local or 8717 // __constant. 8718 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8719 D.setInvalidType(); 8720 return; 8721 8722 // OpenCL v1.2 s6.9.k: 8723 // Arguments to kernel functions in a program cannot be declared with the 8724 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8725 // uintptr_t or a struct and/or union that contain fields declared to be 8726 // one of these built-in scalar types. 8727 8728 case InvalidKernelParam: 8729 // OpenCL v1.2 s6.8 n: 8730 // A kernel function argument cannot be declared 8731 // of event_t type. 8732 // Do not diagnose half type since it is diagnosed as invalid argument 8733 // type for any function elsewhere. 8734 if (!PT->isHalfType()) { 8735 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8736 8737 // Explain what typedefs are involved. 8738 const TypedefType *Typedef = nullptr; 8739 while ((Typedef = PT->getAs<TypedefType>())) { 8740 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8741 // SourceLocation may be invalid for a built-in type. 8742 if (Loc.isValid()) 8743 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8744 PT = Typedef->desugar(); 8745 } 8746 } 8747 8748 D.setInvalidType(); 8749 return; 8750 8751 case PtrKernelParam: 8752 case ValidKernelParam: 8753 ValidTypes.insert(PT.getTypePtr()); 8754 return; 8755 8756 case RecordKernelParam: 8757 break; 8758 } 8759 8760 // Track nested structs we will inspect 8761 SmallVector<const Decl *, 4> VisitStack; 8762 8763 // Track where we are in the nested structs. Items will migrate from 8764 // VisitStack to HistoryStack as we do the DFS for bad field. 8765 SmallVector<const FieldDecl *, 4> HistoryStack; 8766 HistoryStack.push_back(nullptr); 8767 8768 // At this point we already handled everything except of a RecordType or 8769 // an ArrayType of a RecordType. 8770 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8771 const RecordType *RecTy = 8772 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8773 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8774 8775 VisitStack.push_back(RecTy->getDecl()); 8776 assert(VisitStack.back() && "First decl null?"); 8777 8778 do { 8779 const Decl *Next = VisitStack.pop_back_val(); 8780 if (!Next) { 8781 assert(!HistoryStack.empty()); 8782 // Found a marker, we have gone up a level 8783 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8784 ValidTypes.insert(Hist->getType().getTypePtr()); 8785 8786 continue; 8787 } 8788 8789 // Adds everything except the original parameter declaration (which is not a 8790 // field itself) to the history stack. 8791 const RecordDecl *RD; 8792 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8793 HistoryStack.push_back(Field); 8794 8795 QualType FieldTy = Field->getType(); 8796 // Other field types (known to be valid or invalid) are handled while we 8797 // walk around RecordDecl::fields(). 8798 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8799 "Unexpected type."); 8800 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8801 8802 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8803 } else { 8804 RD = cast<RecordDecl>(Next); 8805 } 8806 8807 // Add a null marker so we know when we've gone back up a level 8808 VisitStack.push_back(nullptr); 8809 8810 for (const auto *FD : RD->fields()) { 8811 QualType QT = FD->getType(); 8812 8813 if (ValidTypes.count(QT.getTypePtr())) 8814 continue; 8815 8816 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8817 if (ParamType == ValidKernelParam) 8818 continue; 8819 8820 if (ParamType == RecordKernelParam) { 8821 VisitStack.push_back(FD); 8822 continue; 8823 } 8824 8825 // OpenCL v1.2 s6.9.p: 8826 // Arguments to kernel functions that are declared to be a struct or union 8827 // do not allow OpenCL objects to be passed as elements of the struct or 8828 // union. 8829 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8830 ParamType == InvalidAddrSpacePtrKernelParam) { 8831 S.Diag(Param->getLocation(), 8832 diag::err_record_with_pointers_kernel_param) 8833 << PT->isUnionType() 8834 << PT; 8835 } else { 8836 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8837 } 8838 8839 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8840 << OrigRecDecl->getDeclName(); 8841 8842 // We have an error, now let's go back up through history and show where 8843 // the offending field came from 8844 for (ArrayRef<const FieldDecl *>::const_iterator 8845 I = HistoryStack.begin() + 1, 8846 E = HistoryStack.end(); 8847 I != E; ++I) { 8848 const FieldDecl *OuterField = *I; 8849 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8850 << OuterField->getType(); 8851 } 8852 8853 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8854 << QT->isPointerType() 8855 << QT; 8856 D.setInvalidType(); 8857 return; 8858 } 8859 } while (!VisitStack.empty()); 8860 } 8861 8862 /// Find the DeclContext in which a tag is implicitly declared if we see an 8863 /// elaborated type specifier in the specified context, and lookup finds 8864 /// nothing. 8865 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8866 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8867 DC = DC->getParent(); 8868 return DC; 8869 } 8870 8871 /// Find the Scope in which a tag is implicitly declared if we see an 8872 /// elaborated type specifier in the specified context, and lookup finds 8873 /// nothing. 8874 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8875 while (S->isClassScope() || 8876 (LangOpts.CPlusPlus && 8877 S->isFunctionPrototypeScope()) || 8878 ((S->getFlags() & Scope::DeclScope) == 0) || 8879 (S->getEntity() && S->getEntity()->isTransparentContext())) 8880 S = S->getParent(); 8881 return S; 8882 } 8883 8884 NamedDecl* 8885 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8886 TypeSourceInfo *TInfo, LookupResult &Previous, 8887 MultiTemplateParamsArg TemplateParamListsRef, 8888 bool &AddToScope) { 8889 QualType R = TInfo->getType(); 8890 8891 assert(R->isFunctionType()); 8892 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8893 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8894 8895 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8896 for (TemplateParameterList *TPL : TemplateParamListsRef) 8897 TemplateParamLists.push_back(TPL); 8898 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8899 if (!TemplateParamLists.empty() && 8900 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8901 TemplateParamLists.back() = Invented; 8902 else 8903 TemplateParamLists.push_back(Invented); 8904 } 8905 8906 // TODO: consider using NameInfo for diagnostic. 8907 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8908 DeclarationName Name = NameInfo.getName(); 8909 StorageClass SC = getFunctionStorageClass(*this, D); 8910 8911 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8912 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8913 diag::err_invalid_thread) 8914 << DeclSpec::getSpecifierName(TSCS); 8915 8916 if (D.isFirstDeclarationOfMember()) 8917 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8918 D.getIdentifierLoc()); 8919 8920 bool isFriend = false; 8921 FunctionTemplateDecl *FunctionTemplate = nullptr; 8922 bool isMemberSpecialization = false; 8923 bool isFunctionTemplateSpecialization = false; 8924 8925 bool isDependentClassScopeExplicitSpecialization = false; 8926 bool HasExplicitTemplateArgs = false; 8927 TemplateArgumentListInfo TemplateArgs; 8928 8929 bool isVirtualOkay = false; 8930 8931 DeclContext *OriginalDC = DC; 8932 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8933 8934 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8935 isVirtualOkay); 8936 if (!NewFD) return nullptr; 8937 8938 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8939 NewFD->setTopLevelDeclInObjCContainer(); 8940 8941 // Set the lexical context. If this is a function-scope declaration, or has a 8942 // C++ scope specifier, or is the object of a friend declaration, the lexical 8943 // context will be different from the semantic context. 8944 NewFD->setLexicalDeclContext(CurContext); 8945 8946 if (IsLocalExternDecl) 8947 NewFD->setLocalExternDecl(); 8948 8949 if (getLangOpts().CPlusPlus) { 8950 bool isInline = D.getDeclSpec().isInlineSpecified(); 8951 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8952 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8953 isFriend = D.getDeclSpec().isFriendSpecified(); 8954 if (isFriend && !isInline && D.isFunctionDefinition()) { 8955 // C++ [class.friend]p5 8956 // A function can be defined in a friend declaration of a 8957 // class . . . . Such a function is implicitly inline. 8958 NewFD->setImplicitlyInline(); 8959 } 8960 8961 // If this is a method defined in an __interface, and is not a constructor 8962 // or an overloaded operator, then set the pure flag (isVirtual will already 8963 // return true). 8964 if (const CXXRecordDecl *Parent = 8965 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8966 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8967 NewFD->setPure(true); 8968 8969 // C++ [class.union]p2 8970 // A union can have member functions, but not virtual functions. 8971 if (isVirtual && Parent->isUnion()) 8972 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8973 } 8974 8975 SetNestedNameSpecifier(*this, NewFD, D); 8976 isMemberSpecialization = false; 8977 isFunctionTemplateSpecialization = false; 8978 if (D.isInvalidType()) 8979 NewFD->setInvalidDecl(); 8980 8981 // Match up the template parameter lists with the scope specifier, then 8982 // determine whether we have a template or a template specialization. 8983 bool Invalid = false; 8984 TemplateParameterList *TemplateParams = 8985 MatchTemplateParametersToScopeSpecifier( 8986 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8987 D.getCXXScopeSpec(), 8988 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8989 ? D.getName().TemplateId 8990 : nullptr, 8991 TemplateParamLists, isFriend, isMemberSpecialization, 8992 Invalid); 8993 if (TemplateParams) { 8994 // Check that we can declare a template here. 8995 if (CheckTemplateDeclScope(S, TemplateParams)) 8996 NewFD->setInvalidDecl(); 8997 8998 if (TemplateParams->size() > 0) { 8999 // This is a function template 9000 9001 // A destructor cannot be a template. 9002 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9003 Diag(NewFD->getLocation(), diag::err_destructor_template); 9004 NewFD->setInvalidDecl(); 9005 } 9006 9007 // If we're adding a template to a dependent context, we may need to 9008 // rebuilding some of the types used within the template parameter list, 9009 // now that we know what the current instantiation is. 9010 if (DC->isDependentContext()) { 9011 ContextRAII SavedContext(*this, DC); 9012 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9013 Invalid = true; 9014 } 9015 9016 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9017 NewFD->getLocation(), 9018 Name, TemplateParams, 9019 NewFD); 9020 FunctionTemplate->setLexicalDeclContext(CurContext); 9021 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9022 9023 // For source fidelity, store the other template param lists. 9024 if (TemplateParamLists.size() > 1) { 9025 NewFD->setTemplateParameterListsInfo(Context, 9026 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9027 .drop_back(1)); 9028 } 9029 } else { 9030 // This is a function template specialization. 9031 isFunctionTemplateSpecialization = true; 9032 // For source fidelity, store all the template param lists. 9033 if (TemplateParamLists.size() > 0) 9034 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9035 9036 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9037 if (isFriend) { 9038 // We want to remove the "template<>", found here. 9039 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9040 9041 // If we remove the template<> and the name is not a 9042 // template-id, we're actually silently creating a problem: 9043 // the friend declaration will refer to an untemplated decl, 9044 // and clearly the user wants a template specialization. So 9045 // we need to insert '<>' after the name. 9046 SourceLocation InsertLoc; 9047 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9048 InsertLoc = D.getName().getSourceRange().getEnd(); 9049 InsertLoc = getLocForEndOfToken(InsertLoc); 9050 } 9051 9052 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9053 << Name << RemoveRange 9054 << FixItHint::CreateRemoval(RemoveRange) 9055 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9056 } 9057 } 9058 } else { 9059 // Check that we can declare a template here. 9060 if (!TemplateParamLists.empty() && isMemberSpecialization && 9061 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9062 NewFD->setInvalidDecl(); 9063 9064 // All template param lists were matched against the scope specifier: 9065 // this is NOT (an explicit specialization of) a template. 9066 if (TemplateParamLists.size() > 0) 9067 // For source fidelity, store all the template param lists. 9068 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9069 } 9070 9071 if (Invalid) { 9072 NewFD->setInvalidDecl(); 9073 if (FunctionTemplate) 9074 FunctionTemplate->setInvalidDecl(); 9075 } 9076 9077 // C++ [dcl.fct.spec]p5: 9078 // The virtual specifier shall only be used in declarations of 9079 // nonstatic class member functions that appear within a 9080 // member-specification of a class declaration; see 10.3. 9081 // 9082 if (isVirtual && !NewFD->isInvalidDecl()) { 9083 if (!isVirtualOkay) { 9084 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9085 diag::err_virtual_non_function); 9086 } else if (!CurContext->isRecord()) { 9087 // 'virtual' was specified outside of the class. 9088 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9089 diag::err_virtual_out_of_class) 9090 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9091 } else if (NewFD->getDescribedFunctionTemplate()) { 9092 // C++ [temp.mem]p3: 9093 // A member function template shall not be virtual. 9094 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9095 diag::err_virtual_member_function_template) 9096 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9097 } else { 9098 // Okay: Add virtual to the method. 9099 NewFD->setVirtualAsWritten(true); 9100 } 9101 9102 if (getLangOpts().CPlusPlus14 && 9103 NewFD->getReturnType()->isUndeducedType()) 9104 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9105 } 9106 9107 if (getLangOpts().CPlusPlus14 && 9108 (NewFD->isDependentContext() || 9109 (isFriend && CurContext->isDependentContext())) && 9110 NewFD->getReturnType()->isUndeducedType()) { 9111 // If the function template is referenced directly (for instance, as a 9112 // member of the current instantiation), pretend it has a dependent type. 9113 // This is not really justified by the standard, but is the only sane 9114 // thing to do. 9115 // FIXME: For a friend function, we have not marked the function as being 9116 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9117 const FunctionProtoType *FPT = 9118 NewFD->getType()->castAs<FunctionProtoType>(); 9119 QualType Result = 9120 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9121 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9122 FPT->getExtProtoInfo())); 9123 } 9124 9125 // C++ [dcl.fct.spec]p3: 9126 // The inline specifier shall not appear on a block scope function 9127 // declaration. 9128 if (isInline && !NewFD->isInvalidDecl()) { 9129 if (CurContext->isFunctionOrMethod()) { 9130 // 'inline' is not allowed on block scope function declaration. 9131 Diag(D.getDeclSpec().getInlineSpecLoc(), 9132 diag::err_inline_declaration_block_scope) << Name 9133 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9134 } 9135 } 9136 9137 // C++ [dcl.fct.spec]p6: 9138 // The explicit specifier shall be used only in the declaration of a 9139 // constructor or conversion function within its class definition; 9140 // see 12.3.1 and 12.3.2. 9141 if (hasExplicit && !NewFD->isInvalidDecl() && 9142 !isa<CXXDeductionGuideDecl>(NewFD)) { 9143 if (!CurContext->isRecord()) { 9144 // 'explicit' was specified outside of the class. 9145 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9146 diag::err_explicit_out_of_class) 9147 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9148 } else if (!isa<CXXConstructorDecl>(NewFD) && 9149 !isa<CXXConversionDecl>(NewFD)) { 9150 // 'explicit' was specified on a function that wasn't a constructor 9151 // or conversion function. 9152 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9153 diag::err_explicit_non_ctor_or_conv_function) 9154 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9155 } 9156 } 9157 9158 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9159 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9160 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9161 // are implicitly inline. 9162 NewFD->setImplicitlyInline(); 9163 9164 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9165 // be either constructors or to return a literal type. Therefore, 9166 // destructors cannot be declared constexpr. 9167 if (isa<CXXDestructorDecl>(NewFD) && 9168 (!getLangOpts().CPlusPlus20 || 9169 ConstexprKind == ConstexprSpecKind::Consteval)) { 9170 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9171 << static_cast<int>(ConstexprKind); 9172 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9173 ? ConstexprSpecKind::Unspecified 9174 : ConstexprSpecKind::Constexpr); 9175 } 9176 // C++20 [dcl.constexpr]p2: An allocation function, or a 9177 // deallocation function shall not be declared with the consteval 9178 // specifier. 9179 if (ConstexprKind == ConstexprSpecKind::Consteval && 9180 (NewFD->getOverloadedOperator() == OO_New || 9181 NewFD->getOverloadedOperator() == OO_Array_New || 9182 NewFD->getOverloadedOperator() == OO_Delete || 9183 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9184 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9185 diag::err_invalid_consteval_decl_kind) 9186 << NewFD; 9187 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9188 } 9189 } 9190 9191 // If __module_private__ was specified, mark the function accordingly. 9192 if (D.getDeclSpec().isModulePrivateSpecified()) { 9193 if (isFunctionTemplateSpecialization) { 9194 SourceLocation ModulePrivateLoc 9195 = D.getDeclSpec().getModulePrivateSpecLoc(); 9196 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9197 << 0 9198 << FixItHint::CreateRemoval(ModulePrivateLoc); 9199 } else { 9200 NewFD->setModulePrivate(); 9201 if (FunctionTemplate) 9202 FunctionTemplate->setModulePrivate(); 9203 } 9204 } 9205 9206 if (isFriend) { 9207 if (FunctionTemplate) { 9208 FunctionTemplate->setObjectOfFriendDecl(); 9209 FunctionTemplate->setAccess(AS_public); 9210 } 9211 NewFD->setObjectOfFriendDecl(); 9212 NewFD->setAccess(AS_public); 9213 } 9214 9215 // If a function is defined as defaulted or deleted, mark it as such now. 9216 // We'll do the relevant checks on defaulted / deleted functions later. 9217 switch (D.getFunctionDefinitionKind()) { 9218 case FunctionDefinitionKind::Declaration: 9219 case FunctionDefinitionKind::Definition: 9220 break; 9221 9222 case FunctionDefinitionKind::Defaulted: 9223 NewFD->setDefaulted(); 9224 break; 9225 9226 case FunctionDefinitionKind::Deleted: 9227 NewFD->setDeletedAsWritten(); 9228 break; 9229 } 9230 9231 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9232 D.isFunctionDefinition()) { 9233 // C++ [class.mfct]p2: 9234 // A member function may be defined (8.4) in its class definition, in 9235 // which case it is an inline member function (7.1.2) 9236 NewFD->setImplicitlyInline(); 9237 } 9238 9239 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9240 !CurContext->isRecord()) { 9241 // C++ [class.static]p1: 9242 // A data or function member of a class may be declared static 9243 // in a class definition, in which case it is a static member of 9244 // the class. 9245 9246 // Complain about the 'static' specifier if it's on an out-of-line 9247 // member function definition. 9248 9249 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9250 // member function template declaration and class member template 9251 // declaration (MSVC versions before 2015), warn about this. 9252 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9253 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9254 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9255 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9256 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9257 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9258 } 9259 9260 // C++11 [except.spec]p15: 9261 // A deallocation function with no exception-specification is treated 9262 // as if it were specified with noexcept(true). 9263 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9264 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9265 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9266 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9267 NewFD->setType(Context.getFunctionType( 9268 FPT->getReturnType(), FPT->getParamTypes(), 9269 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9270 } 9271 9272 // Filter out previous declarations that don't match the scope. 9273 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9274 D.getCXXScopeSpec().isNotEmpty() || 9275 isMemberSpecialization || 9276 isFunctionTemplateSpecialization); 9277 9278 // Handle GNU asm-label extension (encoded as an attribute). 9279 if (Expr *E = (Expr*) D.getAsmLabel()) { 9280 // The parser guarantees this is a string. 9281 StringLiteral *SE = cast<StringLiteral>(E); 9282 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9283 /*IsLiteralLabel=*/true, 9284 SE->getStrTokenLoc(0))); 9285 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9286 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9287 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9288 if (I != ExtnameUndeclaredIdentifiers.end()) { 9289 if (isDeclExternC(NewFD)) { 9290 NewFD->addAttr(I->second); 9291 ExtnameUndeclaredIdentifiers.erase(I); 9292 } else 9293 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9294 << /*Variable*/0 << NewFD; 9295 } 9296 } 9297 9298 // Copy the parameter declarations from the declarator D to the function 9299 // declaration NewFD, if they are available. First scavenge them into Params. 9300 SmallVector<ParmVarDecl*, 16> Params; 9301 unsigned FTIIdx; 9302 if (D.isFunctionDeclarator(FTIIdx)) { 9303 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9304 9305 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9306 // function that takes no arguments, not a function that takes a 9307 // single void argument. 9308 // We let through "const void" here because Sema::GetTypeForDeclarator 9309 // already checks for that case. 9310 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9311 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9312 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9313 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9314 Param->setDeclContext(NewFD); 9315 Params.push_back(Param); 9316 9317 if (Param->isInvalidDecl()) 9318 NewFD->setInvalidDecl(); 9319 } 9320 } 9321 9322 if (!getLangOpts().CPlusPlus) { 9323 // In C, find all the tag declarations from the prototype and move them 9324 // into the function DeclContext. Remove them from the surrounding tag 9325 // injection context of the function, which is typically but not always 9326 // the TU. 9327 DeclContext *PrototypeTagContext = 9328 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9329 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9330 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9331 9332 // We don't want to reparent enumerators. Look at their parent enum 9333 // instead. 9334 if (!TD) { 9335 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9336 TD = cast<EnumDecl>(ECD->getDeclContext()); 9337 } 9338 if (!TD) 9339 continue; 9340 DeclContext *TagDC = TD->getLexicalDeclContext(); 9341 if (!TagDC->containsDecl(TD)) 9342 continue; 9343 TagDC->removeDecl(TD); 9344 TD->setDeclContext(NewFD); 9345 NewFD->addDecl(TD); 9346 9347 // Preserve the lexical DeclContext if it is not the surrounding tag 9348 // injection context of the FD. In this example, the semantic context of 9349 // E will be f and the lexical context will be S, while both the 9350 // semantic and lexical contexts of S will be f: 9351 // void f(struct S { enum E { a } f; } s); 9352 if (TagDC != PrototypeTagContext) 9353 TD->setLexicalDeclContext(TagDC); 9354 } 9355 } 9356 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9357 // When we're declaring a function with a typedef, typeof, etc as in the 9358 // following example, we'll need to synthesize (unnamed) 9359 // parameters for use in the declaration. 9360 // 9361 // @code 9362 // typedef void fn(int); 9363 // fn f; 9364 // @endcode 9365 9366 // Synthesize a parameter for each argument type. 9367 for (const auto &AI : FT->param_types()) { 9368 ParmVarDecl *Param = 9369 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9370 Param->setScopeInfo(0, Params.size()); 9371 Params.push_back(Param); 9372 } 9373 } else { 9374 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9375 "Should not need args for typedef of non-prototype fn"); 9376 } 9377 9378 // Finally, we know we have the right number of parameters, install them. 9379 NewFD->setParams(Params); 9380 9381 if (D.getDeclSpec().isNoreturnSpecified()) 9382 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9383 D.getDeclSpec().getNoreturnSpecLoc(), 9384 AttributeCommonInfo::AS_Keyword)); 9385 9386 // Functions returning a variably modified type violate C99 6.7.5.2p2 9387 // because all functions have linkage. 9388 if (!NewFD->isInvalidDecl() && 9389 NewFD->getReturnType()->isVariablyModifiedType()) { 9390 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9391 NewFD->setInvalidDecl(); 9392 } 9393 9394 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9395 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9396 !NewFD->hasAttr<SectionAttr>()) 9397 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9398 Context, PragmaClangTextSection.SectionName, 9399 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9400 9401 // Apply an implicit SectionAttr if #pragma code_seg is active. 9402 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9403 !NewFD->hasAttr<SectionAttr>()) { 9404 NewFD->addAttr(SectionAttr::CreateImplicit( 9405 Context, CodeSegStack.CurrentValue->getString(), 9406 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9407 SectionAttr::Declspec_allocate)); 9408 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9409 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9410 ASTContext::PSF_Read, 9411 NewFD)) 9412 NewFD->dropAttr<SectionAttr>(); 9413 } 9414 9415 // Apply an implicit CodeSegAttr from class declspec or 9416 // apply an implicit SectionAttr from #pragma code_seg if active. 9417 if (!NewFD->hasAttr<CodeSegAttr>()) { 9418 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9419 D.isFunctionDefinition())) { 9420 NewFD->addAttr(SAttr); 9421 } 9422 } 9423 9424 // Handle attributes. 9425 ProcessDeclAttributes(S, NewFD, D); 9426 9427 if (getLangOpts().OpenCL) { 9428 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9429 // type declaration will generate a compilation error. 9430 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9431 if (AddressSpace != LangAS::Default) { 9432 Diag(NewFD->getLocation(), 9433 diag::err_opencl_return_value_with_address_space); 9434 NewFD->setInvalidDecl(); 9435 } 9436 } 9437 9438 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9439 checkDeviceDecl(NewFD, D.getBeginLoc()); 9440 9441 if (!getLangOpts().CPlusPlus) { 9442 // Perform semantic checking on the function declaration. 9443 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9444 CheckMain(NewFD, D.getDeclSpec()); 9445 9446 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9447 CheckMSVCRTEntryPoint(NewFD); 9448 9449 if (!NewFD->isInvalidDecl()) 9450 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9451 isMemberSpecialization)); 9452 else if (!Previous.empty()) 9453 // Recover gracefully from an invalid redeclaration. 9454 D.setRedeclaration(true); 9455 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9456 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9457 "previous declaration set still overloaded"); 9458 9459 // Diagnose no-prototype function declarations with calling conventions that 9460 // don't support variadic calls. Only do this in C and do it after merging 9461 // possibly prototyped redeclarations. 9462 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9463 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9464 CallingConv CC = FT->getExtInfo().getCC(); 9465 if (!supportsVariadicCall(CC)) { 9466 // Windows system headers sometimes accidentally use stdcall without 9467 // (void) parameters, so we relax this to a warning. 9468 int DiagID = 9469 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9470 Diag(NewFD->getLocation(), DiagID) 9471 << FunctionType::getNameForCallConv(CC); 9472 } 9473 } 9474 9475 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9476 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9477 checkNonTrivialCUnion(NewFD->getReturnType(), 9478 NewFD->getReturnTypeSourceRange().getBegin(), 9479 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9480 } else { 9481 // C++11 [replacement.functions]p3: 9482 // The program's definitions shall not be specified as inline. 9483 // 9484 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9485 // 9486 // Suppress the diagnostic if the function is __attribute__((used)), since 9487 // that forces an external definition to be emitted. 9488 if (D.getDeclSpec().isInlineSpecified() && 9489 NewFD->isReplaceableGlobalAllocationFunction() && 9490 !NewFD->hasAttr<UsedAttr>()) 9491 Diag(D.getDeclSpec().getInlineSpecLoc(), 9492 diag::ext_operator_new_delete_declared_inline) 9493 << NewFD->getDeclName(); 9494 9495 // If the declarator is a template-id, translate the parser's template 9496 // argument list into our AST format. 9497 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9498 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9499 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9500 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9501 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9502 TemplateId->NumArgs); 9503 translateTemplateArguments(TemplateArgsPtr, 9504 TemplateArgs); 9505 9506 HasExplicitTemplateArgs = true; 9507 9508 if (NewFD->isInvalidDecl()) { 9509 HasExplicitTemplateArgs = false; 9510 } else if (FunctionTemplate) { 9511 // Function template with explicit template arguments. 9512 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9513 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9514 9515 HasExplicitTemplateArgs = false; 9516 } else { 9517 assert((isFunctionTemplateSpecialization || 9518 D.getDeclSpec().isFriendSpecified()) && 9519 "should have a 'template<>' for this decl"); 9520 // "friend void foo<>(int);" is an implicit specialization decl. 9521 isFunctionTemplateSpecialization = true; 9522 } 9523 } else if (isFriend && isFunctionTemplateSpecialization) { 9524 // This combination is only possible in a recovery case; the user 9525 // wrote something like: 9526 // template <> friend void foo(int); 9527 // which we're recovering from as if the user had written: 9528 // friend void foo<>(int); 9529 // Go ahead and fake up a template id. 9530 HasExplicitTemplateArgs = true; 9531 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9532 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9533 } 9534 9535 // We do not add HD attributes to specializations here because 9536 // they may have different constexpr-ness compared to their 9537 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9538 // may end up with different effective targets. Instead, a 9539 // specialization inherits its target attributes from its template 9540 // in the CheckFunctionTemplateSpecialization() call below. 9541 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9542 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9543 9544 // If it's a friend (and only if it's a friend), it's possible 9545 // that either the specialized function type or the specialized 9546 // template is dependent, and therefore matching will fail. In 9547 // this case, don't check the specialization yet. 9548 if (isFunctionTemplateSpecialization && isFriend && 9549 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9550 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9551 TemplateArgs.arguments()))) { 9552 assert(HasExplicitTemplateArgs && 9553 "friend function specialization without template args"); 9554 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9555 Previous)) 9556 NewFD->setInvalidDecl(); 9557 } else if (isFunctionTemplateSpecialization) { 9558 if (CurContext->isDependentContext() && CurContext->isRecord() 9559 && !isFriend) { 9560 isDependentClassScopeExplicitSpecialization = true; 9561 } else if (!NewFD->isInvalidDecl() && 9562 CheckFunctionTemplateSpecialization( 9563 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9564 Previous)) 9565 NewFD->setInvalidDecl(); 9566 9567 // C++ [dcl.stc]p1: 9568 // A storage-class-specifier shall not be specified in an explicit 9569 // specialization (14.7.3) 9570 FunctionTemplateSpecializationInfo *Info = 9571 NewFD->getTemplateSpecializationInfo(); 9572 if (Info && SC != SC_None) { 9573 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9574 Diag(NewFD->getLocation(), 9575 diag::err_explicit_specialization_inconsistent_storage_class) 9576 << SC 9577 << FixItHint::CreateRemoval( 9578 D.getDeclSpec().getStorageClassSpecLoc()); 9579 9580 else 9581 Diag(NewFD->getLocation(), 9582 diag::ext_explicit_specialization_storage_class) 9583 << FixItHint::CreateRemoval( 9584 D.getDeclSpec().getStorageClassSpecLoc()); 9585 } 9586 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9587 if (CheckMemberSpecialization(NewFD, Previous)) 9588 NewFD->setInvalidDecl(); 9589 } 9590 9591 // Perform semantic checking on the function declaration. 9592 if (!isDependentClassScopeExplicitSpecialization) { 9593 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9594 CheckMain(NewFD, D.getDeclSpec()); 9595 9596 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9597 CheckMSVCRTEntryPoint(NewFD); 9598 9599 if (!NewFD->isInvalidDecl()) 9600 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9601 isMemberSpecialization)); 9602 else if (!Previous.empty()) 9603 // Recover gracefully from an invalid redeclaration. 9604 D.setRedeclaration(true); 9605 } 9606 9607 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9608 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9609 "previous declaration set still overloaded"); 9610 9611 NamedDecl *PrincipalDecl = (FunctionTemplate 9612 ? cast<NamedDecl>(FunctionTemplate) 9613 : NewFD); 9614 9615 if (isFriend && NewFD->getPreviousDecl()) { 9616 AccessSpecifier Access = AS_public; 9617 if (!NewFD->isInvalidDecl()) 9618 Access = NewFD->getPreviousDecl()->getAccess(); 9619 9620 NewFD->setAccess(Access); 9621 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9622 } 9623 9624 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9625 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9626 PrincipalDecl->setNonMemberOperator(); 9627 9628 // If we have a function template, check the template parameter 9629 // list. This will check and merge default template arguments. 9630 if (FunctionTemplate) { 9631 FunctionTemplateDecl *PrevTemplate = 9632 FunctionTemplate->getPreviousDecl(); 9633 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9634 PrevTemplate ? PrevTemplate->getTemplateParameters() 9635 : nullptr, 9636 D.getDeclSpec().isFriendSpecified() 9637 ? (D.isFunctionDefinition() 9638 ? TPC_FriendFunctionTemplateDefinition 9639 : TPC_FriendFunctionTemplate) 9640 : (D.getCXXScopeSpec().isSet() && 9641 DC && DC->isRecord() && 9642 DC->isDependentContext()) 9643 ? TPC_ClassTemplateMember 9644 : TPC_FunctionTemplate); 9645 } 9646 9647 if (NewFD->isInvalidDecl()) { 9648 // Ignore all the rest of this. 9649 } else if (!D.isRedeclaration()) { 9650 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9651 AddToScope }; 9652 // Fake up an access specifier if it's supposed to be a class member. 9653 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9654 NewFD->setAccess(AS_public); 9655 9656 // Qualified decls generally require a previous declaration. 9657 if (D.getCXXScopeSpec().isSet()) { 9658 // ...with the major exception of templated-scope or 9659 // dependent-scope friend declarations. 9660 9661 // TODO: we currently also suppress this check in dependent 9662 // contexts because (1) the parameter depth will be off when 9663 // matching friend templates and (2) we might actually be 9664 // selecting a friend based on a dependent factor. But there 9665 // are situations where these conditions don't apply and we 9666 // can actually do this check immediately. 9667 // 9668 // Unless the scope is dependent, it's always an error if qualified 9669 // redeclaration lookup found nothing at all. Diagnose that now; 9670 // nothing will diagnose that error later. 9671 if (isFriend && 9672 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9673 (!Previous.empty() && CurContext->isDependentContext()))) { 9674 // ignore these 9675 } else { 9676 // The user tried to provide an out-of-line definition for a 9677 // function that is a member of a class or namespace, but there 9678 // was no such member function declared (C++ [class.mfct]p2, 9679 // C++ [namespace.memdef]p2). For example: 9680 // 9681 // class X { 9682 // void f() const; 9683 // }; 9684 // 9685 // void X::f() { } // ill-formed 9686 // 9687 // Complain about this problem, and attempt to suggest close 9688 // matches (e.g., those that differ only in cv-qualifiers and 9689 // whether the parameter types are references). 9690 9691 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9692 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9693 AddToScope = ExtraArgs.AddToScope; 9694 return Result; 9695 } 9696 } 9697 9698 // Unqualified local friend declarations are required to resolve 9699 // to something. 9700 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9701 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9702 *this, Previous, NewFD, ExtraArgs, true, S)) { 9703 AddToScope = ExtraArgs.AddToScope; 9704 return Result; 9705 } 9706 } 9707 } else if (!D.isFunctionDefinition() && 9708 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9709 !isFriend && !isFunctionTemplateSpecialization && 9710 !isMemberSpecialization) { 9711 // An out-of-line member function declaration must also be a 9712 // definition (C++ [class.mfct]p2). 9713 // Note that this is not the case for explicit specializations of 9714 // function templates or member functions of class templates, per 9715 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9716 // extension for compatibility with old SWIG code which likes to 9717 // generate them. 9718 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9719 << D.getCXXScopeSpec().getRange(); 9720 } 9721 } 9722 9723 // If this is the first declaration of a library builtin function, add 9724 // attributes as appropriate. 9725 if (!D.isRedeclaration() && 9726 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9727 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9728 if (unsigned BuiltinID = II->getBuiltinID()) { 9729 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9730 // Validate the type matches unless this builtin is specified as 9731 // matching regardless of its declared type. 9732 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9733 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9734 } else { 9735 ASTContext::GetBuiltinTypeError Error; 9736 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9737 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9738 9739 if (!Error && !BuiltinType.isNull() && 9740 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9741 NewFD->getType(), BuiltinType)) 9742 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9743 } 9744 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9745 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9746 // FIXME: We should consider this a builtin only in the std namespace. 9747 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9748 } 9749 } 9750 } 9751 } 9752 9753 ProcessPragmaWeak(S, NewFD); 9754 checkAttributesAfterMerging(*this, *NewFD); 9755 9756 AddKnownFunctionAttributes(NewFD); 9757 9758 if (NewFD->hasAttr<OverloadableAttr>() && 9759 !NewFD->getType()->getAs<FunctionProtoType>()) { 9760 Diag(NewFD->getLocation(), 9761 diag::err_attribute_overloadable_no_prototype) 9762 << NewFD; 9763 9764 // Turn this into a variadic function with no parameters. 9765 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9766 FunctionProtoType::ExtProtoInfo EPI( 9767 Context.getDefaultCallingConvention(true, false)); 9768 EPI.Variadic = true; 9769 EPI.ExtInfo = FT->getExtInfo(); 9770 9771 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9772 NewFD->setType(R); 9773 } 9774 9775 // If there's a #pragma GCC visibility in scope, and this isn't a class 9776 // member, set the visibility of this function. 9777 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9778 AddPushedVisibilityAttribute(NewFD); 9779 9780 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9781 // marking the function. 9782 AddCFAuditedAttribute(NewFD); 9783 9784 // If this is a function definition, check if we have to apply optnone due to 9785 // a pragma. 9786 if(D.isFunctionDefinition()) 9787 AddRangeBasedOptnone(NewFD); 9788 9789 // If this is the first declaration of an extern C variable, update 9790 // the map of such variables. 9791 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9792 isIncompleteDeclExternC(*this, NewFD)) 9793 RegisterLocallyScopedExternCDecl(NewFD, S); 9794 9795 // Set this FunctionDecl's range up to the right paren. 9796 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9797 9798 if (D.isRedeclaration() && !Previous.empty()) { 9799 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9800 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9801 isMemberSpecialization || 9802 isFunctionTemplateSpecialization, 9803 D.isFunctionDefinition()); 9804 } 9805 9806 if (getLangOpts().CUDA) { 9807 IdentifierInfo *II = NewFD->getIdentifier(); 9808 if (II && II->isStr(getCudaConfigureFuncName()) && 9809 !NewFD->isInvalidDecl() && 9810 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9811 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9812 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9813 << getCudaConfigureFuncName(); 9814 Context.setcudaConfigureCallDecl(NewFD); 9815 } 9816 9817 // Variadic functions, other than a *declaration* of printf, are not allowed 9818 // in device-side CUDA code, unless someone passed 9819 // -fcuda-allow-variadic-functions. 9820 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9821 (NewFD->hasAttr<CUDADeviceAttr>() || 9822 NewFD->hasAttr<CUDAGlobalAttr>()) && 9823 !(II && II->isStr("printf") && NewFD->isExternC() && 9824 !D.isFunctionDefinition())) { 9825 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9826 } 9827 } 9828 9829 MarkUnusedFileScopedDecl(NewFD); 9830 9831 9832 9833 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9834 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9835 if ((getLangOpts().OpenCLVersion >= 120) 9836 && (SC == SC_Static)) { 9837 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9838 D.setInvalidType(); 9839 } 9840 9841 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9842 if (!NewFD->getReturnType()->isVoidType()) { 9843 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9844 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9845 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9846 : FixItHint()); 9847 D.setInvalidType(); 9848 } 9849 9850 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9851 for (auto Param : NewFD->parameters()) 9852 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9853 9854 if (getLangOpts().OpenCLCPlusPlus) { 9855 if (DC->isRecord()) { 9856 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9857 D.setInvalidType(); 9858 } 9859 if (FunctionTemplate) { 9860 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9861 D.setInvalidType(); 9862 } 9863 } 9864 } 9865 9866 if (getLangOpts().CPlusPlus) { 9867 if (FunctionTemplate) { 9868 if (NewFD->isInvalidDecl()) 9869 FunctionTemplate->setInvalidDecl(); 9870 return FunctionTemplate; 9871 } 9872 9873 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9874 CompleteMemberSpecialization(NewFD, Previous); 9875 } 9876 9877 for (const ParmVarDecl *Param : NewFD->parameters()) { 9878 QualType PT = Param->getType(); 9879 9880 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9881 // types. 9882 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9883 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9884 QualType ElemTy = PipeTy->getElementType(); 9885 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9886 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9887 D.setInvalidType(); 9888 } 9889 } 9890 } 9891 } 9892 9893 // Here we have an function template explicit specialization at class scope. 9894 // The actual specialization will be postponed to template instatiation 9895 // time via the ClassScopeFunctionSpecializationDecl node. 9896 if (isDependentClassScopeExplicitSpecialization) { 9897 ClassScopeFunctionSpecializationDecl *NewSpec = 9898 ClassScopeFunctionSpecializationDecl::Create( 9899 Context, CurContext, NewFD->getLocation(), 9900 cast<CXXMethodDecl>(NewFD), 9901 HasExplicitTemplateArgs, TemplateArgs); 9902 CurContext->addDecl(NewSpec); 9903 AddToScope = false; 9904 } 9905 9906 // Diagnose availability attributes. Availability cannot be used on functions 9907 // that are run during load/unload. 9908 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9909 if (NewFD->hasAttr<ConstructorAttr>()) { 9910 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9911 << 1; 9912 NewFD->dropAttr<AvailabilityAttr>(); 9913 } 9914 if (NewFD->hasAttr<DestructorAttr>()) { 9915 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9916 << 2; 9917 NewFD->dropAttr<AvailabilityAttr>(); 9918 } 9919 } 9920 9921 // Diagnose no_builtin attribute on function declaration that are not a 9922 // definition. 9923 // FIXME: We should really be doing this in 9924 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9925 // the FunctionDecl and at this point of the code 9926 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9927 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9928 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9929 switch (D.getFunctionDefinitionKind()) { 9930 case FunctionDefinitionKind::Defaulted: 9931 case FunctionDefinitionKind::Deleted: 9932 Diag(NBA->getLocation(), 9933 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9934 << NBA->getSpelling(); 9935 break; 9936 case FunctionDefinitionKind::Declaration: 9937 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9938 << NBA->getSpelling(); 9939 break; 9940 case FunctionDefinitionKind::Definition: 9941 break; 9942 } 9943 9944 return NewFD; 9945 } 9946 9947 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9948 /// when __declspec(code_seg) "is applied to a class, all member functions of 9949 /// the class and nested classes -- this includes compiler-generated special 9950 /// member functions -- are put in the specified segment." 9951 /// The actual behavior is a little more complicated. The Microsoft compiler 9952 /// won't check outer classes if there is an active value from #pragma code_seg. 9953 /// The CodeSeg is always applied from the direct parent but only from outer 9954 /// classes when the #pragma code_seg stack is empty. See: 9955 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9956 /// available since MS has removed the page. 9957 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9958 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9959 if (!Method) 9960 return nullptr; 9961 const CXXRecordDecl *Parent = Method->getParent(); 9962 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9963 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9964 NewAttr->setImplicit(true); 9965 return NewAttr; 9966 } 9967 9968 // The Microsoft compiler won't check outer classes for the CodeSeg 9969 // when the #pragma code_seg stack is active. 9970 if (S.CodeSegStack.CurrentValue) 9971 return nullptr; 9972 9973 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9974 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9975 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9976 NewAttr->setImplicit(true); 9977 return NewAttr; 9978 } 9979 } 9980 return nullptr; 9981 } 9982 9983 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9984 /// containing class. Otherwise it will return implicit SectionAttr if the 9985 /// function is a definition and there is an active value on CodeSegStack 9986 /// (from the current #pragma code-seg value). 9987 /// 9988 /// \param FD Function being declared. 9989 /// \param IsDefinition Whether it is a definition or just a declarartion. 9990 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9991 /// nullptr if no attribute should be added. 9992 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9993 bool IsDefinition) { 9994 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9995 return A; 9996 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9997 CodeSegStack.CurrentValue) 9998 return SectionAttr::CreateImplicit( 9999 getASTContext(), CodeSegStack.CurrentValue->getString(), 10000 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10001 SectionAttr::Declspec_allocate); 10002 return nullptr; 10003 } 10004 10005 /// Determines if we can perform a correct type check for \p D as a 10006 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10007 /// best-effort check. 10008 /// 10009 /// \param NewD The new declaration. 10010 /// \param OldD The old declaration. 10011 /// \param NewT The portion of the type of the new declaration to check. 10012 /// \param OldT The portion of the type of the old declaration to check. 10013 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10014 QualType NewT, QualType OldT) { 10015 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10016 return true; 10017 10018 // For dependently-typed local extern declarations and friends, we can't 10019 // perform a correct type check in general until instantiation: 10020 // 10021 // int f(); 10022 // template<typename T> void g() { T f(); } 10023 // 10024 // (valid if g() is only instantiated with T = int). 10025 if (NewT->isDependentType() && 10026 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10027 return false; 10028 10029 // Similarly, if the previous declaration was a dependent local extern 10030 // declaration, we don't really know its type yet. 10031 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10032 return false; 10033 10034 return true; 10035 } 10036 10037 /// Checks if the new declaration declared in dependent context must be 10038 /// put in the same redeclaration chain as the specified declaration. 10039 /// 10040 /// \param D Declaration that is checked. 10041 /// \param PrevDecl Previous declaration found with proper lookup method for the 10042 /// same declaration name. 10043 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10044 /// belongs to. 10045 /// 10046 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10047 if (!D->getLexicalDeclContext()->isDependentContext()) 10048 return true; 10049 10050 // Don't chain dependent friend function definitions until instantiation, to 10051 // permit cases like 10052 // 10053 // void func(); 10054 // template<typename T> class C1 { friend void func() {} }; 10055 // template<typename T> class C2 { friend void func() {} }; 10056 // 10057 // ... which is valid if only one of C1 and C2 is ever instantiated. 10058 // 10059 // FIXME: This need only apply to function definitions. For now, we proxy 10060 // this by checking for a file-scope function. We do not want this to apply 10061 // to friend declarations nominating member functions, because that gets in 10062 // the way of access checks. 10063 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10064 return false; 10065 10066 auto *VD = dyn_cast<ValueDecl>(D); 10067 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10068 return !VD || !PrevVD || 10069 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10070 PrevVD->getType()); 10071 } 10072 10073 /// Check the target attribute of the function for MultiVersion 10074 /// validity. 10075 /// 10076 /// Returns true if there was an error, false otherwise. 10077 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10078 const auto *TA = FD->getAttr<TargetAttr>(); 10079 assert(TA && "MultiVersion Candidate requires a target attribute"); 10080 ParsedTargetAttr ParseInfo = TA->parse(); 10081 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10082 enum ErrType { Feature = 0, Architecture = 1 }; 10083 10084 if (!ParseInfo.Architecture.empty() && 10085 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10086 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10087 << Architecture << ParseInfo.Architecture; 10088 return true; 10089 } 10090 10091 for (const auto &Feat : ParseInfo.Features) { 10092 auto BareFeat = StringRef{Feat}.substr(1); 10093 if (Feat[0] == '-') { 10094 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10095 << Feature << ("no-" + BareFeat).str(); 10096 return true; 10097 } 10098 10099 if (!TargetInfo.validateCpuSupports(BareFeat) || 10100 !TargetInfo.isValidFeatureName(BareFeat)) { 10101 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10102 << Feature << BareFeat; 10103 return true; 10104 } 10105 } 10106 return false; 10107 } 10108 10109 // Provide a white-list of attributes that are allowed to be combined with 10110 // multiversion functions. 10111 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10112 MultiVersionKind MVType) { 10113 // Note: this list/diagnosis must match the list in 10114 // checkMultiversionAttributesAllSame. 10115 switch (Kind) { 10116 default: 10117 return false; 10118 case attr::Used: 10119 return MVType == MultiVersionKind::Target; 10120 case attr::NonNull: 10121 case attr::NoThrow: 10122 return true; 10123 } 10124 } 10125 10126 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10127 const FunctionDecl *FD, 10128 const FunctionDecl *CausedFD, 10129 MultiVersionKind MVType) { 10130 bool IsCPUSpecificCPUDispatchMVType = 10131 MVType == MultiVersionKind::CPUDispatch || 10132 MVType == MultiVersionKind::CPUSpecific; 10133 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10134 Sema &S, const Attr *A) { 10135 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10136 << IsCPUSpecificCPUDispatchMVType << A; 10137 if (CausedFD) 10138 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10139 return true; 10140 }; 10141 10142 for (const Attr *A : FD->attrs()) { 10143 switch (A->getKind()) { 10144 case attr::CPUDispatch: 10145 case attr::CPUSpecific: 10146 if (MVType != MultiVersionKind::CPUDispatch && 10147 MVType != MultiVersionKind::CPUSpecific) 10148 return Diagnose(S, A); 10149 break; 10150 case attr::Target: 10151 if (MVType != MultiVersionKind::Target) 10152 return Diagnose(S, A); 10153 break; 10154 default: 10155 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10156 return Diagnose(S, A); 10157 break; 10158 } 10159 } 10160 return false; 10161 } 10162 10163 bool Sema::areMultiversionVariantFunctionsCompatible( 10164 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10165 const PartialDiagnostic &NoProtoDiagID, 10166 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10167 const PartialDiagnosticAt &NoSupportDiagIDAt, 10168 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10169 bool ConstexprSupported, bool CLinkageMayDiffer) { 10170 enum DoesntSupport { 10171 FuncTemplates = 0, 10172 VirtFuncs = 1, 10173 DeducedReturn = 2, 10174 Constructors = 3, 10175 Destructors = 4, 10176 DeletedFuncs = 5, 10177 DefaultedFuncs = 6, 10178 ConstexprFuncs = 7, 10179 ConstevalFuncs = 8, 10180 }; 10181 enum Different { 10182 CallingConv = 0, 10183 ReturnType = 1, 10184 ConstexprSpec = 2, 10185 InlineSpec = 3, 10186 StorageClass = 4, 10187 Linkage = 5, 10188 }; 10189 10190 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10191 !OldFD->getType()->getAs<FunctionProtoType>()) { 10192 Diag(OldFD->getLocation(), NoProtoDiagID); 10193 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10194 return true; 10195 } 10196 10197 if (NoProtoDiagID.getDiagID() != 0 && 10198 !NewFD->getType()->getAs<FunctionProtoType>()) 10199 return Diag(NewFD->getLocation(), NoProtoDiagID); 10200 10201 if (!TemplatesSupported && 10202 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10203 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10204 << FuncTemplates; 10205 10206 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10207 if (NewCXXFD->isVirtual()) 10208 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10209 << VirtFuncs; 10210 10211 if (isa<CXXConstructorDecl>(NewCXXFD)) 10212 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10213 << Constructors; 10214 10215 if (isa<CXXDestructorDecl>(NewCXXFD)) 10216 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10217 << Destructors; 10218 } 10219 10220 if (NewFD->isDeleted()) 10221 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10222 << DeletedFuncs; 10223 10224 if (NewFD->isDefaulted()) 10225 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10226 << DefaultedFuncs; 10227 10228 if (!ConstexprSupported && NewFD->isConstexpr()) 10229 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10230 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10231 10232 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10233 const auto *NewType = cast<FunctionType>(NewQType); 10234 QualType NewReturnType = NewType->getReturnType(); 10235 10236 if (NewReturnType->isUndeducedType()) 10237 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10238 << DeducedReturn; 10239 10240 // Ensure the return type is identical. 10241 if (OldFD) { 10242 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10243 const auto *OldType = cast<FunctionType>(OldQType); 10244 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10245 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10246 10247 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10248 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10249 10250 QualType OldReturnType = OldType->getReturnType(); 10251 10252 if (OldReturnType != NewReturnType) 10253 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10254 10255 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10256 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10257 10258 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10259 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10260 10261 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10262 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10263 10264 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10265 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10266 10267 if (CheckEquivalentExceptionSpec( 10268 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10269 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10270 return true; 10271 } 10272 return false; 10273 } 10274 10275 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10276 const FunctionDecl *NewFD, 10277 bool CausesMV, 10278 MultiVersionKind MVType) { 10279 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10280 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10281 if (OldFD) 10282 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10283 return true; 10284 } 10285 10286 bool IsCPUSpecificCPUDispatchMVType = 10287 MVType == MultiVersionKind::CPUDispatch || 10288 MVType == MultiVersionKind::CPUSpecific; 10289 10290 if (CausesMV && OldFD && 10291 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10292 return true; 10293 10294 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10295 return true; 10296 10297 // Only allow transition to MultiVersion if it hasn't been used. 10298 if (OldFD && CausesMV && OldFD->isUsed(false)) 10299 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10300 10301 return S.areMultiversionVariantFunctionsCompatible( 10302 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10303 PartialDiagnosticAt(NewFD->getLocation(), 10304 S.PDiag(diag::note_multiversioning_caused_here)), 10305 PartialDiagnosticAt(NewFD->getLocation(), 10306 S.PDiag(diag::err_multiversion_doesnt_support) 10307 << IsCPUSpecificCPUDispatchMVType), 10308 PartialDiagnosticAt(NewFD->getLocation(), 10309 S.PDiag(diag::err_multiversion_diff)), 10310 /*TemplatesSupported=*/false, 10311 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10312 /*CLinkageMayDiffer=*/false); 10313 } 10314 10315 /// Check the validity of a multiversion function declaration that is the 10316 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10317 /// 10318 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10319 /// 10320 /// Returns true if there was an error, false otherwise. 10321 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10322 MultiVersionKind MVType, 10323 const TargetAttr *TA) { 10324 assert(MVType != MultiVersionKind::None && 10325 "Function lacks multiversion attribute"); 10326 10327 // Target only causes MV if it is default, otherwise this is a normal 10328 // function. 10329 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10330 return false; 10331 10332 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10333 FD->setInvalidDecl(); 10334 return true; 10335 } 10336 10337 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10338 FD->setInvalidDecl(); 10339 return true; 10340 } 10341 10342 FD->setIsMultiVersion(); 10343 return false; 10344 } 10345 10346 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10347 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10348 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10349 return true; 10350 } 10351 10352 return false; 10353 } 10354 10355 static bool CheckTargetCausesMultiVersioning( 10356 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10357 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10358 LookupResult &Previous) { 10359 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10360 ParsedTargetAttr NewParsed = NewTA->parse(); 10361 // Sort order doesn't matter, it just needs to be consistent. 10362 llvm::sort(NewParsed.Features); 10363 10364 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10365 // to change, this is a simple redeclaration. 10366 if (!NewTA->isDefaultVersion() && 10367 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10368 return false; 10369 10370 // Otherwise, this decl causes MultiVersioning. 10371 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10372 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10373 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10374 NewFD->setInvalidDecl(); 10375 return true; 10376 } 10377 10378 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10379 MultiVersionKind::Target)) { 10380 NewFD->setInvalidDecl(); 10381 return true; 10382 } 10383 10384 if (CheckMultiVersionValue(S, NewFD)) { 10385 NewFD->setInvalidDecl(); 10386 return true; 10387 } 10388 10389 // If this is 'default', permit the forward declaration. 10390 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10391 Redeclaration = true; 10392 OldDecl = OldFD; 10393 OldFD->setIsMultiVersion(); 10394 NewFD->setIsMultiVersion(); 10395 return false; 10396 } 10397 10398 if (CheckMultiVersionValue(S, OldFD)) { 10399 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10400 NewFD->setInvalidDecl(); 10401 return true; 10402 } 10403 10404 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10405 10406 if (OldParsed == NewParsed) { 10407 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10408 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10409 NewFD->setInvalidDecl(); 10410 return true; 10411 } 10412 10413 for (const auto *FD : OldFD->redecls()) { 10414 const auto *CurTA = FD->getAttr<TargetAttr>(); 10415 // We allow forward declarations before ANY multiversioning attributes, but 10416 // nothing after the fact. 10417 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10418 (!CurTA || CurTA->isInherited())) { 10419 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10420 << 0; 10421 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10422 NewFD->setInvalidDecl(); 10423 return true; 10424 } 10425 } 10426 10427 OldFD->setIsMultiVersion(); 10428 NewFD->setIsMultiVersion(); 10429 Redeclaration = false; 10430 MergeTypeWithPrevious = false; 10431 OldDecl = nullptr; 10432 Previous.clear(); 10433 return false; 10434 } 10435 10436 /// Check the validity of a new function declaration being added to an existing 10437 /// multiversioned declaration collection. 10438 static bool CheckMultiVersionAdditionalDecl( 10439 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10440 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10441 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10442 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10443 LookupResult &Previous) { 10444 10445 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10446 // Disallow mixing of multiversioning types. 10447 if ((OldMVType == MultiVersionKind::Target && 10448 NewMVType != MultiVersionKind::Target) || 10449 (NewMVType == MultiVersionKind::Target && 10450 OldMVType != MultiVersionKind::Target)) { 10451 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10452 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10453 NewFD->setInvalidDecl(); 10454 return true; 10455 } 10456 10457 ParsedTargetAttr NewParsed; 10458 if (NewTA) { 10459 NewParsed = NewTA->parse(); 10460 llvm::sort(NewParsed.Features); 10461 } 10462 10463 bool UseMemberUsingDeclRules = 10464 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10465 10466 // Next, check ALL non-overloads to see if this is a redeclaration of a 10467 // previous member of the MultiVersion set. 10468 for (NamedDecl *ND : Previous) { 10469 FunctionDecl *CurFD = ND->getAsFunction(); 10470 if (!CurFD) 10471 continue; 10472 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10473 continue; 10474 10475 if (NewMVType == MultiVersionKind::Target) { 10476 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10477 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10478 NewFD->setIsMultiVersion(); 10479 Redeclaration = true; 10480 OldDecl = ND; 10481 return false; 10482 } 10483 10484 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10485 if (CurParsed == NewParsed) { 10486 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10487 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10488 NewFD->setInvalidDecl(); 10489 return true; 10490 } 10491 } else { 10492 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10493 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10494 // Handle CPUDispatch/CPUSpecific versions. 10495 // Only 1 CPUDispatch function is allowed, this will make it go through 10496 // the redeclaration errors. 10497 if (NewMVType == MultiVersionKind::CPUDispatch && 10498 CurFD->hasAttr<CPUDispatchAttr>()) { 10499 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10500 std::equal( 10501 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10502 NewCPUDisp->cpus_begin(), 10503 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10504 return Cur->getName() == New->getName(); 10505 })) { 10506 NewFD->setIsMultiVersion(); 10507 Redeclaration = true; 10508 OldDecl = ND; 10509 return false; 10510 } 10511 10512 // If the declarations don't match, this is an error condition. 10513 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10514 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10515 NewFD->setInvalidDecl(); 10516 return true; 10517 } 10518 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10519 10520 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10521 std::equal( 10522 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10523 NewCPUSpec->cpus_begin(), 10524 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10525 return Cur->getName() == New->getName(); 10526 })) { 10527 NewFD->setIsMultiVersion(); 10528 Redeclaration = true; 10529 OldDecl = ND; 10530 return false; 10531 } 10532 10533 // Only 1 version of CPUSpecific is allowed for each CPU. 10534 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10535 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10536 if (CurII == NewII) { 10537 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10538 << NewII; 10539 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10540 NewFD->setInvalidDecl(); 10541 return true; 10542 } 10543 } 10544 } 10545 } 10546 // If the two decls aren't the same MVType, there is no possible error 10547 // condition. 10548 } 10549 } 10550 10551 // Else, this is simply a non-redecl case. Checking the 'value' is only 10552 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10553 // handled in the attribute adding step. 10554 if (NewMVType == MultiVersionKind::Target && 10555 CheckMultiVersionValue(S, NewFD)) { 10556 NewFD->setInvalidDecl(); 10557 return true; 10558 } 10559 10560 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10561 !OldFD->isMultiVersion(), NewMVType)) { 10562 NewFD->setInvalidDecl(); 10563 return true; 10564 } 10565 10566 // Permit forward declarations in the case where these two are compatible. 10567 if (!OldFD->isMultiVersion()) { 10568 OldFD->setIsMultiVersion(); 10569 NewFD->setIsMultiVersion(); 10570 Redeclaration = true; 10571 OldDecl = OldFD; 10572 return false; 10573 } 10574 10575 NewFD->setIsMultiVersion(); 10576 Redeclaration = false; 10577 MergeTypeWithPrevious = false; 10578 OldDecl = nullptr; 10579 Previous.clear(); 10580 return false; 10581 } 10582 10583 10584 /// Check the validity of a mulitversion function declaration. 10585 /// Also sets the multiversion'ness' of the function itself. 10586 /// 10587 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10588 /// 10589 /// Returns true if there was an error, false otherwise. 10590 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10591 bool &Redeclaration, NamedDecl *&OldDecl, 10592 bool &MergeTypeWithPrevious, 10593 LookupResult &Previous) { 10594 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10595 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10596 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10597 10598 // Mixing Multiversioning types is prohibited. 10599 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10600 (NewCPUDisp && NewCPUSpec)) { 10601 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10602 NewFD->setInvalidDecl(); 10603 return true; 10604 } 10605 10606 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10607 10608 // Main isn't allowed to become a multiversion function, however it IS 10609 // permitted to have 'main' be marked with the 'target' optimization hint. 10610 if (NewFD->isMain()) { 10611 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10612 MVType == MultiVersionKind::CPUDispatch || 10613 MVType == MultiVersionKind::CPUSpecific) { 10614 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10615 NewFD->setInvalidDecl(); 10616 return true; 10617 } 10618 return false; 10619 } 10620 10621 if (!OldDecl || !OldDecl->getAsFunction() || 10622 OldDecl->getDeclContext()->getRedeclContext() != 10623 NewFD->getDeclContext()->getRedeclContext()) { 10624 // If there's no previous declaration, AND this isn't attempting to cause 10625 // multiversioning, this isn't an error condition. 10626 if (MVType == MultiVersionKind::None) 10627 return false; 10628 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10629 } 10630 10631 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10632 10633 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10634 return false; 10635 10636 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10637 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10638 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10639 NewFD->setInvalidDecl(); 10640 return true; 10641 } 10642 10643 // Handle the target potentially causes multiversioning case. 10644 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10645 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10646 Redeclaration, OldDecl, 10647 MergeTypeWithPrevious, Previous); 10648 10649 // At this point, we have a multiversion function decl (in OldFD) AND an 10650 // appropriate attribute in the current function decl. Resolve that these are 10651 // still compatible with previous declarations. 10652 return CheckMultiVersionAdditionalDecl( 10653 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10654 OldDecl, MergeTypeWithPrevious, Previous); 10655 } 10656 10657 /// Perform semantic checking of a new function declaration. 10658 /// 10659 /// Performs semantic analysis of the new function declaration 10660 /// NewFD. This routine performs all semantic checking that does not 10661 /// require the actual declarator involved in the declaration, and is 10662 /// used both for the declaration of functions as they are parsed 10663 /// (called via ActOnDeclarator) and for the declaration of functions 10664 /// that have been instantiated via C++ template instantiation (called 10665 /// via InstantiateDecl). 10666 /// 10667 /// \param IsMemberSpecialization whether this new function declaration is 10668 /// a member specialization (that replaces any definition provided by the 10669 /// previous declaration). 10670 /// 10671 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10672 /// 10673 /// \returns true if the function declaration is a redeclaration. 10674 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10675 LookupResult &Previous, 10676 bool IsMemberSpecialization) { 10677 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10678 "Variably modified return types are not handled here"); 10679 10680 // Determine whether the type of this function should be merged with 10681 // a previous visible declaration. This never happens for functions in C++, 10682 // and always happens in C if the previous declaration was visible. 10683 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10684 !Previous.isShadowed(); 10685 10686 bool Redeclaration = false; 10687 NamedDecl *OldDecl = nullptr; 10688 bool MayNeedOverloadableChecks = false; 10689 10690 // Merge or overload the declaration with an existing declaration of 10691 // the same name, if appropriate. 10692 if (!Previous.empty()) { 10693 // Determine whether NewFD is an overload of PrevDecl or 10694 // a declaration that requires merging. If it's an overload, 10695 // there's no more work to do here; we'll just add the new 10696 // function to the scope. 10697 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10698 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10699 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10700 Redeclaration = true; 10701 OldDecl = Candidate; 10702 } 10703 } else { 10704 MayNeedOverloadableChecks = true; 10705 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10706 /*NewIsUsingDecl*/ false)) { 10707 case Ovl_Match: 10708 Redeclaration = true; 10709 break; 10710 10711 case Ovl_NonFunction: 10712 Redeclaration = true; 10713 break; 10714 10715 case Ovl_Overload: 10716 Redeclaration = false; 10717 break; 10718 } 10719 } 10720 } 10721 10722 // Check for a previous extern "C" declaration with this name. 10723 if (!Redeclaration && 10724 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10725 if (!Previous.empty()) { 10726 // This is an extern "C" declaration with the same name as a previous 10727 // declaration, and thus redeclares that entity... 10728 Redeclaration = true; 10729 OldDecl = Previous.getFoundDecl(); 10730 MergeTypeWithPrevious = false; 10731 10732 // ... except in the presence of __attribute__((overloadable)). 10733 if (OldDecl->hasAttr<OverloadableAttr>() || 10734 NewFD->hasAttr<OverloadableAttr>()) { 10735 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10736 MayNeedOverloadableChecks = true; 10737 Redeclaration = false; 10738 OldDecl = nullptr; 10739 } 10740 } 10741 } 10742 } 10743 10744 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10745 MergeTypeWithPrevious, Previous)) 10746 return Redeclaration; 10747 10748 // PPC MMA non-pointer types are not allowed as function return types. 10749 if (Context.getTargetInfo().getTriple().isPPC64() && 10750 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10751 NewFD->setInvalidDecl(); 10752 } 10753 10754 // C++11 [dcl.constexpr]p8: 10755 // A constexpr specifier for a non-static member function that is not 10756 // a constructor declares that member function to be const. 10757 // 10758 // This needs to be delayed until we know whether this is an out-of-line 10759 // definition of a static member function. 10760 // 10761 // This rule is not present in C++1y, so we produce a backwards 10762 // compatibility warning whenever it happens in C++11. 10763 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10764 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10765 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10766 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10767 CXXMethodDecl *OldMD = nullptr; 10768 if (OldDecl) 10769 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10770 if (!OldMD || !OldMD->isStatic()) { 10771 const FunctionProtoType *FPT = 10772 MD->getType()->castAs<FunctionProtoType>(); 10773 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10774 EPI.TypeQuals.addConst(); 10775 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10776 FPT->getParamTypes(), EPI)); 10777 10778 // Warn that we did this, if we're not performing template instantiation. 10779 // In that case, we'll have warned already when the template was defined. 10780 if (!inTemplateInstantiation()) { 10781 SourceLocation AddConstLoc; 10782 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10783 .IgnoreParens().getAs<FunctionTypeLoc>()) 10784 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10785 10786 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10787 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10788 } 10789 } 10790 } 10791 10792 if (Redeclaration) { 10793 // NewFD and OldDecl represent declarations that need to be 10794 // merged. 10795 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10796 NewFD->setInvalidDecl(); 10797 return Redeclaration; 10798 } 10799 10800 Previous.clear(); 10801 Previous.addDecl(OldDecl); 10802 10803 if (FunctionTemplateDecl *OldTemplateDecl = 10804 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10805 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10806 FunctionTemplateDecl *NewTemplateDecl 10807 = NewFD->getDescribedFunctionTemplate(); 10808 assert(NewTemplateDecl && "Template/non-template mismatch"); 10809 10810 // The call to MergeFunctionDecl above may have created some state in 10811 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10812 // can add it as a redeclaration. 10813 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10814 10815 NewFD->setPreviousDeclaration(OldFD); 10816 if (NewFD->isCXXClassMember()) { 10817 NewFD->setAccess(OldTemplateDecl->getAccess()); 10818 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10819 } 10820 10821 // If this is an explicit specialization of a member that is a function 10822 // template, mark it as a member specialization. 10823 if (IsMemberSpecialization && 10824 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10825 NewTemplateDecl->setMemberSpecialization(); 10826 assert(OldTemplateDecl->isMemberSpecialization()); 10827 // Explicit specializations of a member template do not inherit deleted 10828 // status from the parent member template that they are specializing. 10829 if (OldFD->isDeleted()) { 10830 // FIXME: This assert will not hold in the presence of modules. 10831 assert(OldFD->getCanonicalDecl() == OldFD); 10832 // FIXME: We need an update record for this AST mutation. 10833 OldFD->setDeletedAsWritten(false); 10834 } 10835 } 10836 10837 } else { 10838 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10839 auto *OldFD = cast<FunctionDecl>(OldDecl); 10840 // This needs to happen first so that 'inline' propagates. 10841 NewFD->setPreviousDeclaration(OldFD); 10842 if (NewFD->isCXXClassMember()) 10843 NewFD->setAccess(OldFD->getAccess()); 10844 } 10845 } 10846 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10847 !NewFD->getAttr<OverloadableAttr>()) { 10848 assert((Previous.empty() || 10849 llvm::any_of(Previous, 10850 [](const NamedDecl *ND) { 10851 return ND->hasAttr<OverloadableAttr>(); 10852 })) && 10853 "Non-redecls shouldn't happen without overloadable present"); 10854 10855 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10856 const auto *FD = dyn_cast<FunctionDecl>(ND); 10857 return FD && !FD->hasAttr<OverloadableAttr>(); 10858 }); 10859 10860 if (OtherUnmarkedIter != Previous.end()) { 10861 Diag(NewFD->getLocation(), 10862 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10863 Diag((*OtherUnmarkedIter)->getLocation(), 10864 diag::note_attribute_overloadable_prev_overload) 10865 << false; 10866 10867 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10868 } 10869 } 10870 10871 if (LangOpts.OpenMP) 10872 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10873 10874 // Semantic checking for this function declaration (in isolation). 10875 10876 if (getLangOpts().CPlusPlus) { 10877 // C++-specific checks. 10878 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10879 CheckConstructor(Constructor); 10880 } else if (CXXDestructorDecl *Destructor = 10881 dyn_cast<CXXDestructorDecl>(NewFD)) { 10882 CXXRecordDecl *Record = Destructor->getParent(); 10883 QualType ClassType = Context.getTypeDeclType(Record); 10884 10885 // FIXME: Shouldn't we be able to perform this check even when the class 10886 // type is dependent? Both gcc and edg can handle that. 10887 if (!ClassType->isDependentType()) { 10888 DeclarationName Name 10889 = Context.DeclarationNames.getCXXDestructorName( 10890 Context.getCanonicalType(ClassType)); 10891 if (NewFD->getDeclName() != Name) { 10892 Diag(NewFD->getLocation(), diag::err_destructor_name); 10893 NewFD->setInvalidDecl(); 10894 return Redeclaration; 10895 } 10896 } 10897 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10898 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10899 CheckDeductionGuideTemplate(TD); 10900 10901 // A deduction guide is not on the list of entities that can be 10902 // explicitly specialized. 10903 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10904 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10905 << /*explicit specialization*/ 1; 10906 } 10907 10908 // Find any virtual functions that this function overrides. 10909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10910 if (!Method->isFunctionTemplateSpecialization() && 10911 !Method->getDescribedFunctionTemplate() && 10912 Method->isCanonicalDecl()) { 10913 AddOverriddenMethods(Method->getParent(), Method); 10914 } 10915 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10916 // C++2a [class.virtual]p6 10917 // A virtual method shall not have a requires-clause. 10918 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10919 diag::err_constrained_virtual_method); 10920 10921 if (Method->isStatic()) 10922 checkThisInStaticMemberFunctionType(Method); 10923 } 10924 10925 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10926 ActOnConversionDeclarator(Conversion); 10927 10928 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10929 if (NewFD->isOverloadedOperator() && 10930 CheckOverloadedOperatorDeclaration(NewFD)) { 10931 NewFD->setInvalidDecl(); 10932 return Redeclaration; 10933 } 10934 10935 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10936 if (NewFD->getLiteralIdentifier() && 10937 CheckLiteralOperatorDeclaration(NewFD)) { 10938 NewFD->setInvalidDecl(); 10939 return Redeclaration; 10940 } 10941 10942 // In C++, check default arguments now that we have merged decls. Unless 10943 // the lexical context is the class, because in this case this is done 10944 // during delayed parsing anyway. 10945 if (!CurContext->isRecord()) 10946 CheckCXXDefaultArguments(NewFD); 10947 10948 // If this function declares a builtin function, check the type of this 10949 // declaration against the expected type for the builtin. 10950 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10951 ASTContext::GetBuiltinTypeError Error; 10952 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10953 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10954 // If the type of the builtin differs only in its exception 10955 // specification, that's OK. 10956 // FIXME: If the types do differ in this way, it would be better to 10957 // retain the 'noexcept' form of the type. 10958 if (!T.isNull() && 10959 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10960 NewFD->getType())) 10961 // The type of this function differs from the type of the builtin, 10962 // so forget about the builtin entirely. 10963 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10964 } 10965 10966 // If this function is declared as being extern "C", then check to see if 10967 // the function returns a UDT (class, struct, or union type) that is not C 10968 // compatible, and if it does, warn the user. 10969 // But, issue any diagnostic on the first declaration only. 10970 if (Previous.empty() && NewFD->isExternC()) { 10971 QualType R = NewFD->getReturnType(); 10972 if (R->isIncompleteType() && !R->isVoidType()) 10973 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10974 << NewFD << R; 10975 else if (!R.isPODType(Context) && !R->isVoidType() && 10976 !R->isObjCObjectPointerType()) 10977 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10978 } 10979 10980 // C++1z [dcl.fct]p6: 10981 // [...] whether the function has a non-throwing exception-specification 10982 // [is] part of the function type 10983 // 10984 // This results in an ABI break between C++14 and C++17 for functions whose 10985 // declared type includes an exception-specification in a parameter or 10986 // return type. (Exception specifications on the function itself are OK in 10987 // most cases, and exception specifications are not permitted in most other 10988 // contexts where they could make it into a mangling.) 10989 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10990 auto HasNoexcept = [&](QualType T) -> bool { 10991 // Strip off declarator chunks that could be between us and a function 10992 // type. We don't need to look far, exception specifications are very 10993 // restricted prior to C++17. 10994 if (auto *RT = T->getAs<ReferenceType>()) 10995 T = RT->getPointeeType(); 10996 else if (T->isAnyPointerType()) 10997 T = T->getPointeeType(); 10998 else if (auto *MPT = T->getAs<MemberPointerType>()) 10999 T = MPT->getPointeeType(); 11000 if (auto *FPT = T->getAs<FunctionProtoType>()) 11001 if (FPT->isNothrow()) 11002 return true; 11003 return false; 11004 }; 11005 11006 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11007 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11008 for (QualType T : FPT->param_types()) 11009 AnyNoexcept |= HasNoexcept(T); 11010 if (AnyNoexcept) 11011 Diag(NewFD->getLocation(), 11012 diag::warn_cxx17_compat_exception_spec_in_signature) 11013 << NewFD; 11014 } 11015 11016 if (!Redeclaration && LangOpts.CUDA) 11017 checkCUDATargetOverload(NewFD, Previous); 11018 } 11019 return Redeclaration; 11020 } 11021 11022 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11023 // C++11 [basic.start.main]p3: 11024 // A program that [...] declares main to be inline, static or 11025 // constexpr is ill-formed. 11026 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11027 // appear in a declaration of main. 11028 // static main is not an error under C99, but we should warn about it. 11029 // We accept _Noreturn main as an extension. 11030 if (FD->getStorageClass() == SC_Static) 11031 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11032 ? diag::err_static_main : diag::warn_static_main) 11033 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11034 if (FD->isInlineSpecified()) 11035 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11036 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11037 if (DS.isNoreturnSpecified()) { 11038 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11039 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11040 Diag(NoreturnLoc, diag::ext_noreturn_main); 11041 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11042 << FixItHint::CreateRemoval(NoreturnRange); 11043 } 11044 if (FD->isConstexpr()) { 11045 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11046 << FD->isConsteval() 11047 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11048 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11049 } 11050 11051 if (getLangOpts().OpenCL) { 11052 Diag(FD->getLocation(), diag::err_opencl_no_main) 11053 << FD->hasAttr<OpenCLKernelAttr>(); 11054 FD->setInvalidDecl(); 11055 return; 11056 } 11057 11058 QualType T = FD->getType(); 11059 assert(T->isFunctionType() && "function decl is not of function type"); 11060 const FunctionType* FT = T->castAs<FunctionType>(); 11061 11062 // Set default calling convention for main() 11063 if (FT->getCallConv() != CC_C) { 11064 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11065 FD->setType(QualType(FT, 0)); 11066 T = Context.getCanonicalType(FD->getType()); 11067 } 11068 11069 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11070 // In C with GNU extensions we allow main() to have non-integer return 11071 // type, but we should warn about the extension, and we disable the 11072 // implicit-return-zero rule. 11073 11074 // GCC in C mode accepts qualified 'int'. 11075 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11076 FD->setHasImplicitReturnZero(true); 11077 else { 11078 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11079 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11080 if (RTRange.isValid()) 11081 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11082 << FixItHint::CreateReplacement(RTRange, "int"); 11083 } 11084 } else { 11085 // In C and C++, main magically returns 0 if you fall off the end; 11086 // set the flag which tells us that. 11087 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11088 11089 // All the standards say that main() should return 'int'. 11090 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11091 FD->setHasImplicitReturnZero(true); 11092 else { 11093 // Otherwise, this is just a flat-out error. 11094 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11095 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11096 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11097 : FixItHint()); 11098 FD->setInvalidDecl(true); 11099 } 11100 } 11101 11102 // Treat protoless main() as nullary. 11103 if (isa<FunctionNoProtoType>(FT)) return; 11104 11105 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11106 unsigned nparams = FTP->getNumParams(); 11107 assert(FD->getNumParams() == nparams); 11108 11109 bool HasExtraParameters = (nparams > 3); 11110 11111 if (FTP->isVariadic()) { 11112 Diag(FD->getLocation(), diag::ext_variadic_main); 11113 // FIXME: if we had information about the location of the ellipsis, we 11114 // could add a FixIt hint to remove it as a parameter. 11115 } 11116 11117 // Darwin passes an undocumented fourth argument of type char**. If 11118 // other platforms start sprouting these, the logic below will start 11119 // getting shifty. 11120 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11121 HasExtraParameters = false; 11122 11123 if (HasExtraParameters) { 11124 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11125 FD->setInvalidDecl(true); 11126 nparams = 3; 11127 } 11128 11129 // FIXME: a lot of the following diagnostics would be improved 11130 // if we had some location information about types. 11131 11132 QualType CharPP = 11133 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11134 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11135 11136 for (unsigned i = 0; i < nparams; ++i) { 11137 QualType AT = FTP->getParamType(i); 11138 11139 bool mismatch = true; 11140 11141 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11142 mismatch = false; 11143 else if (Expected[i] == CharPP) { 11144 // As an extension, the following forms are okay: 11145 // char const ** 11146 // char const * const * 11147 // char * const * 11148 11149 QualifierCollector qs; 11150 const PointerType* PT; 11151 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11152 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11153 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11154 Context.CharTy)) { 11155 qs.removeConst(); 11156 mismatch = !qs.empty(); 11157 } 11158 } 11159 11160 if (mismatch) { 11161 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11162 // TODO: suggest replacing given type with expected type 11163 FD->setInvalidDecl(true); 11164 } 11165 } 11166 11167 if (nparams == 1 && !FD->isInvalidDecl()) { 11168 Diag(FD->getLocation(), diag::warn_main_one_arg); 11169 } 11170 11171 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11172 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11173 FD->setInvalidDecl(); 11174 } 11175 } 11176 11177 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11178 11179 // Default calling convention for main and wmain is __cdecl 11180 if (FD->getName() == "main" || FD->getName() == "wmain") 11181 return false; 11182 11183 // Default calling convention for MinGW is __cdecl 11184 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11185 if (T.isWindowsGNUEnvironment()) 11186 return false; 11187 11188 // Default calling convention for WinMain, wWinMain and DllMain 11189 // is __stdcall on 32 bit Windows 11190 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11191 return true; 11192 11193 return false; 11194 } 11195 11196 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11197 QualType T = FD->getType(); 11198 assert(T->isFunctionType() && "function decl is not of function type"); 11199 const FunctionType *FT = T->castAs<FunctionType>(); 11200 11201 // Set an implicit return of 'zero' if the function can return some integral, 11202 // enumeration, pointer or nullptr type. 11203 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11204 FT->getReturnType()->isAnyPointerType() || 11205 FT->getReturnType()->isNullPtrType()) 11206 // DllMain is exempt because a return value of zero means it failed. 11207 if (FD->getName() != "DllMain") 11208 FD->setHasImplicitReturnZero(true); 11209 11210 // Explicity specified calling conventions are applied to MSVC entry points 11211 if (!hasExplicitCallingConv(T)) { 11212 if (isDefaultStdCall(FD, *this)) { 11213 if (FT->getCallConv() != CC_X86StdCall) { 11214 FT = Context.adjustFunctionType( 11215 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11216 FD->setType(QualType(FT, 0)); 11217 } 11218 } else if (FT->getCallConv() != CC_C) { 11219 FT = Context.adjustFunctionType(FT, 11220 FT->getExtInfo().withCallingConv(CC_C)); 11221 FD->setType(QualType(FT, 0)); 11222 } 11223 } 11224 11225 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11226 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11227 FD->setInvalidDecl(); 11228 } 11229 } 11230 11231 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11232 // FIXME: Need strict checking. In C89, we need to check for 11233 // any assignment, increment, decrement, function-calls, or 11234 // commas outside of a sizeof. In C99, it's the same list, 11235 // except that the aforementioned are allowed in unevaluated 11236 // expressions. Everything else falls under the 11237 // "may accept other forms of constant expressions" exception. 11238 // 11239 // Regular C++ code will not end up here (exceptions: language extensions, 11240 // OpenCL C++ etc), so the constant expression rules there don't matter. 11241 if (Init->isValueDependent()) { 11242 assert(Init->containsErrors() && 11243 "Dependent code should only occur in error-recovery path."); 11244 return true; 11245 } 11246 const Expr *Culprit; 11247 if (Init->isConstantInitializer(Context, false, &Culprit)) 11248 return false; 11249 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11250 << Culprit->getSourceRange(); 11251 return true; 11252 } 11253 11254 namespace { 11255 // Visits an initialization expression to see if OrigDecl is evaluated in 11256 // its own initialization and throws a warning if it does. 11257 class SelfReferenceChecker 11258 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11259 Sema &S; 11260 Decl *OrigDecl; 11261 bool isRecordType; 11262 bool isPODType; 11263 bool isReferenceType; 11264 11265 bool isInitList; 11266 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11267 11268 public: 11269 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11270 11271 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11272 S(S), OrigDecl(OrigDecl) { 11273 isPODType = false; 11274 isRecordType = false; 11275 isReferenceType = false; 11276 isInitList = false; 11277 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11278 isPODType = VD->getType().isPODType(S.Context); 11279 isRecordType = VD->getType()->isRecordType(); 11280 isReferenceType = VD->getType()->isReferenceType(); 11281 } 11282 } 11283 11284 // For most expressions, just call the visitor. For initializer lists, 11285 // track the index of the field being initialized since fields are 11286 // initialized in order allowing use of previously initialized fields. 11287 void CheckExpr(Expr *E) { 11288 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11289 if (!InitList) { 11290 Visit(E); 11291 return; 11292 } 11293 11294 // Track and increment the index here. 11295 isInitList = true; 11296 InitFieldIndex.push_back(0); 11297 for (auto Child : InitList->children()) { 11298 CheckExpr(cast<Expr>(Child)); 11299 ++InitFieldIndex.back(); 11300 } 11301 InitFieldIndex.pop_back(); 11302 } 11303 11304 // Returns true if MemberExpr is checked and no further checking is needed. 11305 // Returns false if additional checking is required. 11306 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11307 llvm::SmallVector<FieldDecl*, 4> Fields; 11308 Expr *Base = E; 11309 bool ReferenceField = false; 11310 11311 // Get the field members used. 11312 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11313 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11314 if (!FD) 11315 return false; 11316 Fields.push_back(FD); 11317 if (FD->getType()->isReferenceType()) 11318 ReferenceField = true; 11319 Base = ME->getBase()->IgnoreParenImpCasts(); 11320 } 11321 11322 // Keep checking only if the base Decl is the same. 11323 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11324 if (!DRE || DRE->getDecl() != OrigDecl) 11325 return false; 11326 11327 // A reference field can be bound to an unininitialized field. 11328 if (CheckReference && !ReferenceField) 11329 return true; 11330 11331 // Convert FieldDecls to their index number. 11332 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11333 for (const FieldDecl *I : llvm::reverse(Fields)) 11334 UsedFieldIndex.push_back(I->getFieldIndex()); 11335 11336 // See if a warning is needed by checking the first difference in index 11337 // numbers. If field being used has index less than the field being 11338 // initialized, then the use is safe. 11339 for (auto UsedIter = UsedFieldIndex.begin(), 11340 UsedEnd = UsedFieldIndex.end(), 11341 OrigIter = InitFieldIndex.begin(), 11342 OrigEnd = InitFieldIndex.end(); 11343 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11344 if (*UsedIter < *OrigIter) 11345 return true; 11346 if (*UsedIter > *OrigIter) 11347 break; 11348 } 11349 11350 // TODO: Add a different warning which will print the field names. 11351 HandleDeclRefExpr(DRE); 11352 return true; 11353 } 11354 11355 // For most expressions, the cast is directly above the DeclRefExpr. 11356 // For conditional operators, the cast can be outside the conditional 11357 // operator if both expressions are DeclRefExpr's. 11358 void HandleValue(Expr *E) { 11359 E = E->IgnoreParens(); 11360 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11361 HandleDeclRefExpr(DRE); 11362 return; 11363 } 11364 11365 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11366 Visit(CO->getCond()); 11367 HandleValue(CO->getTrueExpr()); 11368 HandleValue(CO->getFalseExpr()); 11369 return; 11370 } 11371 11372 if (BinaryConditionalOperator *BCO = 11373 dyn_cast<BinaryConditionalOperator>(E)) { 11374 Visit(BCO->getCond()); 11375 HandleValue(BCO->getFalseExpr()); 11376 return; 11377 } 11378 11379 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11380 HandleValue(OVE->getSourceExpr()); 11381 return; 11382 } 11383 11384 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11385 if (BO->getOpcode() == BO_Comma) { 11386 Visit(BO->getLHS()); 11387 HandleValue(BO->getRHS()); 11388 return; 11389 } 11390 } 11391 11392 if (isa<MemberExpr>(E)) { 11393 if (isInitList) { 11394 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11395 false /*CheckReference*/)) 11396 return; 11397 } 11398 11399 Expr *Base = E->IgnoreParenImpCasts(); 11400 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11401 // Check for static member variables and don't warn on them. 11402 if (!isa<FieldDecl>(ME->getMemberDecl())) 11403 return; 11404 Base = ME->getBase()->IgnoreParenImpCasts(); 11405 } 11406 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11407 HandleDeclRefExpr(DRE); 11408 return; 11409 } 11410 11411 Visit(E); 11412 } 11413 11414 // Reference types not handled in HandleValue are handled here since all 11415 // uses of references are bad, not just r-value uses. 11416 void VisitDeclRefExpr(DeclRefExpr *E) { 11417 if (isReferenceType) 11418 HandleDeclRefExpr(E); 11419 } 11420 11421 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11422 if (E->getCastKind() == CK_LValueToRValue) { 11423 HandleValue(E->getSubExpr()); 11424 return; 11425 } 11426 11427 Inherited::VisitImplicitCastExpr(E); 11428 } 11429 11430 void VisitMemberExpr(MemberExpr *E) { 11431 if (isInitList) { 11432 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11433 return; 11434 } 11435 11436 // Don't warn on arrays since they can be treated as pointers. 11437 if (E->getType()->canDecayToPointerType()) return; 11438 11439 // Warn when a non-static method call is followed by non-static member 11440 // field accesses, which is followed by a DeclRefExpr. 11441 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11442 bool Warn = (MD && !MD->isStatic()); 11443 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11444 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11445 if (!isa<FieldDecl>(ME->getMemberDecl())) 11446 Warn = false; 11447 Base = ME->getBase()->IgnoreParenImpCasts(); 11448 } 11449 11450 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11451 if (Warn) 11452 HandleDeclRefExpr(DRE); 11453 return; 11454 } 11455 11456 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11457 // Visit that expression. 11458 Visit(Base); 11459 } 11460 11461 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11462 Expr *Callee = E->getCallee(); 11463 11464 if (isa<UnresolvedLookupExpr>(Callee)) 11465 return Inherited::VisitCXXOperatorCallExpr(E); 11466 11467 Visit(Callee); 11468 for (auto Arg: E->arguments()) 11469 HandleValue(Arg->IgnoreParenImpCasts()); 11470 } 11471 11472 void VisitUnaryOperator(UnaryOperator *E) { 11473 // For POD record types, addresses of its own members are well-defined. 11474 if (E->getOpcode() == UO_AddrOf && isRecordType && 11475 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11476 if (!isPODType) 11477 HandleValue(E->getSubExpr()); 11478 return; 11479 } 11480 11481 if (E->isIncrementDecrementOp()) { 11482 HandleValue(E->getSubExpr()); 11483 return; 11484 } 11485 11486 Inherited::VisitUnaryOperator(E); 11487 } 11488 11489 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11490 11491 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11492 if (E->getConstructor()->isCopyConstructor()) { 11493 Expr *ArgExpr = E->getArg(0); 11494 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11495 if (ILE->getNumInits() == 1) 11496 ArgExpr = ILE->getInit(0); 11497 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11498 if (ICE->getCastKind() == CK_NoOp) 11499 ArgExpr = ICE->getSubExpr(); 11500 HandleValue(ArgExpr); 11501 return; 11502 } 11503 Inherited::VisitCXXConstructExpr(E); 11504 } 11505 11506 void VisitCallExpr(CallExpr *E) { 11507 // Treat std::move as a use. 11508 if (E->isCallToStdMove()) { 11509 HandleValue(E->getArg(0)); 11510 return; 11511 } 11512 11513 Inherited::VisitCallExpr(E); 11514 } 11515 11516 void VisitBinaryOperator(BinaryOperator *E) { 11517 if (E->isCompoundAssignmentOp()) { 11518 HandleValue(E->getLHS()); 11519 Visit(E->getRHS()); 11520 return; 11521 } 11522 11523 Inherited::VisitBinaryOperator(E); 11524 } 11525 11526 // A custom visitor for BinaryConditionalOperator is needed because the 11527 // regular visitor would check the condition and true expression separately 11528 // but both point to the same place giving duplicate diagnostics. 11529 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11530 Visit(E->getCond()); 11531 Visit(E->getFalseExpr()); 11532 } 11533 11534 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11535 Decl* ReferenceDecl = DRE->getDecl(); 11536 if (OrigDecl != ReferenceDecl) return; 11537 unsigned diag; 11538 if (isReferenceType) { 11539 diag = diag::warn_uninit_self_reference_in_reference_init; 11540 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11541 diag = diag::warn_static_self_reference_in_init; 11542 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11543 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11544 DRE->getDecl()->getType()->isRecordType()) { 11545 diag = diag::warn_uninit_self_reference_in_init; 11546 } else { 11547 // Local variables will be handled by the CFG analysis. 11548 return; 11549 } 11550 11551 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11552 S.PDiag(diag) 11553 << DRE->getDecl() << OrigDecl->getLocation() 11554 << DRE->getSourceRange()); 11555 } 11556 }; 11557 11558 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11559 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11560 bool DirectInit) { 11561 // Parameters arguments are occassionially constructed with itself, 11562 // for instance, in recursive functions. Skip them. 11563 if (isa<ParmVarDecl>(OrigDecl)) 11564 return; 11565 11566 E = E->IgnoreParens(); 11567 11568 // Skip checking T a = a where T is not a record or reference type. 11569 // Doing so is a way to silence uninitialized warnings. 11570 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11571 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11572 if (ICE->getCastKind() == CK_LValueToRValue) 11573 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11574 if (DRE->getDecl() == OrigDecl) 11575 return; 11576 11577 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11578 } 11579 } // end anonymous namespace 11580 11581 namespace { 11582 // Simple wrapper to add the name of a variable or (if no variable is 11583 // available) a DeclarationName into a diagnostic. 11584 struct VarDeclOrName { 11585 VarDecl *VDecl; 11586 DeclarationName Name; 11587 11588 friend const Sema::SemaDiagnosticBuilder & 11589 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11590 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11591 } 11592 }; 11593 } // end anonymous namespace 11594 11595 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11596 DeclarationName Name, QualType Type, 11597 TypeSourceInfo *TSI, 11598 SourceRange Range, bool DirectInit, 11599 Expr *Init) { 11600 bool IsInitCapture = !VDecl; 11601 assert((!VDecl || !VDecl->isInitCapture()) && 11602 "init captures are expected to be deduced prior to initialization"); 11603 11604 VarDeclOrName VN{VDecl, Name}; 11605 11606 DeducedType *Deduced = Type->getContainedDeducedType(); 11607 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11608 11609 // C++11 [dcl.spec.auto]p3 11610 if (!Init) { 11611 assert(VDecl && "no init for init capture deduction?"); 11612 11613 // Except for class argument deduction, and then for an initializing 11614 // declaration only, i.e. no static at class scope or extern. 11615 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11616 VDecl->hasExternalStorage() || 11617 VDecl->isStaticDataMember()) { 11618 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11619 << VDecl->getDeclName() << Type; 11620 return QualType(); 11621 } 11622 } 11623 11624 ArrayRef<Expr*> DeduceInits; 11625 if (Init) 11626 DeduceInits = Init; 11627 11628 if (DirectInit) { 11629 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11630 DeduceInits = PL->exprs(); 11631 } 11632 11633 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11634 assert(VDecl && "non-auto type for init capture deduction?"); 11635 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11636 InitializationKind Kind = InitializationKind::CreateForInit( 11637 VDecl->getLocation(), DirectInit, Init); 11638 // FIXME: Initialization should not be taking a mutable list of inits. 11639 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11640 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11641 InitsCopy); 11642 } 11643 11644 if (DirectInit) { 11645 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11646 DeduceInits = IL->inits(); 11647 } 11648 11649 // Deduction only works if we have exactly one source expression. 11650 if (DeduceInits.empty()) { 11651 // It isn't possible to write this directly, but it is possible to 11652 // end up in this situation with "auto x(some_pack...);" 11653 Diag(Init->getBeginLoc(), IsInitCapture 11654 ? diag::err_init_capture_no_expression 11655 : diag::err_auto_var_init_no_expression) 11656 << VN << Type << Range; 11657 return QualType(); 11658 } 11659 11660 if (DeduceInits.size() > 1) { 11661 Diag(DeduceInits[1]->getBeginLoc(), 11662 IsInitCapture ? diag::err_init_capture_multiple_expressions 11663 : diag::err_auto_var_init_multiple_expressions) 11664 << VN << Type << Range; 11665 return QualType(); 11666 } 11667 11668 Expr *DeduceInit = DeduceInits[0]; 11669 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11670 Diag(Init->getBeginLoc(), IsInitCapture 11671 ? diag::err_init_capture_paren_braces 11672 : diag::err_auto_var_init_paren_braces) 11673 << isa<InitListExpr>(Init) << VN << Type << Range; 11674 return QualType(); 11675 } 11676 11677 // Expressions default to 'id' when we're in a debugger. 11678 bool DefaultedAnyToId = false; 11679 if (getLangOpts().DebuggerCastResultToId && 11680 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11681 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11682 if (Result.isInvalid()) { 11683 return QualType(); 11684 } 11685 Init = Result.get(); 11686 DefaultedAnyToId = true; 11687 } 11688 11689 // C++ [dcl.decomp]p1: 11690 // If the assignment-expression [...] has array type A and no ref-qualifier 11691 // is present, e has type cv A 11692 if (VDecl && isa<DecompositionDecl>(VDecl) && 11693 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11694 DeduceInit->getType()->isConstantArrayType()) 11695 return Context.getQualifiedType(DeduceInit->getType(), 11696 Type.getQualifiers()); 11697 11698 QualType DeducedType; 11699 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11700 if (!IsInitCapture) 11701 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11702 else if (isa<InitListExpr>(Init)) 11703 Diag(Range.getBegin(), 11704 diag::err_init_capture_deduction_failure_from_init_list) 11705 << VN 11706 << (DeduceInit->getType().isNull() ? TSI->getType() 11707 : DeduceInit->getType()) 11708 << DeduceInit->getSourceRange(); 11709 else 11710 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11711 << VN << TSI->getType() 11712 << (DeduceInit->getType().isNull() ? TSI->getType() 11713 : DeduceInit->getType()) 11714 << DeduceInit->getSourceRange(); 11715 } 11716 11717 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11718 // 'id' instead of a specific object type prevents most of our usual 11719 // checks. 11720 // We only want to warn outside of template instantiations, though: 11721 // inside a template, the 'id' could have come from a parameter. 11722 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11723 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11724 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11725 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11726 } 11727 11728 return DeducedType; 11729 } 11730 11731 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11732 Expr *Init) { 11733 assert(!Init || !Init->containsErrors()); 11734 QualType DeducedType = deduceVarTypeFromInitializer( 11735 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11736 VDecl->getSourceRange(), DirectInit, Init); 11737 if (DeducedType.isNull()) { 11738 VDecl->setInvalidDecl(); 11739 return true; 11740 } 11741 11742 VDecl->setType(DeducedType); 11743 assert(VDecl->isLinkageValid()); 11744 11745 // In ARC, infer lifetime. 11746 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11747 VDecl->setInvalidDecl(); 11748 11749 if (getLangOpts().OpenCL) 11750 deduceOpenCLAddressSpace(VDecl); 11751 11752 // If this is a redeclaration, check that the type we just deduced matches 11753 // the previously declared type. 11754 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11755 // We never need to merge the type, because we cannot form an incomplete 11756 // array of auto, nor deduce such a type. 11757 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11758 } 11759 11760 // Check the deduced type is valid for a variable declaration. 11761 CheckVariableDeclarationType(VDecl); 11762 return VDecl->isInvalidDecl(); 11763 } 11764 11765 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11766 SourceLocation Loc) { 11767 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11768 Init = EWC->getSubExpr(); 11769 11770 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11771 Init = CE->getSubExpr(); 11772 11773 QualType InitType = Init->getType(); 11774 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11775 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11776 "shouldn't be called if type doesn't have a non-trivial C struct"); 11777 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11778 for (auto I : ILE->inits()) { 11779 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11780 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11781 continue; 11782 SourceLocation SL = I->getExprLoc(); 11783 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11784 } 11785 return; 11786 } 11787 11788 if (isa<ImplicitValueInitExpr>(Init)) { 11789 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11790 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11791 NTCUK_Init); 11792 } else { 11793 // Assume all other explicit initializers involving copying some existing 11794 // object. 11795 // TODO: ignore any explicit initializers where we can guarantee 11796 // copy-elision. 11797 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11798 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11799 } 11800 } 11801 11802 namespace { 11803 11804 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11805 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11806 // in the source code or implicitly by the compiler if it is in a union 11807 // defined in a system header and has non-trivial ObjC ownership 11808 // qualifications. We don't want those fields to participate in determining 11809 // whether the containing union is non-trivial. 11810 return FD->hasAttr<UnavailableAttr>(); 11811 } 11812 11813 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11814 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11815 void> { 11816 using Super = 11817 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11818 void>; 11819 11820 DiagNonTrivalCUnionDefaultInitializeVisitor( 11821 QualType OrigTy, SourceLocation OrigLoc, 11822 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11823 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11824 11825 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11826 const FieldDecl *FD, bool InNonTrivialUnion) { 11827 if (const auto *AT = S.Context.getAsArrayType(QT)) 11828 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11829 InNonTrivialUnion); 11830 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11831 } 11832 11833 void visitARCStrong(QualType QT, const FieldDecl *FD, 11834 bool InNonTrivialUnion) { 11835 if (InNonTrivialUnion) 11836 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11837 << 1 << 0 << QT << FD->getName(); 11838 } 11839 11840 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11841 if (InNonTrivialUnion) 11842 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11843 << 1 << 0 << QT << FD->getName(); 11844 } 11845 11846 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11847 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11848 if (RD->isUnion()) { 11849 if (OrigLoc.isValid()) { 11850 bool IsUnion = false; 11851 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11852 IsUnion = OrigRD->isUnion(); 11853 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11854 << 0 << OrigTy << IsUnion << UseContext; 11855 // Reset OrigLoc so that this diagnostic is emitted only once. 11856 OrigLoc = SourceLocation(); 11857 } 11858 InNonTrivialUnion = true; 11859 } 11860 11861 if (InNonTrivialUnion) 11862 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11863 << 0 << 0 << QT.getUnqualifiedType() << ""; 11864 11865 for (const FieldDecl *FD : RD->fields()) 11866 if (!shouldIgnoreForRecordTriviality(FD)) 11867 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11868 } 11869 11870 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11871 11872 // The non-trivial C union type or the struct/union type that contains a 11873 // non-trivial C union. 11874 QualType OrigTy; 11875 SourceLocation OrigLoc; 11876 Sema::NonTrivialCUnionContext UseContext; 11877 Sema &S; 11878 }; 11879 11880 struct DiagNonTrivalCUnionDestructedTypeVisitor 11881 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11882 using Super = 11883 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11884 11885 DiagNonTrivalCUnionDestructedTypeVisitor( 11886 QualType OrigTy, SourceLocation OrigLoc, 11887 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11888 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11889 11890 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11891 const FieldDecl *FD, bool InNonTrivialUnion) { 11892 if (const auto *AT = S.Context.getAsArrayType(QT)) 11893 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11894 InNonTrivialUnion); 11895 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11896 } 11897 11898 void visitARCStrong(QualType QT, const FieldDecl *FD, 11899 bool InNonTrivialUnion) { 11900 if (InNonTrivialUnion) 11901 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11902 << 1 << 1 << QT << FD->getName(); 11903 } 11904 11905 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11906 if (InNonTrivialUnion) 11907 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11908 << 1 << 1 << QT << FD->getName(); 11909 } 11910 11911 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11912 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11913 if (RD->isUnion()) { 11914 if (OrigLoc.isValid()) { 11915 bool IsUnion = false; 11916 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11917 IsUnion = OrigRD->isUnion(); 11918 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11919 << 1 << OrigTy << IsUnion << UseContext; 11920 // Reset OrigLoc so that this diagnostic is emitted only once. 11921 OrigLoc = SourceLocation(); 11922 } 11923 InNonTrivialUnion = true; 11924 } 11925 11926 if (InNonTrivialUnion) 11927 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11928 << 0 << 1 << QT.getUnqualifiedType() << ""; 11929 11930 for (const FieldDecl *FD : RD->fields()) 11931 if (!shouldIgnoreForRecordTriviality(FD)) 11932 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11933 } 11934 11935 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11936 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11937 bool InNonTrivialUnion) {} 11938 11939 // The non-trivial C union type or the struct/union type that contains a 11940 // non-trivial C union. 11941 QualType OrigTy; 11942 SourceLocation OrigLoc; 11943 Sema::NonTrivialCUnionContext UseContext; 11944 Sema &S; 11945 }; 11946 11947 struct DiagNonTrivalCUnionCopyVisitor 11948 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11949 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11950 11951 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11952 Sema::NonTrivialCUnionContext UseContext, 11953 Sema &S) 11954 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11955 11956 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11957 const FieldDecl *FD, bool InNonTrivialUnion) { 11958 if (const auto *AT = S.Context.getAsArrayType(QT)) 11959 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11960 InNonTrivialUnion); 11961 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11962 } 11963 11964 void visitARCStrong(QualType QT, const FieldDecl *FD, 11965 bool InNonTrivialUnion) { 11966 if (InNonTrivialUnion) 11967 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11968 << 1 << 2 << QT << FD->getName(); 11969 } 11970 11971 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11972 if (InNonTrivialUnion) 11973 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11974 << 1 << 2 << QT << FD->getName(); 11975 } 11976 11977 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11978 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11979 if (RD->isUnion()) { 11980 if (OrigLoc.isValid()) { 11981 bool IsUnion = false; 11982 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11983 IsUnion = OrigRD->isUnion(); 11984 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11985 << 2 << OrigTy << IsUnion << UseContext; 11986 // Reset OrigLoc so that this diagnostic is emitted only once. 11987 OrigLoc = SourceLocation(); 11988 } 11989 InNonTrivialUnion = true; 11990 } 11991 11992 if (InNonTrivialUnion) 11993 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11994 << 0 << 2 << QT.getUnqualifiedType() << ""; 11995 11996 for (const FieldDecl *FD : RD->fields()) 11997 if (!shouldIgnoreForRecordTriviality(FD)) 11998 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11999 } 12000 12001 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12002 const FieldDecl *FD, bool InNonTrivialUnion) {} 12003 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12004 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12005 bool InNonTrivialUnion) {} 12006 12007 // The non-trivial C union type or the struct/union type that contains a 12008 // non-trivial C union. 12009 QualType OrigTy; 12010 SourceLocation OrigLoc; 12011 Sema::NonTrivialCUnionContext UseContext; 12012 Sema &S; 12013 }; 12014 12015 } // namespace 12016 12017 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12018 NonTrivialCUnionContext UseContext, 12019 unsigned NonTrivialKind) { 12020 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12021 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12022 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12023 "shouldn't be called if type doesn't have a non-trivial C union"); 12024 12025 if ((NonTrivialKind & NTCUK_Init) && 12026 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12027 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12028 .visit(QT, nullptr, false); 12029 if ((NonTrivialKind & NTCUK_Destruct) && 12030 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12031 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12032 .visit(QT, nullptr, false); 12033 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12034 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12035 .visit(QT, nullptr, false); 12036 } 12037 12038 /// AddInitializerToDecl - Adds the initializer Init to the 12039 /// declaration dcl. If DirectInit is true, this is C++ direct 12040 /// initialization rather than copy initialization. 12041 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12042 // If there is no declaration, there was an error parsing it. Just ignore 12043 // the initializer. 12044 if (!RealDecl || RealDecl->isInvalidDecl()) { 12045 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12046 return; 12047 } 12048 12049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12050 // Pure-specifiers are handled in ActOnPureSpecifier. 12051 Diag(Method->getLocation(), diag::err_member_function_initialization) 12052 << Method->getDeclName() << Init->getSourceRange(); 12053 Method->setInvalidDecl(); 12054 return; 12055 } 12056 12057 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12058 if (!VDecl) { 12059 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12060 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12061 RealDecl->setInvalidDecl(); 12062 return; 12063 } 12064 12065 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12066 if (VDecl->getType()->isUndeducedType()) { 12067 // Attempt typo correction early so that the type of the init expression can 12068 // be deduced based on the chosen correction if the original init contains a 12069 // TypoExpr. 12070 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12071 if (!Res.isUsable()) { 12072 // There are unresolved typos in Init, just drop them. 12073 // FIXME: improve the recovery strategy to preserve the Init. 12074 RealDecl->setInvalidDecl(); 12075 return; 12076 } 12077 if (Res.get()->containsErrors()) { 12078 // Invalidate the decl as we don't know the type for recovery-expr yet. 12079 RealDecl->setInvalidDecl(); 12080 VDecl->setInit(Res.get()); 12081 return; 12082 } 12083 Init = Res.get(); 12084 12085 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12086 return; 12087 } 12088 12089 // dllimport cannot be used on variable definitions. 12090 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12091 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12092 VDecl->setInvalidDecl(); 12093 return; 12094 } 12095 12096 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12097 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12098 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12099 VDecl->setInvalidDecl(); 12100 return; 12101 } 12102 12103 if (!VDecl->getType()->isDependentType()) { 12104 // A definition must end up with a complete type, which means it must be 12105 // complete with the restriction that an array type might be completed by 12106 // the initializer; note that later code assumes this restriction. 12107 QualType BaseDeclType = VDecl->getType(); 12108 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12109 BaseDeclType = Array->getElementType(); 12110 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12111 diag::err_typecheck_decl_incomplete_type)) { 12112 RealDecl->setInvalidDecl(); 12113 return; 12114 } 12115 12116 // The variable can not have an abstract class type. 12117 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12118 diag::err_abstract_type_in_decl, 12119 AbstractVariableType)) 12120 VDecl->setInvalidDecl(); 12121 } 12122 12123 // If adding the initializer will turn this declaration into a definition, 12124 // and we already have a definition for this variable, diagnose or otherwise 12125 // handle the situation. 12126 VarDecl *Def; 12127 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12128 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12129 !VDecl->isThisDeclarationADemotedDefinition() && 12130 checkVarDeclRedefinition(Def, VDecl)) 12131 return; 12132 12133 if (getLangOpts().CPlusPlus) { 12134 // C++ [class.static.data]p4 12135 // If a static data member is of const integral or const 12136 // enumeration type, its declaration in the class definition can 12137 // specify a constant-initializer which shall be an integral 12138 // constant expression (5.19). In that case, the member can appear 12139 // in integral constant expressions. The member shall still be 12140 // defined in a namespace scope if it is used in the program and the 12141 // namespace scope definition shall not contain an initializer. 12142 // 12143 // We already performed a redefinition check above, but for static 12144 // data members we also need to check whether there was an in-class 12145 // declaration with an initializer. 12146 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12147 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12148 << VDecl->getDeclName(); 12149 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12150 diag::note_previous_initializer) 12151 << 0; 12152 return; 12153 } 12154 12155 if (VDecl->hasLocalStorage()) 12156 setFunctionHasBranchProtectedScope(); 12157 12158 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12159 VDecl->setInvalidDecl(); 12160 return; 12161 } 12162 } 12163 12164 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12165 // a kernel function cannot be initialized." 12166 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12167 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12168 VDecl->setInvalidDecl(); 12169 return; 12170 } 12171 12172 // The LoaderUninitialized attribute acts as a definition (of undef). 12173 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12174 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12175 VDecl->setInvalidDecl(); 12176 return; 12177 } 12178 12179 // Get the decls type and save a reference for later, since 12180 // CheckInitializerTypes may change it. 12181 QualType DclT = VDecl->getType(), SavT = DclT; 12182 12183 // Expressions default to 'id' when we're in a debugger 12184 // and we are assigning it to a variable of Objective-C pointer type. 12185 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12186 Init->getType() == Context.UnknownAnyTy) { 12187 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12188 if (Result.isInvalid()) { 12189 VDecl->setInvalidDecl(); 12190 return; 12191 } 12192 Init = Result.get(); 12193 } 12194 12195 // Perform the initialization. 12196 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12197 if (!VDecl->isInvalidDecl()) { 12198 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12199 InitializationKind Kind = InitializationKind::CreateForInit( 12200 VDecl->getLocation(), DirectInit, Init); 12201 12202 MultiExprArg Args = Init; 12203 if (CXXDirectInit) 12204 Args = MultiExprArg(CXXDirectInit->getExprs(), 12205 CXXDirectInit->getNumExprs()); 12206 12207 // Try to correct any TypoExprs in the initialization arguments. 12208 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12209 ExprResult Res = CorrectDelayedTyposInExpr( 12210 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12211 [this, Entity, Kind](Expr *E) { 12212 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12213 return Init.Failed() ? ExprError() : E; 12214 }); 12215 if (Res.isInvalid()) { 12216 VDecl->setInvalidDecl(); 12217 } else if (Res.get() != Args[Idx]) { 12218 Args[Idx] = Res.get(); 12219 } 12220 } 12221 if (VDecl->isInvalidDecl()) 12222 return; 12223 12224 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12225 /*TopLevelOfInitList=*/false, 12226 /*TreatUnavailableAsInvalid=*/false); 12227 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12228 if (Result.isInvalid()) { 12229 // If the provied initializer fails to initialize the var decl, 12230 // we attach a recovery expr for better recovery. 12231 auto RecoveryExpr = 12232 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12233 if (RecoveryExpr.get()) 12234 VDecl->setInit(RecoveryExpr.get()); 12235 return; 12236 } 12237 12238 Init = Result.getAs<Expr>(); 12239 } 12240 12241 // Check for self-references within variable initializers. 12242 // Variables declared within a function/method body (except for references) 12243 // are handled by a dataflow analysis. 12244 // This is undefined behavior in C++, but valid in C. 12245 if (getLangOpts().CPlusPlus) { 12246 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12247 VDecl->getType()->isReferenceType()) { 12248 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12249 } 12250 } 12251 12252 // If the type changed, it means we had an incomplete type that was 12253 // completed by the initializer. For example: 12254 // int ary[] = { 1, 3, 5 }; 12255 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12256 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12257 VDecl->setType(DclT); 12258 12259 if (!VDecl->isInvalidDecl()) { 12260 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12261 12262 if (VDecl->hasAttr<BlocksAttr>()) 12263 checkRetainCycles(VDecl, Init); 12264 12265 // It is safe to assign a weak reference into a strong variable. 12266 // Although this code can still have problems: 12267 // id x = self.weakProp; 12268 // id y = self.weakProp; 12269 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12270 // paths through the function. This should be revisited if 12271 // -Wrepeated-use-of-weak is made flow-sensitive. 12272 if (FunctionScopeInfo *FSI = getCurFunction()) 12273 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12274 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12275 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12276 Init->getBeginLoc())) 12277 FSI->markSafeWeakUse(Init); 12278 } 12279 12280 // The initialization is usually a full-expression. 12281 // 12282 // FIXME: If this is a braced initialization of an aggregate, it is not 12283 // an expression, and each individual field initializer is a separate 12284 // full-expression. For instance, in: 12285 // 12286 // struct Temp { ~Temp(); }; 12287 // struct S { S(Temp); }; 12288 // struct T { S a, b; } t = { Temp(), Temp() } 12289 // 12290 // we should destroy the first Temp before constructing the second. 12291 ExprResult Result = 12292 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12293 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12294 if (Result.isInvalid()) { 12295 VDecl->setInvalidDecl(); 12296 return; 12297 } 12298 Init = Result.get(); 12299 12300 // Attach the initializer to the decl. 12301 VDecl->setInit(Init); 12302 12303 if (VDecl->isLocalVarDecl()) { 12304 // Don't check the initializer if the declaration is malformed. 12305 if (VDecl->isInvalidDecl()) { 12306 // do nothing 12307 12308 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12309 // This is true even in C++ for OpenCL. 12310 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12311 CheckForConstantInitializer(Init, DclT); 12312 12313 // Otherwise, C++ does not restrict the initializer. 12314 } else if (getLangOpts().CPlusPlus) { 12315 // do nothing 12316 12317 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12318 // static storage duration shall be constant expressions or string literals. 12319 } else if (VDecl->getStorageClass() == SC_Static) { 12320 CheckForConstantInitializer(Init, DclT); 12321 12322 // C89 is stricter than C99 for aggregate initializers. 12323 // C89 6.5.7p3: All the expressions [...] in an initializer list 12324 // for an object that has aggregate or union type shall be 12325 // constant expressions. 12326 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12327 isa<InitListExpr>(Init)) { 12328 const Expr *Culprit; 12329 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12330 Diag(Culprit->getExprLoc(), 12331 diag::ext_aggregate_init_not_constant) 12332 << Culprit->getSourceRange(); 12333 } 12334 } 12335 12336 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12337 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12338 if (VDecl->hasLocalStorage()) 12339 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12340 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12341 VDecl->getLexicalDeclContext()->isRecord()) { 12342 // This is an in-class initialization for a static data member, e.g., 12343 // 12344 // struct S { 12345 // static const int value = 17; 12346 // }; 12347 12348 // C++ [class.mem]p4: 12349 // A member-declarator can contain a constant-initializer only 12350 // if it declares a static member (9.4) of const integral or 12351 // const enumeration type, see 9.4.2. 12352 // 12353 // C++11 [class.static.data]p3: 12354 // If a non-volatile non-inline const static data member is of integral 12355 // or enumeration type, its declaration in the class definition can 12356 // specify a brace-or-equal-initializer in which every initializer-clause 12357 // that is an assignment-expression is a constant expression. A static 12358 // data member of literal type can be declared in the class definition 12359 // with the constexpr specifier; if so, its declaration shall specify a 12360 // brace-or-equal-initializer in which every initializer-clause that is 12361 // an assignment-expression is a constant expression. 12362 12363 // Do nothing on dependent types. 12364 if (DclT->isDependentType()) { 12365 12366 // Allow any 'static constexpr' members, whether or not they are of literal 12367 // type. We separately check that every constexpr variable is of literal 12368 // type. 12369 } else if (VDecl->isConstexpr()) { 12370 12371 // Require constness. 12372 } else if (!DclT.isConstQualified()) { 12373 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12374 << Init->getSourceRange(); 12375 VDecl->setInvalidDecl(); 12376 12377 // We allow integer constant expressions in all cases. 12378 } else if (DclT->isIntegralOrEnumerationType()) { 12379 // Check whether the expression is a constant expression. 12380 SourceLocation Loc; 12381 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12382 // In C++11, a non-constexpr const static data member with an 12383 // in-class initializer cannot be volatile. 12384 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12385 else if (Init->isValueDependent()) 12386 ; // Nothing to check. 12387 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12388 ; // Ok, it's an ICE! 12389 else if (Init->getType()->isScopedEnumeralType() && 12390 Init->isCXX11ConstantExpr(Context)) 12391 ; // Ok, it is a scoped-enum constant expression. 12392 else if (Init->isEvaluatable(Context)) { 12393 // If we can constant fold the initializer through heroics, accept it, 12394 // but report this as a use of an extension for -pedantic. 12395 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12396 << Init->getSourceRange(); 12397 } else { 12398 // Otherwise, this is some crazy unknown case. Report the issue at the 12399 // location provided by the isIntegerConstantExpr failed check. 12400 Diag(Loc, diag::err_in_class_initializer_non_constant) 12401 << Init->getSourceRange(); 12402 VDecl->setInvalidDecl(); 12403 } 12404 12405 // We allow foldable floating-point constants as an extension. 12406 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12407 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12408 // it anyway and provide a fixit to add the 'constexpr'. 12409 if (getLangOpts().CPlusPlus11) { 12410 Diag(VDecl->getLocation(), 12411 diag::ext_in_class_initializer_float_type_cxx11) 12412 << DclT << Init->getSourceRange(); 12413 Diag(VDecl->getBeginLoc(), 12414 diag::note_in_class_initializer_float_type_cxx11) 12415 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12416 } else { 12417 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12418 << DclT << Init->getSourceRange(); 12419 12420 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12421 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12422 << Init->getSourceRange(); 12423 VDecl->setInvalidDecl(); 12424 } 12425 } 12426 12427 // Suggest adding 'constexpr' in C++11 for literal types. 12428 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12429 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12430 << DclT << Init->getSourceRange() 12431 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12432 VDecl->setConstexpr(true); 12433 12434 } else { 12435 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12436 << DclT << Init->getSourceRange(); 12437 VDecl->setInvalidDecl(); 12438 } 12439 } else if (VDecl->isFileVarDecl()) { 12440 // In C, extern is typically used to avoid tentative definitions when 12441 // declaring variables in headers, but adding an intializer makes it a 12442 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12443 // In C++, extern is often used to give implictly static const variables 12444 // external linkage, so don't warn in that case. If selectany is present, 12445 // this might be header code intended for C and C++ inclusion, so apply the 12446 // C++ rules. 12447 if (VDecl->getStorageClass() == SC_Extern && 12448 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12449 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12450 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12451 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12452 Diag(VDecl->getLocation(), diag::warn_extern_init); 12453 12454 // In Microsoft C++ mode, a const variable defined in namespace scope has 12455 // external linkage by default if the variable is declared with 12456 // __declspec(dllexport). 12457 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12458 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12459 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12460 VDecl->setStorageClass(SC_Extern); 12461 12462 // C99 6.7.8p4. All file scoped initializers need to be constant. 12463 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12464 CheckForConstantInitializer(Init, DclT); 12465 } 12466 12467 QualType InitType = Init->getType(); 12468 if (!InitType.isNull() && 12469 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12470 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12471 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12472 12473 // We will represent direct-initialization similarly to copy-initialization: 12474 // int x(1); -as-> int x = 1; 12475 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12476 // 12477 // Clients that want to distinguish between the two forms, can check for 12478 // direct initializer using VarDecl::getInitStyle(). 12479 // A major benefit is that clients that don't particularly care about which 12480 // exactly form was it (like the CodeGen) can handle both cases without 12481 // special case code. 12482 12483 // C++ 8.5p11: 12484 // The form of initialization (using parentheses or '=') is generally 12485 // insignificant, but does matter when the entity being initialized has a 12486 // class type. 12487 if (CXXDirectInit) { 12488 assert(DirectInit && "Call-style initializer must be direct init."); 12489 VDecl->setInitStyle(VarDecl::CallInit); 12490 } else if (DirectInit) { 12491 // This must be list-initialization. No other way is direct-initialization. 12492 VDecl->setInitStyle(VarDecl::ListInit); 12493 } 12494 12495 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12496 DeclsToCheckForDeferredDiags.push_back(VDecl); 12497 CheckCompleteVariableDeclaration(VDecl); 12498 } 12499 12500 /// ActOnInitializerError - Given that there was an error parsing an 12501 /// initializer for the given declaration, try to return to some form 12502 /// of sanity. 12503 void Sema::ActOnInitializerError(Decl *D) { 12504 // Our main concern here is re-establishing invariants like "a 12505 // variable's type is either dependent or complete". 12506 if (!D || D->isInvalidDecl()) return; 12507 12508 VarDecl *VD = dyn_cast<VarDecl>(D); 12509 if (!VD) return; 12510 12511 // Bindings are not usable if we can't make sense of the initializer. 12512 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12513 for (auto *BD : DD->bindings()) 12514 BD->setInvalidDecl(); 12515 12516 // Auto types are meaningless if we can't make sense of the initializer. 12517 if (VD->getType()->isUndeducedType()) { 12518 D->setInvalidDecl(); 12519 return; 12520 } 12521 12522 QualType Ty = VD->getType(); 12523 if (Ty->isDependentType()) return; 12524 12525 // Require a complete type. 12526 if (RequireCompleteType(VD->getLocation(), 12527 Context.getBaseElementType(Ty), 12528 diag::err_typecheck_decl_incomplete_type)) { 12529 VD->setInvalidDecl(); 12530 return; 12531 } 12532 12533 // Require a non-abstract type. 12534 if (RequireNonAbstractType(VD->getLocation(), Ty, 12535 diag::err_abstract_type_in_decl, 12536 AbstractVariableType)) { 12537 VD->setInvalidDecl(); 12538 return; 12539 } 12540 12541 // Don't bother complaining about constructors or destructors, 12542 // though. 12543 } 12544 12545 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12546 // If there is no declaration, there was an error parsing it. Just ignore it. 12547 if (!RealDecl) 12548 return; 12549 12550 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12551 QualType Type = Var->getType(); 12552 12553 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12554 if (isa<DecompositionDecl>(RealDecl)) { 12555 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12556 Var->setInvalidDecl(); 12557 return; 12558 } 12559 12560 if (Type->isUndeducedType() && 12561 DeduceVariableDeclarationType(Var, false, nullptr)) 12562 return; 12563 12564 // C++11 [class.static.data]p3: A static data member can be declared with 12565 // the constexpr specifier; if so, its declaration shall specify 12566 // a brace-or-equal-initializer. 12567 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12568 // the definition of a variable [...] or the declaration of a static data 12569 // member. 12570 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12571 !Var->isThisDeclarationADemotedDefinition()) { 12572 if (Var->isStaticDataMember()) { 12573 // C++1z removes the relevant rule; the in-class declaration is always 12574 // a definition there. 12575 if (!getLangOpts().CPlusPlus17 && 12576 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12577 Diag(Var->getLocation(), 12578 diag::err_constexpr_static_mem_var_requires_init) 12579 << Var; 12580 Var->setInvalidDecl(); 12581 return; 12582 } 12583 } else { 12584 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12585 Var->setInvalidDecl(); 12586 return; 12587 } 12588 } 12589 12590 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12591 // be initialized. 12592 if (!Var->isInvalidDecl() && 12593 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12594 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12595 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12596 Var->setInvalidDecl(); 12597 return; 12598 } 12599 12600 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12601 if (Var->getStorageClass() == SC_Extern) { 12602 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12603 << Var; 12604 Var->setInvalidDecl(); 12605 return; 12606 } 12607 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12608 diag::err_typecheck_decl_incomplete_type)) { 12609 Var->setInvalidDecl(); 12610 return; 12611 } 12612 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12613 if (!RD->hasTrivialDefaultConstructor()) { 12614 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12615 Var->setInvalidDecl(); 12616 return; 12617 } 12618 } 12619 } 12620 12621 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12622 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12623 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12624 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12625 NTCUC_DefaultInitializedObject, NTCUK_Init); 12626 12627 12628 switch (DefKind) { 12629 case VarDecl::Definition: 12630 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12631 break; 12632 12633 // We have an out-of-line definition of a static data member 12634 // that has an in-class initializer, so we type-check this like 12635 // a declaration. 12636 // 12637 LLVM_FALLTHROUGH; 12638 12639 case VarDecl::DeclarationOnly: 12640 // It's only a declaration. 12641 12642 // Block scope. C99 6.7p7: If an identifier for an object is 12643 // declared with no linkage (C99 6.2.2p6), the type for the 12644 // object shall be complete. 12645 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12646 !Var->hasLinkage() && !Var->isInvalidDecl() && 12647 RequireCompleteType(Var->getLocation(), Type, 12648 diag::err_typecheck_decl_incomplete_type)) 12649 Var->setInvalidDecl(); 12650 12651 // Make sure that the type is not abstract. 12652 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12653 RequireNonAbstractType(Var->getLocation(), Type, 12654 diag::err_abstract_type_in_decl, 12655 AbstractVariableType)) 12656 Var->setInvalidDecl(); 12657 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12658 Var->getStorageClass() == SC_PrivateExtern) { 12659 Diag(Var->getLocation(), diag::warn_private_extern); 12660 Diag(Var->getLocation(), diag::note_private_extern); 12661 } 12662 12663 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12664 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12665 ExternalDeclarations.push_back(Var); 12666 12667 return; 12668 12669 case VarDecl::TentativeDefinition: 12670 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12671 // object that has file scope without an initializer, and without a 12672 // storage-class specifier or with the storage-class specifier "static", 12673 // constitutes a tentative definition. Note: A tentative definition with 12674 // external linkage is valid (C99 6.2.2p5). 12675 if (!Var->isInvalidDecl()) { 12676 if (const IncompleteArrayType *ArrayT 12677 = Context.getAsIncompleteArrayType(Type)) { 12678 if (RequireCompleteSizedType( 12679 Var->getLocation(), ArrayT->getElementType(), 12680 diag::err_array_incomplete_or_sizeless_type)) 12681 Var->setInvalidDecl(); 12682 } else if (Var->getStorageClass() == SC_Static) { 12683 // C99 6.9.2p3: If the declaration of an identifier for an object is 12684 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12685 // declared type shall not be an incomplete type. 12686 // NOTE: code such as the following 12687 // static struct s; 12688 // struct s { int a; }; 12689 // is accepted by gcc. Hence here we issue a warning instead of 12690 // an error and we do not invalidate the static declaration. 12691 // NOTE: to avoid multiple warnings, only check the first declaration. 12692 if (Var->isFirstDecl()) 12693 RequireCompleteType(Var->getLocation(), Type, 12694 diag::ext_typecheck_decl_incomplete_type); 12695 } 12696 } 12697 12698 // Record the tentative definition; we're done. 12699 if (!Var->isInvalidDecl()) 12700 TentativeDefinitions.push_back(Var); 12701 return; 12702 } 12703 12704 // Provide a specific diagnostic for uninitialized variable 12705 // definitions with incomplete array type. 12706 if (Type->isIncompleteArrayType()) { 12707 Diag(Var->getLocation(), 12708 diag::err_typecheck_incomplete_array_needs_initializer); 12709 Var->setInvalidDecl(); 12710 return; 12711 } 12712 12713 // Provide a specific diagnostic for uninitialized variable 12714 // definitions with reference type. 12715 if (Type->isReferenceType()) { 12716 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12717 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12718 Var->setInvalidDecl(); 12719 return; 12720 } 12721 12722 // Do not attempt to type-check the default initializer for a 12723 // variable with dependent type. 12724 if (Type->isDependentType()) 12725 return; 12726 12727 if (Var->isInvalidDecl()) 12728 return; 12729 12730 if (!Var->hasAttr<AliasAttr>()) { 12731 if (RequireCompleteType(Var->getLocation(), 12732 Context.getBaseElementType(Type), 12733 diag::err_typecheck_decl_incomplete_type)) { 12734 Var->setInvalidDecl(); 12735 return; 12736 } 12737 } else { 12738 return; 12739 } 12740 12741 // The variable can not have an abstract class type. 12742 if (RequireNonAbstractType(Var->getLocation(), Type, 12743 diag::err_abstract_type_in_decl, 12744 AbstractVariableType)) { 12745 Var->setInvalidDecl(); 12746 return; 12747 } 12748 12749 // Check for jumps past the implicit initializer. C++0x 12750 // clarifies that this applies to a "variable with automatic 12751 // storage duration", not a "local variable". 12752 // C++11 [stmt.dcl]p3 12753 // A program that jumps from a point where a variable with automatic 12754 // storage duration is not in scope to a point where it is in scope is 12755 // ill-formed unless the variable has scalar type, class type with a 12756 // trivial default constructor and a trivial destructor, a cv-qualified 12757 // version of one of these types, or an array of one of the preceding 12758 // types and is declared without an initializer. 12759 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12760 if (const RecordType *Record 12761 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12762 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12763 // Mark the function (if we're in one) for further checking even if the 12764 // looser rules of C++11 do not require such checks, so that we can 12765 // diagnose incompatibilities with C++98. 12766 if (!CXXRecord->isPOD()) 12767 setFunctionHasBranchProtectedScope(); 12768 } 12769 } 12770 // In OpenCL, we can't initialize objects in the __local address space, 12771 // even implicitly, so don't synthesize an implicit initializer. 12772 if (getLangOpts().OpenCL && 12773 Var->getType().getAddressSpace() == LangAS::opencl_local) 12774 return; 12775 // C++03 [dcl.init]p9: 12776 // If no initializer is specified for an object, and the 12777 // object is of (possibly cv-qualified) non-POD class type (or 12778 // array thereof), the object shall be default-initialized; if 12779 // the object is of const-qualified type, the underlying class 12780 // type shall have a user-declared default 12781 // constructor. Otherwise, if no initializer is specified for 12782 // a non- static object, the object and its subobjects, if 12783 // any, have an indeterminate initial value); if the object 12784 // or any of its subobjects are of const-qualified type, the 12785 // program is ill-formed. 12786 // C++0x [dcl.init]p11: 12787 // If no initializer is specified for an object, the object is 12788 // default-initialized; [...]. 12789 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12790 InitializationKind Kind 12791 = InitializationKind::CreateDefault(Var->getLocation()); 12792 12793 InitializationSequence InitSeq(*this, Entity, Kind, None); 12794 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12795 12796 if (Init.get()) { 12797 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12798 // This is important for template substitution. 12799 Var->setInitStyle(VarDecl::CallInit); 12800 } else if (Init.isInvalid()) { 12801 // If default-init fails, attach a recovery-expr initializer to track 12802 // that initialization was attempted and failed. 12803 auto RecoveryExpr = 12804 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12805 if (RecoveryExpr.get()) 12806 Var->setInit(RecoveryExpr.get()); 12807 } 12808 12809 CheckCompleteVariableDeclaration(Var); 12810 } 12811 } 12812 12813 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12814 // If there is no declaration, there was an error parsing it. Ignore it. 12815 if (!D) 12816 return; 12817 12818 VarDecl *VD = dyn_cast<VarDecl>(D); 12819 if (!VD) { 12820 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12821 D->setInvalidDecl(); 12822 return; 12823 } 12824 12825 VD->setCXXForRangeDecl(true); 12826 12827 // for-range-declaration cannot be given a storage class specifier. 12828 int Error = -1; 12829 switch (VD->getStorageClass()) { 12830 case SC_None: 12831 break; 12832 case SC_Extern: 12833 Error = 0; 12834 break; 12835 case SC_Static: 12836 Error = 1; 12837 break; 12838 case SC_PrivateExtern: 12839 Error = 2; 12840 break; 12841 case SC_Auto: 12842 Error = 3; 12843 break; 12844 case SC_Register: 12845 Error = 4; 12846 break; 12847 } 12848 12849 // for-range-declaration cannot be given a storage class specifier con't. 12850 switch (VD->getTSCSpec()) { 12851 case TSCS_thread_local: 12852 Error = 6; 12853 break; 12854 case TSCS___thread: 12855 case TSCS__Thread_local: 12856 case TSCS_unspecified: 12857 break; 12858 } 12859 12860 if (Error != -1) { 12861 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12862 << VD << Error; 12863 D->setInvalidDecl(); 12864 } 12865 } 12866 12867 StmtResult 12868 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12869 IdentifierInfo *Ident, 12870 ParsedAttributes &Attrs, 12871 SourceLocation AttrEnd) { 12872 // C++1y [stmt.iter]p1: 12873 // A range-based for statement of the form 12874 // for ( for-range-identifier : for-range-initializer ) statement 12875 // is equivalent to 12876 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12877 DeclSpec DS(Attrs.getPool().getFactory()); 12878 12879 const char *PrevSpec; 12880 unsigned DiagID; 12881 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12882 getPrintingPolicy()); 12883 12884 Declarator D(DS, DeclaratorContext::ForInit); 12885 D.SetIdentifier(Ident, IdentLoc); 12886 D.takeAttributes(Attrs, AttrEnd); 12887 12888 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12889 IdentLoc); 12890 Decl *Var = ActOnDeclarator(S, D); 12891 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12892 FinalizeDeclaration(Var); 12893 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12894 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12895 } 12896 12897 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12898 if (var->isInvalidDecl()) return; 12899 12900 if (getLangOpts().OpenCL) { 12901 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12902 // initialiser 12903 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12904 !var->hasInit()) { 12905 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12906 << 1 /*Init*/; 12907 var->setInvalidDecl(); 12908 return; 12909 } 12910 } 12911 12912 // In Objective-C, don't allow jumps past the implicit initialization of a 12913 // local retaining variable. 12914 if (getLangOpts().ObjC && 12915 var->hasLocalStorage()) { 12916 switch (var->getType().getObjCLifetime()) { 12917 case Qualifiers::OCL_None: 12918 case Qualifiers::OCL_ExplicitNone: 12919 case Qualifiers::OCL_Autoreleasing: 12920 break; 12921 12922 case Qualifiers::OCL_Weak: 12923 case Qualifiers::OCL_Strong: 12924 setFunctionHasBranchProtectedScope(); 12925 break; 12926 } 12927 } 12928 12929 if (var->hasLocalStorage() && 12930 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12931 setFunctionHasBranchProtectedScope(); 12932 12933 // Warn about externally-visible variables being defined without a 12934 // prior declaration. We only want to do this for global 12935 // declarations, but we also specifically need to avoid doing it for 12936 // class members because the linkage of an anonymous class can 12937 // change if it's later given a typedef name. 12938 if (var->isThisDeclarationADefinition() && 12939 var->getDeclContext()->getRedeclContext()->isFileContext() && 12940 var->isExternallyVisible() && var->hasLinkage() && 12941 !var->isInline() && !var->getDescribedVarTemplate() && 12942 !isa<VarTemplatePartialSpecializationDecl>(var) && 12943 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12944 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12945 var->getLocation())) { 12946 // Find a previous declaration that's not a definition. 12947 VarDecl *prev = var->getPreviousDecl(); 12948 while (prev && prev->isThisDeclarationADefinition()) 12949 prev = prev->getPreviousDecl(); 12950 12951 if (!prev) { 12952 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12953 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12954 << /* variable */ 0; 12955 } 12956 } 12957 12958 // Cache the result of checking for constant initialization. 12959 Optional<bool> CacheHasConstInit; 12960 const Expr *CacheCulprit = nullptr; 12961 auto checkConstInit = [&]() mutable { 12962 if (!CacheHasConstInit) 12963 CacheHasConstInit = var->getInit()->isConstantInitializer( 12964 Context, var->getType()->isReferenceType(), &CacheCulprit); 12965 return *CacheHasConstInit; 12966 }; 12967 12968 if (var->getTLSKind() == VarDecl::TLS_Static) { 12969 if (var->getType().isDestructedType()) { 12970 // GNU C++98 edits for __thread, [basic.start.term]p3: 12971 // The type of an object with thread storage duration shall not 12972 // have a non-trivial destructor. 12973 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12974 if (getLangOpts().CPlusPlus11) 12975 Diag(var->getLocation(), diag::note_use_thread_local); 12976 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12977 if (!checkConstInit()) { 12978 // GNU C++98 edits for __thread, [basic.start.init]p4: 12979 // An object of thread storage duration shall not require dynamic 12980 // initialization. 12981 // FIXME: Need strict checking here. 12982 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12983 << CacheCulprit->getSourceRange(); 12984 if (getLangOpts().CPlusPlus11) 12985 Diag(var->getLocation(), diag::note_use_thread_local); 12986 } 12987 } 12988 } 12989 12990 // Apply section attributes and pragmas to global variables. 12991 bool GlobalStorage = var->hasGlobalStorage(); 12992 if (GlobalStorage && var->isThisDeclarationADefinition() && 12993 !inTemplateInstantiation()) { 12994 PragmaStack<StringLiteral *> *Stack = nullptr; 12995 int SectionFlags = ASTContext::PSF_Read; 12996 if (var->getType().isConstQualified()) 12997 Stack = &ConstSegStack; 12998 else if (!var->getInit()) { 12999 Stack = &BSSSegStack; 13000 SectionFlags |= ASTContext::PSF_Write; 13001 } else { 13002 Stack = &DataSegStack; 13003 SectionFlags |= ASTContext::PSF_Write; 13004 } 13005 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13006 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13007 SectionFlags |= ASTContext::PSF_Implicit; 13008 UnifySection(SA->getName(), SectionFlags, var); 13009 } else if (Stack->CurrentValue) { 13010 SectionFlags |= ASTContext::PSF_Implicit; 13011 auto SectionName = Stack->CurrentValue->getString(); 13012 var->addAttr(SectionAttr::CreateImplicit( 13013 Context, SectionName, Stack->CurrentPragmaLocation, 13014 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13015 if (UnifySection(SectionName, SectionFlags, var)) 13016 var->dropAttr<SectionAttr>(); 13017 } 13018 13019 // Apply the init_seg attribute if this has an initializer. If the 13020 // initializer turns out to not be dynamic, we'll end up ignoring this 13021 // attribute. 13022 if (CurInitSeg && var->getInit()) 13023 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13024 CurInitSegLoc, 13025 AttributeCommonInfo::AS_Pragma)); 13026 } 13027 13028 if (!var->getType()->isStructureType() && var->hasInit() && 13029 isa<InitListExpr>(var->getInit())) { 13030 const auto *ILE = cast<InitListExpr>(var->getInit()); 13031 unsigned NumInits = ILE->getNumInits(); 13032 if (NumInits > 2) 13033 for (unsigned I = 0; I < NumInits; ++I) { 13034 const auto *Init = ILE->getInit(I); 13035 if (!Init) 13036 break; 13037 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13038 if (!SL) 13039 break; 13040 13041 unsigned NumConcat = SL->getNumConcatenated(); 13042 // Diagnose missing comma in string array initialization. 13043 // Do not warn when all the elements in the initializer are concatenated 13044 // together. Do not warn for macros too. 13045 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13046 bool OnlyOneMissingComma = true; 13047 for (unsigned J = I + 1; J < NumInits; ++J) { 13048 const auto *Init = ILE->getInit(J); 13049 if (!Init) 13050 break; 13051 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13052 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13053 OnlyOneMissingComma = false; 13054 break; 13055 } 13056 } 13057 13058 if (OnlyOneMissingComma) { 13059 SmallVector<FixItHint, 1> Hints; 13060 for (unsigned i = 0; i < NumConcat - 1; ++i) 13061 Hints.push_back(FixItHint::CreateInsertion( 13062 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13063 13064 Diag(SL->getStrTokenLoc(1), 13065 diag::warn_concatenated_literal_array_init) 13066 << Hints; 13067 Diag(SL->getBeginLoc(), 13068 diag::note_concatenated_string_literal_silence); 13069 } 13070 // In any case, stop now. 13071 break; 13072 } 13073 } 13074 } 13075 13076 // All the following checks are C++ only. 13077 if (!getLangOpts().CPlusPlus) { 13078 // If this variable must be emitted, add it as an initializer for the 13079 // current module. 13080 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13081 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13082 return; 13083 } 13084 13085 QualType type = var->getType(); 13086 13087 if (var->hasAttr<BlocksAttr>()) 13088 getCurFunction()->addByrefBlockVar(var); 13089 13090 Expr *Init = var->getInit(); 13091 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13092 QualType baseType = Context.getBaseElementType(type); 13093 13094 // Check whether the initializer is sufficiently constant. 13095 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13096 (GlobalStorage || var->isConstexpr() || 13097 var->mightBeUsableInConstantExpressions(Context))) { 13098 // If this variable might have a constant initializer or might be usable in 13099 // constant expressions, check whether or not it actually is now. We can't 13100 // do this lazily, because the result might depend on things that change 13101 // later, such as which constexpr functions happen to be defined. 13102 SmallVector<PartialDiagnosticAt, 8> Notes; 13103 bool HasConstInit; 13104 if (!getLangOpts().CPlusPlus11) { 13105 // Prior to C++11, in contexts where a constant initializer is required, 13106 // the set of valid constant initializers is described by syntactic rules 13107 // in [expr.const]p2-6. 13108 // FIXME: Stricter checking for these rules would be useful for constinit / 13109 // -Wglobal-constructors. 13110 HasConstInit = checkConstInit(); 13111 13112 // Compute and cache the constant value, and remember that we have a 13113 // constant initializer. 13114 if (HasConstInit) { 13115 (void)var->checkForConstantInitialization(Notes); 13116 Notes.clear(); 13117 } else if (CacheCulprit) { 13118 Notes.emplace_back(CacheCulprit->getExprLoc(), 13119 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13120 Notes.back().second << CacheCulprit->getSourceRange(); 13121 } 13122 } else { 13123 // Evaluate the initializer to see if it's a constant initializer. 13124 HasConstInit = var->checkForConstantInitialization(Notes); 13125 } 13126 13127 if (HasConstInit) { 13128 // FIXME: Consider replacing the initializer with a ConstantExpr. 13129 } else if (var->isConstexpr()) { 13130 SourceLocation DiagLoc = var->getLocation(); 13131 // If the note doesn't add any useful information other than a source 13132 // location, fold it into the primary diagnostic. 13133 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13134 diag::note_invalid_subexpr_in_const_expr) { 13135 DiagLoc = Notes[0].first; 13136 Notes.clear(); 13137 } 13138 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13139 << var << Init->getSourceRange(); 13140 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13141 Diag(Notes[I].first, Notes[I].second); 13142 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13143 auto *Attr = var->getAttr<ConstInitAttr>(); 13144 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13145 << Init->getSourceRange(); 13146 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13147 << Attr->getRange() << Attr->isConstinit(); 13148 for (auto &it : Notes) 13149 Diag(it.first, it.second); 13150 } else if (IsGlobal && 13151 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13152 var->getLocation())) { 13153 // Warn about globals which don't have a constant initializer. Don't 13154 // warn about globals with a non-trivial destructor because we already 13155 // warned about them. 13156 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13157 if (!(RD && !RD->hasTrivialDestructor())) { 13158 // checkConstInit() here permits trivial default initialization even in 13159 // C++11 onwards, where such an initializer is not a constant initializer 13160 // but nonetheless doesn't require a global constructor. 13161 if (!checkConstInit()) 13162 Diag(var->getLocation(), diag::warn_global_constructor) 13163 << Init->getSourceRange(); 13164 } 13165 } 13166 } 13167 13168 // Require the destructor. 13169 if (!type->isDependentType()) 13170 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13171 FinalizeVarWithDestructor(var, recordType); 13172 13173 // If this variable must be emitted, add it as an initializer for the current 13174 // module. 13175 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13176 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13177 13178 // Build the bindings if this is a structured binding declaration. 13179 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13180 CheckCompleteDecompositionDeclaration(DD); 13181 } 13182 13183 /// Determines if a variable's alignment is dependent. 13184 static bool hasDependentAlignment(VarDecl *VD) { 13185 if (VD->getType()->isDependentType()) 13186 return true; 13187 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13188 if (I->isAlignmentDependent()) 13189 return true; 13190 return false; 13191 } 13192 13193 /// Check if VD needs to be dllexport/dllimport due to being in a 13194 /// dllexport/import function. 13195 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13196 assert(VD->isStaticLocal()); 13197 13198 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13199 13200 // Find outermost function when VD is in lambda function. 13201 while (FD && !getDLLAttr(FD) && 13202 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13203 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13204 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13205 } 13206 13207 if (!FD) 13208 return; 13209 13210 // Static locals inherit dll attributes from their function. 13211 if (Attr *A = getDLLAttr(FD)) { 13212 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13213 NewAttr->setInherited(true); 13214 VD->addAttr(NewAttr); 13215 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13216 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13217 NewAttr->setInherited(true); 13218 VD->addAttr(NewAttr); 13219 13220 // Export this function to enforce exporting this static variable even 13221 // if it is not used in this compilation unit. 13222 if (!FD->hasAttr<DLLExportAttr>()) 13223 FD->addAttr(NewAttr); 13224 13225 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13226 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13227 NewAttr->setInherited(true); 13228 VD->addAttr(NewAttr); 13229 } 13230 } 13231 13232 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13233 /// any semantic actions necessary after any initializer has been attached. 13234 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13235 // Note that we are no longer parsing the initializer for this declaration. 13236 ParsingInitForAutoVars.erase(ThisDecl); 13237 13238 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13239 if (!VD) 13240 return; 13241 13242 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13243 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13244 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13245 if (PragmaClangBSSSection.Valid) 13246 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13247 Context, PragmaClangBSSSection.SectionName, 13248 PragmaClangBSSSection.PragmaLocation, 13249 AttributeCommonInfo::AS_Pragma)); 13250 if (PragmaClangDataSection.Valid) 13251 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13252 Context, PragmaClangDataSection.SectionName, 13253 PragmaClangDataSection.PragmaLocation, 13254 AttributeCommonInfo::AS_Pragma)); 13255 if (PragmaClangRodataSection.Valid) 13256 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13257 Context, PragmaClangRodataSection.SectionName, 13258 PragmaClangRodataSection.PragmaLocation, 13259 AttributeCommonInfo::AS_Pragma)); 13260 if (PragmaClangRelroSection.Valid) 13261 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13262 Context, PragmaClangRelroSection.SectionName, 13263 PragmaClangRelroSection.PragmaLocation, 13264 AttributeCommonInfo::AS_Pragma)); 13265 } 13266 13267 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13268 for (auto *BD : DD->bindings()) { 13269 FinalizeDeclaration(BD); 13270 } 13271 } 13272 13273 checkAttributesAfterMerging(*this, *VD); 13274 13275 // Perform TLS alignment check here after attributes attached to the variable 13276 // which may affect the alignment have been processed. Only perform the check 13277 // if the target has a maximum TLS alignment (zero means no constraints). 13278 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13279 // Protect the check so that it's not performed on dependent types and 13280 // dependent alignments (we can't determine the alignment in that case). 13281 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13282 !VD->isInvalidDecl()) { 13283 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13284 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13285 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13286 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13287 << (unsigned)MaxAlignChars.getQuantity(); 13288 } 13289 } 13290 } 13291 13292 if (VD->isStaticLocal()) 13293 CheckStaticLocalForDllExport(VD); 13294 13295 // Perform check for initializers of device-side global variables. 13296 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13297 // 7.5). We must also apply the same checks to all __shared__ 13298 // variables whether they are local or not. CUDA also allows 13299 // constant initializers for __constant__ and __device__ variables. 13300 if (getLangOpts().CUDA) 13301 checkAllowedCUDAInitializer(VD); 13302 13303 // Grab the dllimport or dllexport attribute off of the VarDecl. 13304 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13305 13306 // Imported static data members cannot be defined out-of-line. 13307 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13308 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13309 VD->isThisDeclarationADefinition()) { 13310 // We allow definitions of dllimport class template static data members 13311 // with a warning. 13312 CXXRecordDecl *Context = 13313 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13314 bool IsClassTemplateMember = 13315 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13316 Context->getDescribedClassTemplate(); 13317 13318 Diag(VD->getLocation(), 13319 IsClassTemplateMember 13320 ? diag::warn_attribute_dllimport_static_field_definition 13321 : diag::err_attribute_dllimport_static_field_definition); 13322 Diag(IA->getLocation(), diag::note_attribute); 13323 if (!IsClassTemplateMember) 13324 VD->setInvalidDecl(); 13325 } 13326 } 13327 13328 // dllimport/dllexport variables cannot be thread local, their TLS index 13329 // isn't exported with the variable. 13330 if (DLLAttr && VD->getTLSKind()) { 13331 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13332 if (F && getDLLAttr(F)) { 13333 assert(VD->isStaticLocal()); 13334 // But if this is a static local in a dlimport/dllexport function, the 13335 // function will never be inlined, which means the var would never be 13336 // imported, so having it marked import/export is safe. 13337 } else { 13338 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13339 << DLLAttr; 13340 VD->setInvalidDecl(); 13341 } 13342 } 13343 13344 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13345 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13346 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13347 << Attr; 13348 VD->dropAttr<UsedAttr>(); 13349 } 13350 } 13351 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13352 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13353 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13354 << Attr; 13355 VD->dropAttr<RetainAttr>(); 13356 } 13357 } 13358 13359 const DeclContext *DC = VD->getDeclContext(); 13360 // If there's a #pragma GCC visibility in scope, and this isn't a class 13361 // member, set the visibility of this variable. 13362 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13363 AddPushedVisibilityAttribute(VD); 13364 13365 // FIXME: Warn on unused var template partial specializations. 13366 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13367 MarkUnusedFileScopedDecl(VD); 13368 13369 // Now we have parsed the initializer and can update the table of magic 13370 // tag values. 13371 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13372 !VD->getType()->isIntegralOrEnumerationType()) 13373 return; 13374 13375 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13376 const Expr *MagicValueExpr = VD->getInit(); 13377 if (!MagicValueExpr) { 13378 continue; 13379 } 13380 Optional<llvm::APSInt> MagicValueInt; 13381 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13382 Diag(I->getRange().getBegin(), 13383 diag::err_type_tag_for_datatype_not_ice) 13384 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13385 continue; 13386 } 13387 if (MagicValueInt->getActiveBits() > 64) { 13388 Diag(I->getRange().getBegin(), 13389 diag::err_type_tag_for_datatype_too_large) 13390 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13391 continue; 13392 } 13393 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13394 RegisterTypeTagForDatatype(I->getArgumentKind(), 13395 MagicValue, 13396 I->getMatchingCType(), 13397 I->getLayoutCompatible(), 13398 I->getMustBeNull()); 13399 } 13400 } 13401 13402 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13403 auto *VD = dyn_cast<VarDecl>(DD); 13404 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13405 } 13406 13407 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13408 ArrayRef<Decl *> Group) { 13409 SmallVector<Decl*, 8> Decls; 13410 13411 if (DS.isTypeSpecOwned()) 13412 Decls.push_back(DS.getRepAsDecl()); 13413 13414 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13415 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13416 bool DiagnosedMultipleDecomps = false; 13417 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13418 bool DiagnosedNonDeducedAuto = false; 13419 13420 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13421 if (Decl *D = Group[i]) { 13422 // For declarators, there are some additional syntactic-ish checks we need 13423 // to perform. 13424 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13425 if (!FirstDeclaratorInGroup) 13426 FirstDeclaratorInGroup = DD; 13427 if (!FirstDecompDeclaratorInGroup) 13428 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13429 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13430 !hasDeducedAuto(DD)) 13431 FirstNonDeducedAutoInGroup = DD; 13432 13433 if (FirstDeclaratorInGroup != DD) { 13434 // A decomposition declaration cannot be combined with any other 13435 // declaration in the same group. 13436 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13437 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13438 diag::err_decomp_decl_not_alone) 13439 << FirstDeclaratorInGroup->getSourceRange() 13440 << DD->getSourceRange(); 13441 DiagnosedMultipleDecomps = true; 13442 } 13443 13444 // A declarator that uses 'auto' in any way other than to declare a 13445 // variable with a deduced type cannot be combined with any other 13446 // declarator in the same group. 13447 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13448 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13449 diag::err_auto_non_deduced_not_alone) 13450 << FirstNonDeducedAutoInGroup->getType() 13451 ->hasAutoForTrailingReturnType() 13452 << FirstDeclaratorInGroup->getSourceRange() 13453 << DD->getSourceRange(); 13454 DiagnosedNonDeducedAuto = true; 13455 } 13456 } 13457 } 13458 13459 Decls.push_back(D); 13460 } 13461 } 13462 13463 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13464 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13465 handleTagNumbering(Tag, S); 13466 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13467 getLangOpts().CPlusPlus) 13468 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13469 } 13470 } 13471 13472 return BuildDeclaratorGroup(Decls); 13473 } 13474 13475 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13476 /// group, performing any necessary semantic checking. 13477 Sema::DeclGroupPtrTy 13478 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13479 // C++14 [dcl.spec.auto]p7: (DR1347) 13480 // If the type that replaces the placeholder type is not the same in each 13481 // deduction, the program is ill-formed. 13482 if (Group.size() > 1) { 13483 QualType Deduced; 13484 VarDecl *DeducedDecl = nullptr; 13485 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13486 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13487 if (!D || D->isInvalidDecl()) 13488 break; 13489 DeducedType *DT = D->getType()->getContainedDeducedType(); 13490 if (!DT || DT->getDeducedType().isNull()) 13491 continue; 13492 if (Deduced.isNull()) { 13493 Deduced = DT->getDeducedType(); 13494 DeducedDecl = D; 13495 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13496 auto *AT = dyn_cast<AutoType>(DT); 13497 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13498 diag::err_auto_different_deductions) 13499 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13500 << DeducedDecl->getDeclName() << DT->getDeducedType() 13501 << D->getDeclName(); 13502 if (DeducedDecl->hasInit()) 13503 Dia << DeducedDecl->getInit()->getSourceRange(); 13504 if (D->getInit()) 13505 Dia << D->getInit()->getSourceRange(); 13506 D->setInvalidDecl(); 13507 break; 13508 } 13509 } 13510 } 13511 13512 ActOnDocumentableDecls(Group); 13513 13514 return DeclGroupPtrTy::make( 13515 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13516 } 13517 13518 void Sema::ActOnDocumentableDecl(Decl *D) { 13519 ActOnDocumentableDecls(D); 13520 } 13521 13522 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13523 // Don't parse the comment if Doxygen diagnostics are ignored. 13524 if (Group.empty() || !Group[0]) 13525 return; 13526 13527 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13528 Group[0]->getLocation()) && 13529 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13530 Group[0]->getLocation())) 13531 return; 13532 13533 if (Group.size() >= 2) { 13534 // This is a decl group. Normally it will contain only declarations 13535 // produced from declarator list. But in case we have any definitions or 13536 // additional declaration references: 13537 // 'typedef struct S {} S;' 13538 // 'typedef struct S *S;' 13539 // 'struct S *pS;' 13540 // FinalizeDeclaratorGroup adds these as separate declarations. 13541 Decl *MaybeTagDecl = Group[0]; 13542 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13543 Group = Group.slice(1); 13544 } 13545 } 13546 13547 // FIMXE: We assume every Decl in the group is in the same file. 13548 // This is false when preprocessor constructs the group from decls in 13549 // different files (e. g. macros or #include). 13550 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13551 } 13552 13553 /// Common checks for a parameter-declaration that should apply to both function 13554 /// parameters and non-type template parameters. 13555 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13556 // Check that there are no default arguments inside the type of this 13557 // parameter. 13558 if (getLangOpts().CPlusPlus) 13559 CheckExtraCXXDefaultArguments(D); 13560 13561 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13562 if (D.getCXXScopeSpec().isSet()) { 13563 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13564 << D.getCXXScopeSpec().getRange(); 13565 } 13566 13567 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13568 // simple identifier except [...irrelevant cases...]. 13569 switch (D.getName().getKind()) { 13570 case UnqualifiedIdKind::IK_Identifier: 13571 break; 13572 13573 case UnqualifiedIdKind::IK_OperatorFunctionId: 13574 case UnqualifiedIdKind::IK_ConversionFunctionId: 13575 case UnqualifiedIdKind::IK_LiteralOperatorId: 13576 case UnqualifiedIdKind::IK_ConstructorName: 13577 case UnqualifiedIdKind::IK_DestructorName: 13578 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13579 case UnqualifiedIdKind::IK_DeductionGuideName: 13580 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13581 << GetNameForDeclarator(D).getName(); 13582 break; 13583 13584 case UnqualifiedIdKind::IK_TemplateId: 13585 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13586 // GetNameForDeclarator would not produce a useful name in this case. 13587 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13588 break; 13589 } 13590 } 13591 13592 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13593 /// to introduce parameters into function prototype scope. 13594 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13595 const DeclSpec &DS = D.getDeclSpec(); 13596 13597 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13598 13599 // C++03 [dcl.stc]p2 also permits 'auto'. 13600 StorageClass SC = SC_None; 13601 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13602 SC = SC_Register; 13603 // In C++11, the 'register' storage class specifier is deprecated. 13604 // In C++17, it is not allowed, but we tolerate it as an extension. 13605 if (getLangOpts().CPlusPlus11) { 13606 Diag(DS.getStorageClassSpecLoc(), 13607 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13608 : diag::warn_deprecated_register) 13609 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13610 } 13611 } else if (getLangOpts().CPlusPlus && 13612 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13613 SC = SC_Auto; 13614 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13615 Diag(DS.getStorageClassSpecLoc(), 13616 diag::err_invalid_storage_class_in_func_decl); 13617 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13618 } 13619 13620 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13621 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13622 << DeclSpec::getSpecifierName(TSCS); 13623 if (DS.isInlineSpecified()) 13624 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13625 << getLangOpts().CPlusPlus17; 13626 if (DS.hasConstexprSpecifier()) 13627 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13628 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13629 13630 DiagnoseFunctionSpecifiers(DS); 13631 13632 CheckFunctionOrTemplateParamDeclarator(S, D); 13633 13634 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13635 QualType parmDeclType = TInfo->getType(); 13636 13637 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13638 IdentifierInfo *II = D.getIdentifier(); 13639 if (II) { 13640 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13641 ForVisibleRedeclaration); 13642 LookupName(R, S); 13643 if (R.isSingleResult()) { 13644 NamedDecl *PrevDecl = R.getFoundDecl(); 13645 if (PrevDecl->isTemplateParameter()) { 13646 // Maybe we will complain about the shadowed template parameter. 13647 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13648 // Just pretend that we didn't see the previous declaration. 13649 PrevDecl = nullptr; 13650 } else if (S->isDeclScope(PrevDecl)) { 13651 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13652 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13653 13654 // Recover by removing the name 13655 II = nullptr; 13656 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13657 D.setInvalidType(true); 13658 } 13659 } 13660 } 13661 13662 // Temporarily put parameter variables in the translation unit, not 13663 // the enclosing context. This prevents them from accidentally 13664 // looking like class members in C++. 13665 ParmVarDecl *New = 13666 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13667 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13668 13669 if (D.isInvalidType()) 13670 New->setInvalidDecl(); 13671 13672 assert(S->isFunctionPrototypeScope()); 13673 assert(S->getFunctionPrototypeDepth() >= 1); 13674 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13675 S->getNextFunctionPrototypeIndex()); 13676 13677 // Add the parameter declaration into this scope. 13678 S->AddDecl(New); 13679 if (II) 13680 IdResolver.AddDecl(New); 13681 13682 ProcessDeclAttributes(S, New, D); 13683 13684 if (D.getDeclSpec().isModulePrivateSpecified()) 13685 Diag(New->getLocation(), diag::err_module_private_local) 13686 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13687 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13688 13689 if (New->hasAttr<BlocksAttr>()) { 13690 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13691 } 13692 13693 if (getLangOpts().OpenCL) 13694 deduceOpenCLAddressSpace(New); 13695 13696 return New; 13697 } 13698 13699 /// Synthesizes a variable for a parameter arising from a 13700 /// typedef. 13701 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13702 SourceLocation Loc, 13703 QualType T) { 13704 /* FIXME: setting StartLoc == Loc. 13705 Would it be worth to modify callers so as to provide proper source 13706 location for the unnamed parameters, embedding the parameter's type? */ 13707 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13708 T, Context.getTrivialTypeSourceInfo(T, Loc), 13709 SC_None, nullptr); 13710 Param->setImplicit(); 13711 return Param; 13712 } 13713 13714 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13715 // Don't diagnose unused-parameter errors in template instantiations; we 13716 // will already have done so in the template itself. 13717 if (inTemplateInstantiation()) 13718 return; 13719 13720 for (const ParmVarDecl *Parameter : Parameters) { 13721 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13722 !Parameter->hasAttr<UnusedAttr>()) { 13723 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13724 << Parameter->getDeclName(); 13725 } 13726 } 13727 } 13728 13729 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13730 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13731 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13732 return; 13733 13734 // Warn if the return value is pass-by-value and larger than the specified 13735 // threshold. 13736 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13737 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13738 if (Size > LangOpts.NumLargeByValueCopy) 13739 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13740 } 13741 13742 // Warn if any parameter is pass-by-value and larger than the specified 13743 // threshold. 13744 for (const ParmVarDecl *Parameter : Parameters) { 13745 QualType T = Parameter->getType(); 13746 if (T->isDependentType() || !T.isPODType(Context)) 13747 continue; 13748 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13749 if (Size > LangOpts.NumLargeByValueCopy) 13750 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13751 << Parameter << Size; 13752 } 13753 } 13754 13755 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13756 SourceLocation NameLoc, IdentifierInfo *Name, 13757 QualType T, TypeSourceInfo *TSInfo, 13758 StorageClass SC) { 13759 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13760 if (getLangOpts().ObjCAutoRefCount && 13761 T.getObjCLifetime() == Qualifiers::OCL_None && 13762 T->isObjCLifetimeType()) { 13763 13764 Qualifiers::ObjCLifetime lifetime; 13765 13766 // Special cases for arrays: 13767 // - if it's const, use __unsafe_unretained 13768 // - otherwise, it's an error 13769 if (T->isArrayType()) { 13770 if (!T.isConstQualified()) { 13771 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13772 DelayedDiagnostics.add( 13773 sema::DelayedDiagnostic::makeForbiddenType( 13774 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13775 else 13776 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13777 << TSInfo->getTypeLoc().getSourceRange(); 13778 } 13779 lifetime = Qualifiers::OCL_ExplicitNone; 13780 } else { 13781 lifetime = T->getObjCARCImplicitLifetime(); 13782 } 13783 T = Context.getLifetimeQualifiedType(T, lifetime); 13784 } 13785 13786 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13787 Context.getAdjustedParameterType(T), 13788 TSInfo, SC, nullptr); 13789 13790 // Make a note if we created a new pack in the scope of a lambda, so that 13791 // we know that references to that pack must also be expanded within the 13792 // lambda scope. 13793 if (New->isParameterPack()) 13794 if (auto *LSI = getEnclosingLambda()) 13795 LSI->LocalPacks.push_back(New); 13796 13797 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13798 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13799 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13800 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13801 13802 // Parameters can not be abstract class types. 13803 // For record types, this is done by the AbstractClassUsageDiagnoser once 13804 // the class has been completely parsed. 13805 if (!CurContext->isRecord() && 13806 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13807 AbstractParamType)) 13808 New->setInvalidDecl(); 13809 13810 // Parameter declarators cannot be interface types. All ObjC objects are 13811 // passed by reference. 13812 if (T->isObjCObjectType()) { 13813 SourceLocation TypeEndLoc = 13814 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13815 Diag(NameLoc, 13816 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13817 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13818 T = Context.getObjCObjectPointerType(T); 13819 New->setType(T); 13820 } 13821 13822 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13823 // duration shall not be qualified by an address-space qualifier." 13824 // Since all parameters have automatic store duration, they can not have 13825 // an address space. 13826 if (T.getAddressSpace() != LangAS::Default && 13827 // OpenCL allows function arguments declared to be an array of a type 13828 // to be qualified with an address space. 13829 !(getLangOpts().OpenCL && 13830 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13831 Diag(NameLoc, diag::err_arg_with_address_space); 13832 New->setInvalidDecl(); 13833 } 13834 13835 // PPC MMA non-pointer types are not allowed as function argument types. 13836 if (Context.getTargetInfo().getTriple().isPPC64() && 13837 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13838 New->setInvalidDecl(); 13839 } 13840 13841 return New; 13842 } 13843 13844 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13845 SourceLocation LocAfterDecls) { 13846 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13847 13848 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13849 // for a K&R function. 13850 if (!FTI.hasPrototype) { 13851 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13852 --i; 13853 if (FTI.Params[i].Param == nullptr) { 13854 SmallString<256> Code; 13855 llvm::raw_svector_ostream(Code) 13856 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13857 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13858 << FTI.Params[i].Ident 13859 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13860 13861 // Implicitly declare the argument as type 'int' for lack of a better 13862 // type. 13863 AttributeFactory attrs; 13864 DeclSpec DS(attrs); 13865 const char* PrevSpec; // unused 13866 unsigned DiagID; // unused 13867 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13868 DiagID, Context.getPrintingPolicy()); 13869 // Use the identifier location for the type source range. 13870 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13871 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13872 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13873 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13874 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13875 } 13876 } 13877 } 13878 } 13879 13880 Decl * 13881 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13882 MultiTemplateParamsArg TemplateParameterLists, 13883 SkipBodyInfo *SkipBody) { 13884 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13885 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13886 Scope *ParentScope = FnBodyScope->getParent(); 13887 13888 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13889 // we define a non-templated function definition, we will create a declaration 13890 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13891 // The base function declaration will have the equivalent of an `omp declare 13892 // variant` annotation which specifies the mangled definition as a 13893 // specialization function under the OpenMP context defined as part of the 13894 // `omp begin declare variant`. 13895 SmallVector<FunctionDecl *, 4> Bases; 13896 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13897 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13898 ParentScope, D, TemplateParameterLists, Bases); 13899 13900 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13901 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13902 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13903 13904 if (!Bases.empty()) 13905 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13906 13907 return Dcl; 13908 } 13909 13910 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13911 Consumer.HandleInlineFunctionDefinition(D); 13912 } 13913 13914 static bool 13915 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13916 const FunctionDecl *&PossiblePrototype) { 13917 // Don't warn about invalid declarations. 13918 if (FD->isInvalidDecl()) 13919 return false; 13920 13921 // Or declarations that aren't global. 13922 if (!FD->isGlobal()) 13923 return false; 13924 13925 // Don't warn about C++ member functions. 13926 if (isa<CXXMethodDecl>(FD)) 13927 return false; 13928 13929 // Don't warn about 'main'. 13930 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13931 if (IdentifierInfo *II = FD->getIdentifier()) 13932 if (II->isStr("main") || II->isStr("efi_main")) 13933 return false; 13934 13935 // Don't warn about inline functions. 13936 if (FD->isInlined()) 13937 return false; 13938 13939 // Don't warn about function templates. 13940 if (FD->getDescribedFunctionTemplate()) 13941 return false; 13942 13943 // Don't warn about function template specializations. 13944 if (FD->isFunctionTemplateSpecialization()) 13945 return false; 13946 13947 // Don't warn for OpenCL kernels. 13948 if (FD->hasAttr<OpenCLKernelAttr>()) 13949 return false; 13950 13951 // Don't warn on explicitly deleted functions. 13952 if (FD->isDeleted()) 13953 return false; 13954 13955 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13956 Prev; Prev = Prev->getPreviousDecl()) { 13957 // Ignore any declarations that occur in function or method 13958 // scope, because they aren't visible from the header. 13959 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13960 continue; 13961 13962 PossiblePrototype = Prev; 13963 return Prev->getType()->isFunctionNoProtoType(); 13964 } 13965 13966 return true; 13967 } 13968 13969 void 13970 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13971 const FunctionDecl *EffectiveDefinition, 13972 SkipBodyInfo *SkipBody) { 13973 const FunctionDecl *Definition = EffectiveDefinition; 13974 if (!Definition && 13975 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13976 return; 13977 13978 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13979 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13980 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13981 // A merged copy of the same function, instantiated as a member of 13982 // the same class, is OK. 13983 if (declaresSameEntity(OrigFD, OrigDef) && 13984 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13985 cast<Decl>(FD->getLexicalDeclContext()))) 13986 return; 13987 } 13988 } 13989 } 13990 13991 if (canRedefineFunction(Definition, getLangOpts())) 13992 return; 13993 13994 // Don't emit an error when this is redefinition of a typo-corrected 13995 // definition. 13996 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13997 return; 13998 13999 // If we don't have a visible definition of the function, and it's inline or 14000 // a template, skip the new definition. 14001 if (SkipBody && !hasVisibleDefinition(Definition) && 14002 (Definition->getFormalLinkage() == InternalLinkage || 14003 Definition->isInlined() || 14004 Definition->getDescribedFunctionTemplate() || 14005 Definition->getNumTemplateParameterLists())) { 14006 SkipBody->ShouldSkip = true; 14007 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14008 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14009 makeMergedDefinitionVisible(TD); 14010 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14011 return; 14012 } 14013 14014 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14015 Definition->getStorageClass() == SC_Extern) 14016 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14017 << FD << getLangOpts().CPlusPlus; 14018 else 14019 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14020 14021 Diag(Definition->getLocation(), diag::note_previous_definition); 14022 FD->setInvalidDecl(); 14023 } 14024 14025 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14026 Sema &S) { 14027 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14028 14029 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14030 LSI->CallOperator = CallOperator; 14031 LSI->Lambda = LambdaClass; 14032 LSI->ReturnType = CallOperator->getReturnType(); 14033 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14034 14035 if (LCD == LCD_None) 14036 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14037 else if (LCD == LCD_ByCopy) 14038 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14039 else if (LCD == LCD_ByRef) 14040 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14041 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14042 14043 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14044 LSI->Mutable = !CallOperator->isConst(); 14045 14046 // Add the captures to the LSI so they can be noted as already 14047 // captured within tryCaptureVar. 14048 auto I = LambdaClass->field_begin(); 14049 for (const auto &C : LambdaClass->captures()) { 14050 if (C.capturesVariable()) { 14051 VarDecl *VD = C.getCapturedVar(); 14052 if (VD->isInitCapture()) 14053 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14054 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14055 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14056 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14057 /*EllipsisLoc*/C.isPackExpansion() 14058 ? C.getEllipsisLoc() : SourceLocation(), 14059 I->getType(), /*Invalid*/false); 14060 14061 } else if (C.capturesThis()) { 14062 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14063 C.getCaptureKind() == LCK_StarThis); 14064 } else { 14065 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14066 I->getType()); 14067 } 14068 ++I; 14069 } 14070 } 14071 14072 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14073 SkipBodyInfo *SkipBody) { 14074 if (!D) { 14075 // Parsing the function declaration failed in some way. Push on a fake scope 14076 // anyway so we can try to parse the function body. 14077 PushFunctionScope(); 14078 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14079 return D; 14080 } 14081 14082 FunctionDecl *FD = nullptr; 14083 14084 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14085 FD = FunTmpl->getTemplatedDecl(); 14086 else 14087 FD = cast<FunctionDecl>(D); 14088 14089 // Do not push if it is a lambda because one is already pushed when building 14090 // the lambda in ActOnStartOfLambdaDefinition(). 14091 if (!isLambdaCallOperator(FD)) 14092 PushExpressionEvaluationContext( 14093 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14094 : ExprEvalContexts.back().Context); 14095 14096 // Check for defining attributes before the check for redefinition. 14097 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14098 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14099 FD->dropAttr<AliasAttr>(); 14100 FD->setInvalidDecl(); 14101 } 14102 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14103 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14104 FD->dropAttr<IFuncAttr>(); 14105 FD->setInvalidDecl(); 14106 } 14107 14108 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14109 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14110 Ctor->isDefaultConstructor() && 14111 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14112 // If this is an MS ABI dllexport default constructor, instantiate any 14113 // default arguments. 14114 InstantiateDefaultCtorDefaultArgs(Ctor); 14115 } 14116 } 14117 14118 // See if this is a redefinition. If 'will have body' (or similar) is already 14119 // set, then these checks were already performed when it was set. 14120 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14121 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14122 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14123 14124 // If we're skipping the body, we're done. Don't enter the scope. 14125 if (SkipBody && SkipBody->ShouldSkip) 14126 return D; 14127 } 14128 14129 // Mark this function as "will have a body eventually". This lets users to 14130 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14131 // this function. 14132 FD->setWillHaveBody(); 14133 14134 // If we are instantiating a generic lambda call operator, push 14135 // a LambdaScopeInfo onto the function stack. But use the information 14136 // that's already been calculated (ActOnLambdaExpr) to prime the current 14137 // LambdaScopeInfo. 14138 // When the template operator is being specialized, the LambdaScopeInfo, 14139 // has to be properly restored so that tryCaptureVariable doesn't try 14140 // and capture any new variables. In addition when calculating potential 14141 // captures during transformation of nested lambdas, it is necessary to 14142 // have the LSI properly restored. 14143 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14144 assert(inTemplateInstantiation() && 14145 "There should be an active template instantiation on the stack " 14146 "when instantiating a generic lambda!"); 14147 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14148 } else { 14149 // Enter a new function scope 14150 PushFunctionScope(); 14151 } 14152 14153 // Builtin functions cannot be defined. 14154 if (unsigned BuiltinID = FD->getBuiltinID()) { 14155 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14156 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14157 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14158 FD->setInvalidDecl(); 14159 } 14160 } 14161 14162 // The return type of a function definition must be complete 14163 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14164 QualType ResultType = FD->getReturnType(); 14165 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14166 !FD->isInvalidDecl() && 14167 RequireCompleteType(FD->getLocation(), ResultType, 14168 diag::err_func_def_incomplete_result)) 14169 FD->setInvalidDecl(); 14170 14171 if (FnBodyScope) 14172 PushDeclContext(FnBodyScope, FD); 14173 14174 // Check the validity of our function parameters 14175 CheckParmsForFunctionDef(FD->parameters(), 14176 /*CheckParameterNames=*/true); 14177 14178 // Add non-parameter declarations already in the function to the current 14179 // scope. 14180 if (FnBodyScope) { 14181 for (Decl *NPD : FD->decls()) { 14182 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14183 if (!NonParmDecl) 14184 continue; 14185 assert(!isa<ParmVarDecl>(NonParmDecl) && 14186 "parameters should not be in newly created FD yet"); 14187 14188 // If the decl has a name, make it accessible in the current scope. 14189 if (NonParmDecl->getDeclName()) 14190 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14191 14192 // Similarly, dive into enums and fish their constants out, making them 14193 // accessible in this scope. 14194 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14195 for (auto *EI : ED->enumerators()) 14196 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14197 } 14198 } 14199 } 14200 14201 // Introduce our parameters into the function scope 14202 for (auto Param : FD->parameters()) { 14203 Param->setOwningFunction(FD); 14204 14205 // If this has an identifier, add it to the scope stack. 14206 if (Param->getIdentifier() && FnBodyScope) { 14207 CheckShadow(FnBodyScope, Param); 14208 14209 PushOnScopeChains(Param, FnBodyScope); 14210 } 14211 } 14212 14213 // Ensure that the function's exception specification is instantiated. 14214 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14215 ResolveExceptionSpec(D->getLocation(), FPT); 14216 14217 // dllimport cannot be applied to non-inline function definitions. 14218 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14219 !FD->isTemplateInstantiation()) { 14220 assert(!FD->hasAttr<DLLExportAttr>()); 14221 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14222 FD->setInvalidDecl(); 14223 return D; 14224 } 14225 // We want to attach documentation to original Decl (which might be 14226 // a function template). 14227 ActOnDocumentableDecl(D); 14228 if (getCurLexicalContext()->isObjCContainer() && 14229 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14230 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14231 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14232 14233 return D; 14234 } 14235 14236 /// Given the set of return statements within a function body, 14237 /// compute the variables that are subject to the named return value 14238 /// optimization. 14239 /// 14240 /// Each of the variables that is subject to the named return value 14241 /// optimization will be marked as NRVO variables in the AST, and any 14242 /// return statement that has a marked NRVO variable as its NRVO candidate can 14243 /// use the named return value optimization. 14244 /// 14245 /// This function applies a very simplistic algorithm for NRVO: if every return 14246 /// statement in the scope of a variable has the same NRVO candidate, that 14247 /// candidate is an NRVO variable. 14248 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14249 ReturnStmt **Returns = Scope->Returns.data(); 14250 14251 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14252 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14253 if (!NRVOCandidate->isNRVOVariable()) 14254 Returns[I]->setNRVOCandidate(nullptr); 14255 } 14256 } 14257 } 14258 14259 bool Sema::canDelayFunctionBody(const Declarator &D) { 14260 // We can't delay parsing the body of a constexpr function template (yet). 14261 if (D.getDeclSpec().hasConstexprSpecifier()) 14262 return false; 14263 14264 // We can't delay parsing the body of a function template with a deduced 14265 // return type (yet). 14266 if (D.getDeclSpec().hasAutoTypeSpec()) { 14267 // If the placeholder introduces a non-deduced trailing return type, 14268 // we can still delay parsing it. 14269 if (D.getNumTypeObjects()) { 14270 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14271 if (Outer.Kind == DeclaratorChunk::Function && 14272 Outer.Fun.hasTrailingReturnType()) { 14273 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14274 return Ty.isNull() || !Ty->isUndeducedType(); 14275 } 14276 } 14277 return false; 14278 } 14279 14280 return true; 14281 } 14282 14283 bool Sema::canSkipFunctionBody(Decl *D) { 14284 // We cannot skip the body of a function (or function template) which is 14285 // constexpr, since we may need to evaluate its body in order to parse the 14286 // rest of the file. 14287 // We cannot skip the body of a function with an undeduced return type, 14288 // because any callers of that function need to know the type. 14289 if (const FunctionDecl *FD = D->getAsFunction()) { 14290 if (FD->isConstexpr()) 14291 return false; 14292 // We can't simply call Type::isUndeducedType here, because inside template 14293 // auto can be deduced to a dependent type, which is not considered 14294 // "undeduced". 14295 if (FD->getReturnType()->getContainedDeducedType()) 14296 return false; 14297 } 14298 return Consumer.shouldSkipFunctionBody(D); 14299 } 14300 14301 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14302 if (!Decl) 14303 return nullptr; 14304 if (FunctionDecl *FD = Decl->getAsFunction()) 14305 FD->setHasSkippedBody(); 14306 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14307 MD->setHasSkippedBody(); 14308 return Decl; 14309 } 14310 14311 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14312 return ActOnFinishFunctionBody(D, BodyArg, false); 14313 } 14314 14315 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14316 /// body. 14317 class ExitFunctionBodyRAII { 14318 public: 14319 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14320 ~ExitFunctionBodyRAII() { 14321 if (!IsLambda) 14322 S.PopExpressionEvaluationContext(); 14323 } 14324 14325 private: 14326 Sema &S; 14327 bool IsLambda = false; 14328 }; 14329 14330 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14331 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14332 14333 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14334 if (EscapeInfo.count(BD)) 14335 return EscapeInfo[BD]; 14336 14337 bool R = false; 14338 const BlockDecl *CurBD = BD; 14339 14340 do { 14341 R = !CurBD->doesNotEscape(); 14342 if (R) 14343 break; 14344 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14345 } while (CurBD); 14346 14347 return EscapeInfo[BD] = R; 14348 }; 14349 14350 // If the location where 'self' is implicitly retained is inside a escaping 14351 // block, emit a diagnostic. 14352 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14353 S.ImplicitlyRetainedSelfLocs) 14354 if (IsOrNestedInEscapingBlock(P.second)) 14355 S.Diag(P.first, diag::warn_implicitly_retains_self) 14356 << FixItHint::CreateInsertion(P.first, "self->"); 14357 } 14358 14359 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14360 bool IsInstantiation) { 14361 FunctionScopeInfo *FSI = getCurFunction(); 14362 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14363 14364 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14365 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14366 14367 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14368 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14369 14370 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14371 CheckCompletedCoroutineBody(FD, Body); 14372 14373 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14374 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14375 // meant to pop the context added in ActOnStartOfFunctionDef(). 14376 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14377 14378 if (FD) { 14379 FD->setBody(Body); 14380 FD->setWillHaveBody(false); 14381 14382 if (getLangOpts().CPlusPlus14) { 14383 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14384 FD->getReturnType()->isUndeducedType()) { 14385 // If the function has a deduced result type but contains no 'return' 14386 // statements, the result type as written must be exactly 'auto', and 14387 // the deduced result type is 'void'. 14388 if (!FD->getReturnType()->getAs<AutoType>()) { 14389 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14390 << FD->getReturnType(); 14391 FD->setInvalidDecl(); 14392 } else { 14393 // Substitute 'void' for the 'auto' in the type. 14394 TypeLoc ResultType = getReturnTypeLoc(FD); 14395 Context.adjustDeducedFunctionResultType( 14396 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14397 } 14398 } 14399 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14400 // In C++11, we don't use 'auto' deduction rules for lambda call 14401 // operators because we don't support return type deduction. 14402 auto *LSI = getCurLambda(); 14403 if (LSI->HasImplicitReturnType) { 14404 deduceClosureReturnType(*LSI); 14405 14406 // C++11 [expr.prim.lambda]p4: 14407 // [...] if there are no return statements in the compound-statement 14408 // [the deduced type is] the type void 14409 QualType RetType = 14410 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14411 14412 // Update the return type to the deduced type. 14413 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14414 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14415 Proto->getExtProtoInfo())); 14416 } 14417 } 14418 14419 // If the function implicitly returns zero (like 'main') or is naked, 14420 // don't complain about missing return statements. 14421 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14422 WP.disableCheckFallThrough(); 14423 14424 // MSVC permits the use of pure specifier (=0) on function definition, 14425 // defined at class scope, warn about this non-standard construct. 14426 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14427 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14428 14429 if (!FD->isInvalidDecl()) { 14430 // Don't diagnose unused parameters of defaulted or deleted functions. 14431 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14432 DiagnoseUnusedParameters(FD->parameters()); 14433 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14434 FD->getReturnType(), FD); 14435 14436 // If this is a structor, we need a vtable. 14437 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14438 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14439 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14440 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14441 14442 // Try to apply the named return value optimization. We have to check 14443 // if we can do this here because lambdas keep return statements around 14444 // to deduce an implicit return type. 14445 if (FD->getReturnType()->isRecordType() && 14446 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14447 computeNRVO(Body, FSI); 14448 } 14449 14450 // GNU warning -Wmissing-prototypes: 14451 // Warn if a global function is defined without a previous 14452 // prototype declaration. This warning is issued even if the 14453 // definition itself provides a prototype. The aim is to detect 14454 // global functions that fail to be declared in header files. 14455 const FunctionDecl *PossiblePrototype = nullptr; 14456 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14457 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14458 14459 if (PossiblePrototype) { 14460 // We found a declaration that is not a prototype, 14461 // but that could be a zero-parameter prototype 14462 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14463 TypeLoc TL = TI->getTypeLoc(); 14464 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14465 Diag(PossiblePrototype->getLocation(), 14466 diag::note_declaration_not_a_prototype) 14467 << (FD->getNumParams() != 0) 14468 << (FD->getNumParams() == 0 14469 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14470 : FixItHint{}); 14471 } 14472 } else { 14473 // Returns true if the token beginning at this Loc is `const`. 14474 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14475 const LangOptions &LangOpts) { 14476 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14477 if (LocInfo.first.isInvalid()) 14478 return false; 14479 14480 bool Invalid = false; 14481 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14482 if (Invalid) 14483 return false; 14484 14485 if (LocInfo.second > Buffer.size()) 14486 return false; 14487 14488 const char *LexStart = Buffer.data() + LocInfo.second; 14489 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14490 14491 return StartTok.consume_front("const") && 14492 (StartTok.empty() || isWhitespace(StartTok[0]) || 14493 StartTok.startswith("/*") || StartTok.startswith("//")); 14494 }; 14495 14496 auto findBeginLoc = [&]() { 14497 // If the return type has `const` qualifier, we want to insert 14498 // `static` before `const` (and not before the typename). 14499 if ((FD->getReturnType()->isAnyPointerType() && 14500 FD->getReturnType()->getPointeeType().isConstQualified()) || 14501 FD->getReturnType().isConstQualified()) { 14502 // But only do this if we can determine where the `const` is. 14503 14504 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14505 getLangOpts())) 14506 14507 return FD->getBeginLoc(); 14508 } 14509 return FD->getTypeSpecStartLoc(); 14510 }; 14511 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14512 << /* function */ 1 14513 << (FD->getStorageClass() == SC_None 14514 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14515 : FixItHint{}); 14516 } 14517 14518 // GNU warning -Wstrict-prototypes 14519 // Warn if K&R function is defined without a previous declaration. 14520 // This warning is issued only if the definition itself does not provide 14521 // a prototype. Only K&R definitions do not provide a prototype. 14522 if (!FD->hasWrittenPrototype()) { 14523 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14524 TypeLoc TL = TI->getTypeLoc(); 14525 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14526 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14527 } 14528 } 14529 14530 // Warn on CPUDispatch with an actual body. 14531 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14532 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14533 if (!CmpndBody->body_empty()) 14534 Diag(CmpndBody->body_front()->getBeginLoc(), 14535 diag::warn_dispatch_body_ignored); 14536 14537 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14538 const CXXMethodDecl *KeyFunction; 14539 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14540 MD->isVirtual() && 14541 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14542 MD == KeyFunction->getCanonicalDecl()) { 14543 // Update the key-function state if necessary for this ABI. 14544 if (FD->isInlined() && 14545 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14546 Context.setNonKeyFunction(MD); 14547 14548 // If the newly-chosen key function is already defined, then we 14549 // need to mark the vtable as used retroactively. 14550 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14551 const FunctionDecl *Definition; 14552 if (KeyFunction && KeyFunction->isDefined(Definition)) 14553 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14554 } else { 14555 // We just defined they key function; mark the vtable as used. 14556 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14557 } 14558 } 14559 } 14560 14561 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14562 "Function parsing confused"); 14563 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14564 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14565 MD->setBody(Body); 14566 if (!MD->isInvalidDecl()) { 14567 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14568 MD->getReturnType(), MD); 14569 14570 if (Body) 14571 computeNRVO(Body, FSI); 14572 } 14573 if (FSI->ObjCShouldCallSuper) { 14574 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14575 << MD->getSelector().getAsString(); 14576 FSI->ObjCShouldCallSuper = false; 14577 } 14578 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14579 const ObjCMethodDecl *InitMethod = nullptr; 14580 bool isDesignated = 14581 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14582 assert(isDesignated && InitMethod); 14583 (void)isDesignated; 14584 14585 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14586 auto IFace = MD->getClassInterface(); 14587 if (!IFace) 14588 return false; 14589 auto SuperD = IFace->getSuperClass(); 14590 if (!SuperD) 14591 return false; 14592 return SuperD->getIdentifier() == 14593 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14594 }; 14595 // Don't issue this warning for unavailable inits or direct subclasses 14596 // of NSObject. 14597 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14598 Diag(MD->getLocation(), 14599 diag::warn_objc_designated_init_missing_super_call); 14600 Diag(InitMethod->getLocation(), 14601 diag::note_objc_designated_init_marked_here); 14602 } 14603 FSI->ObjCWarnForNoDesignatedInitChain = false; 14604 } 14605 if (FSI->ObjCWarnForNoInitDelegation) { 14606 // Don't issue this warning for unavaialable inits. 14607 if (!MD->isUnavailable()) 14608 Diag(MD->getLocation(), 14609 diag::warn_objc_secondary_init_missing_init_call); 14610 FSI->ObjCWarnForNoInitDelegation = false; 14611 } 14612 14613 diagnoseImplicitlyRetainedSelf(*this); 14614 } else { 14615 // Parsing the function declaration failed in some way. Pop the fake scope 14616 // we pushed on. 14617 PopFunctionScopeInfo(ActivePolicy, dcl); 14618 return nullptr; 14619 } 14620 14621 if (Body && FSI->HasPotentialAvailabilityViolations) 14622 DiagnoseUnguardedAvailabilityViolations(dcl); 14623 14624 assert(!FSI->ObjCShouldCallSuper && 14625 "This should only be set for ObjC methods, which should have been " 14626 "handled in the block above."); 14627 14628 // Verify and clean out per-function state. 14629 if (Body && (!FD || !FD->isDefaulted())) { 14630 // C++ constructors that have function-try-blocks can't have return 14631 // statements in the handlers of that block. (C++ [except.handle]p14) 14632 // Verify this. 14633 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14634 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14635 14636 // Verify that gotos and switch cases don't jump into scopes illegally. 14637 if (FSI->NeedsScopeChecking() && 14638 !PP.isCodeCompletionEnabled()) 14639 DiagnoseInvalidJumps(Body); 14640 14641 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14642 if (!Destructor->getParent()->isDependentType()) 14643 CheckDestructor(Destructor); 14644 14645 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14646 Destructor->getParent()); 14647 } 14648 14649 // If any errors have occurred, clear out any temporaries that may have 14650 // been leftover. This ensures that these temporaries won't be picked up for 14651 // deletion in some later function. 14652 if (hasUncompilableErrorOccurred() || 14653 getDiagnostics().getSuppressAllDiagnostics()) { 14654 DiscardCleanupsInEvaluationContext(); 14655 } 14656 if (!hasUncompilableErrorOccurred() && 14657 !isa<FunctionTemplateDecl>(dcl)) { 14658 // Since the body is valid, issue any analysis-based warnings that are 14659 // enabled. 14660 ActivePolicy = &WP; 14661 } 14662 14663 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14664 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14665 FD->setInvalidDecl(); 14666 14667 if (FD && FD->hasAttr<NakedAttr>()) { 14668 for (const Stmt *S : Body->children()) { 14669 // Allow local register variables without initializer as they don't 14670 // require prologue. 14671 bool RegisterVariables = false; 14672 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14673 for (const auto *Decl : DS->decls()) { 14674 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14675 RegisterVariables = 14676 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14677 if (!RegisterVariables) 14678 break; 14679 } 14680 } 14681 } 14682 if (RegisterVariables) 14683 continue; 14684 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14685 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14686 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14687 FD->setInvalidDecl(); 14688 break; 14689 } 14690 } 14691 } 14692 14693 assert(ExprCleanupObjects.size() == 14694 ExprEvalContexts.back().NumCleanupObjects && 14695 "Leftover temporaries in function"); 14696 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14697 assert(MaybeODRUseExprs.empty() && 14698 "Leftover expressions for odr-use checking"); 14699 } 14700 14701 if (!IsInstantiation) 14702 PopDeclContext(); 14703 14704 PopFunctionScopeInfo(ActivePolicy, dcl); 14705 // If any errors have occurred, clear out any temporaries that may have 14706 // been leftover. This ensures that these temporaries won't be picked up for 14707 // deletion in some later function. 14708 if (hasUncompilableErrorOccurred()) { 14709 DiscardCleanupsInEvaluationContext(); 14710 } 14711 14712 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14713 auto ES = getEmissionStatus(FD); 14714 if (ES == Sema::FunctionEmissionStatus::Emitted || 14715 ES == Sema::FunctionEmissionStatus::Unknown) 14716 DeclsToCheckForDeferredDiags.push_back(FD); 14717 } 14718 14719 return dcl; 14720 } 14721 14722 /// When we finish delayed parsing of an attribute, we must attach it to the 14723 /// relevant Decl. 14724 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14725 ParsedAttributes &Attrs) { 14726 // Always attach attributes to the underlying decl. 14727 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14728 D = TD->getTemplatedDecl(); 14729 ProcessDeclAttributeList(S, D, Attrs); 14730 14731 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14732 if (Method->isStatic()) 14733 checkThisInStaticMemberFunctionAttributes(Method); 14734 } 14735 14736 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14737 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14738 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14739 IdentifierInfo &II, Scope *S) { 14740 // Find the scope in which the identifier is injected and the corresponding 14741 // DeclContext. 14742 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14743 // In that case, we inject the declaration into the translation unit scope 14744 // instead. 14745 Scope *BlockScope = S; 14746 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14747 BlockScope = BlockScope->getParent(); 14748 14749 Scope *ContextScope = BlockScope; 14750 while (!ContextScope->getEntity()) 14751 ContextScope = ContextScope->getParent(); 14752 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14753 14754 // Before we produce a declaration for an implicitly defined 14755 // function, see whether there was a locally-scoped declaration of 14756 // this name as a function or variable. If so, use that 14757 // (non-visible) declaration, and complain about it. 14758 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14759 if (ExternCPrev) { 14760 // We still need to inject the function into the enclosing block scope so 14761 // that later (non-call) uses can see it. 14762 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14763 14764 // C89 footnote 38: 14765 // If in fact it is not defined as having type "function returning int", 14766 // the behavior is undefined. 14767 if (!isa<FunctionDecl>(ExternCPrev) || 14768 !Context.typesAreCompatible( 14769 cast<FunctionDecl>(ExternCPrev)->getType(), 14770 Context.getFunctionNoProtoType(Context.IntTy))) { 14771 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14772 << ExternCPrev << !getLangOpts().C99; 14773 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14774 return ExternCPrev; 14775 } 14776 } 14777 14778 // Extension in C99. Legal in C90, but warn about it. 14779 unsigned diag_id; 14780 if (II.getName().startswith("__builtin_")) 14781 diag_id = diag::warn_builtin_unknown; 14782 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14783 else if (getLangOpts().OpenCL) 14784 diag_id = diag::err_opencl_implicit_function_decl; 14785 else if (getLangOpts().C99) 14786 diag_id = diag::ext_implicit_function_decl; 14787 else 14788 diag_id = diag::warn_implicit_function_decl; 14789 Diag(Loc, diag_id) << &II; 14790 14791 // If we found a prior declaration of this function, don't bother building 14792 // another one. We've already pushed that one into scope, so there's nothing 14793 // more to do. 14794 if (ExternCPrev) 14795 return ExternCPrev; 14796 14797 // Because typo correction is expensive, only do it if the implicit 14798 // function declaration is going to be treated as an error. 14799 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14800 TypoCorrection Corrected; 14801 DeclFilterCCC<FunctionDecl> CCC{}; 14802 if (S && (Corrected = 14803 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14804 S, nullptr, CCC, CTK_NonError))) 14805 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14806 /*ErrorRecovery*/false); 14807 } 14808 14809 // Set a Declarator for the implicit definition: int foo(); 14810 const char *Dummy; 14811 AttributeFactory attrFactory; 14812 DeclSpec DS(attrFactory); 14813 unsigned DiagID; 14814 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14815 Context.getPrintingPolicy()); 14816 (void)Error; // Silence warning. 14817 assert(!Error && "Error setting up implicit decl!"); 14818 SourceLocation NoLoc; 14819 Declarator D(DS, DeclaratorContext::Block); 14820 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14821 /*IsAmbiguous=*/false, 14822 /*LParenLoc=*/NoLoc, 14823 /*Params=*/nullptr, 14824 /*NumParams=*/0, 14825 /*EllipsisLoc=*/NoLoc, 14826 /*RParenLoc=*/NoLoc, 14827 /*RefQualifierIsLvalueRef=*/true, 14828 /*RefQualifierLoc=*/NoLoc, 14829 /*MutableLoc=*/NoLoc, EST_None, 14830 /*ESpecRange=*/SourceRange(), 14831 /*Exceptions=*/nullptr, 14832 /*ExceptionRanges=*/nullptr, 14833 /*NumExceptions=*/0, 14834 /*NoexceptExpr=*/nullptr, 14835 /*ExceptionSpecTokens=*/nullptr, 14836 /*DeclsInPrototype=*/None, Loc, 14837 Loc, D), 14838 std::move(DS.getAttributes()), SourceLocation()); 14839 D.SetIdentifier(&II, Loc); 14840 14841 // Insert this function into the enclosing block scope. 14842 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14843 FD->setImplicit(); 14844 14845 AddKnownFunctionAttributes(FD); 14846 14847 return FD; 14848 } 14849 14850 /// If this function is a C++ replaceable global allocation function 14851 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14852 /// adds any function attributes that we know a priori based on the standard. 14853 /// 14854 /// We need to check for duplicate attributes both here and where user-written 14855 /// attributes are applied to declarations. 14856 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14857 FunctionDecl *FD) { 14858 if (FD->isInvalidDecl()) 14859 return; 14860 14861 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14862 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14863 return; 14864 14865 Optional<unsigned> AlignmentParam; 14866 bool IsNothrow = false; 14867 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14868 return; 14869 14870 // C++2a [basic.stc.dynamic.allocation]p4: 14871 // An allocation function that has a non-throwing exception specification 14872 // indicates failure by returning a null pointer value. Any other allocation 14873 // function never returns a null pointer value and indicates failure only by 14874 // throwing an exception [...] 14875 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14876 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14877 14878 // C++2a [basic.stc.dynamic.allocation]p2: 14879 // An allocation function attempts to allocate the requested amount of 14880 // storage. [...] If the request succeeds, the value returned by a 14881 // replaceable allocation function is a [...] pointer value p0 different 14882 // from any previously returned value p1 [...] 14883 // 14884 // However, this particular information is being added in codegen, 14885 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14886 14887 // C++2a [basic.stc.dynamic.allocation]p2: 14888 // An allocation function attempts to allocate the requested amount of 14889 // storage. If it is successful, it returns the address of the start of a 14890 // block of storage whose length in bytes is at least as large as the 14891 // requested size. 14892 if (!FD->hasAttr<AllocSizeAttr>()) { 14893 FD->addAttr(AllocSizeAttr::CreateImplicit( 14894 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14895 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14896 } 14897 14898 // C++2a [basic.stc.dynamic.allocation]p3: 14899 // For an allocation function [...], the pointer returned on a successful 14900 // call shall represent the address of storage that is aligned as follows: 14901 // (3.1) If the allocation function takes an argument of type 14902 // std::align_val_t, the storage will have the alignment 14903 // specified by the value of this argument. 14904 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14905 FD->addAttr(AllocAlignAttr::CreateImplicit( 14906 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14907 } 14908 14909 // FIXME: 14910 // C++2a [basic.stc.dynamic.allocation]p3: 14911 // For an allocation function [...], the pointer returned on a successful 14912 // call shall represent the address of storage that is aligned as follows: 14913 // (3.2) Otherwise, if the allocation function is named operator new[], 14914 // the storage is aligned for any object that does not have 14915 // new-extended alignment ([basic.align]) and is no larger than the 14916 // requested size. 14917 // (3.3) Otherwise, the storage is aligned for any object that does not 14918 // have new-extended alignment and is of the requested size. 14919 } 14920 14921 /// Adds any function attributes that we know a priori based on 14922 /// the declaration of this function. 14923 /// 14924 /// These attributes can apply both to implicitly-declared builtins 14925 /// (like __builtin___printf_chk) or to library-declared functions 14926 /// like NSLog or printf. 14927 /// 14928 /// We need to check for duplicate attributes both here and where user-written 14929 /// attributes are applied to declarations. 14930 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14931 if (FD->isInvalidDecl()) 14932 return; 14933 14934 // If this is a built-in function, map its builtin attributes to 14935 // actual attributes. 14936 if (unsigned BuiltinID = FD->getBuiltinID()) { 14937 // Handle printf-formatting attributes. 14938 unsigned FormatIdx; 14939 bool HasVAListArg; 14940 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14941 if (!FD->hasAttr<FormatAttr>()) { 14942 const char *fmt = "printf"; 14943 unsigned int NumParams = FD->getNumParams(); 14944 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14945 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14946 fmt = "NSString"; 14947 FD->addAttr(FormatAttr::CreateImplicit(Context, 14948 &Context.Idents.get(fmt), 14949 FormatIdx+1, 14950 HasVAListArg ? 0 : FormatIdx+2, 14951 FD->getLocation())); 14952 } 14953 } 14954 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14955 HasVAListArg)) { 14956 if (!FD->hasAttr<FormatAttr>()) 14957 FD->addAttr(FormatAttr::CreateImplicit(Context, 14958 &Context.Idents.get("scanf"), 14959 FormatIdx+1, 14960 HasVAListArg ? 0 : FormatIdx+2, 14961 FD->getLocation())); 14962 } 14963 14964 // Handle automatically recognized callbacks. 14965 SmallVector<int, 4> Encoding; 14966 if (!FD->hasAttr<CallbackAttr>() && 14967 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14968 FD->addAttr(CallbackAttr::CreateImplicit( 14969 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14970 14971 // Mark const if we don't care about errno and that is the only thing 14972 // preventing the function from being const. This allows IRgen to use LLVM 14973 // intrinsics for such functions. 14974 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14975 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14976 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14977 14978 // We make "fma" on some platforms const because we know it does not set 14979 // errno in those environments even though it could set errno based on the 14980 // C standard. 14981 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14982 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14983 !FD->hasAttr<ConstAttr>()) { 14984 switch (BuiltinID) { 14985 case Builtin::BI__builtin_fma: 14986 case Builtin::BI__builtin_fmaf: 14987 case Builtin::BI__builtin_fmal: 14988 case Builtin::BIfma: 14989 case Builtin::BIfmaf: 14990 case Builtin::BIfmal: 14991 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14992 break; 14993 default: 14994 break; 14995 } 14996 } 14997 14998 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14999 !FD->hasAttr<ReturnsTwiceAttr>()) 15000 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15001 FD->getLocation())); 15002 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15003 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15004 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15005 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15006 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15007 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15008 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15009 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15010 // Add the appropriate attribute, depending on the CUDA compilation mode 15011 // and which target the builtin belongs to. For example, during host 15012 // compilation, aux builtins are __device__, while the rest are __host__. 15013 if (getLangOpts().CUDAIsDevice != 15014 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15015 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15016 else 15017 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15018 } 15019 } 15020 15021 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15022 15023 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15024 // throw, add an implicit nothrow attribute to any extern "C" function we come 15025 // across. 15026 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15027 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15028 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15029 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15030 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15031 } 15032 15033 IdentifierInfo *Name = FD->getIdentifier(); 15034 if (!Name) 15035 return; 15036 if ((!getLangOpts().CPlusPlus && 15037 FD->getDeclContext()->isTranslationUnit()) || 15038 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15039 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15040 LinkageSpecDecl::lang_c)) { 15041 // Okay: this could be a libc/libm/Objective-C function we know 15042 // about. 15043 } else 15044 return; 15045 15046 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15047 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15048 // target-specific builtins, perhaps? 15049 if (!FD->hasAttr<FormatAttr>()) 15050 FD->addAttr(FormatAttr::CreateImplicit(Context, 15051 &Context.Idents.get("printf"), 2, 15052 Name->isStr("vasprintf") ? 0 : 3, 15053 FD->getLocation())); 15054 } 15055 15056 if (Name->isStr("__CFStringMakeConstantString")) { 15057 // We already have a __builtin___CFStringMakeConstantString, 15058 // but builds that use -fno-constant-cfstrings don't go through that. 15059 if (!FD->hasAttr<FormatArgAttr>()) 15060 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15061 FD->getLocation())); 15062 } 15063 } 15064 15065 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15066 TypeSourceInfo *TInfo) { 15067 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15068 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15069 15070 if (!TInfo) { 15071 assert(D.isInvalidType() && "no declarator info for valid type"); 15072 TInfo = Context.getTrivialTypeSourceInfo(T); 15073 } 15074 15075 // Scope manipulation handled by caller. 15076 TypedefDecl *NewTD = 15077 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15078 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15079 15080 // Bail out immediately if we have an invalid declaration. 15081 if (D.isInvalidType()) { 15082 NewTD->setInvalidDecl(); 15083 return NewTD; 15084 } 15085 15086 if (D.getDeclSpec().isModulePrivateSpecified()) { 15087 if (CurContext->isFunctionOrMethod()) 15088 Diag(NewTD->getLocation(), diag::err_module_private_local) 15089 << 2 << NewTD 15090 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15091 << FixItHint::CreateRemoval( 15092 D.getDeclSpec().getModulePrivateSpecLoc()); 15093 else 15094 NewTD->setModulePrivate(); 15095 } 15096 15097 // C++ [dcl.typedef]p8: 15098 // If the typedef declaration defines an unnamed class (or 15099 // enum), the first typedef-name declared by the declaration 15100 // to be that class type (or enum type) is used to denote the 15101 // class type (or enum type) for linkage purposes only. 15102 // We need to check whether the type was declared in the declaration. 15103 switch (D.getDeclSpec().getTypeSpecType()) { 15104 case TST_enum: 15105 case TST_struct: 15106 case TST_interface: 15107 case TST_union: 15108 case TST_class: { 15109 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15110 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15111 break; 15112 } 15113 15114 default: 15115 break; 15116 } 15117 15118 return NewTD; 15119 } 15120 15121 /// Check that this is a valid underlying type for an enum declaration. 15122 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15123 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15124 QualType T = TI->getType(); 15125 15126 if (T->isDependentType()) 15127 return false; 15128 15129 // This doesn't use 'isIntegralType' despite the error message mentioning 15130 // integral type because isIntegralType would also allow enum types in C. 15131 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15132 if (BT->isInteger()) 15133 return false; 15134 15135 if (T->isExtIntType()) 15136 return false; 15137 15138 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15139 } 15140 15141 /// Check whether this is a valid redeclaration of a previous enumeration. 15142 /// \return true if the redeclaration was invalid. 15143 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15144 QualType EnumUnderlyingTy, bool IsFixed, 15145 const EnumDecl *Prev) { 15146 if (IsScoped != Prev->isScoped()) { 15147 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15148 << Prev->isScoped(); 15149 Diag(Prev->getLocation(), diag::note_previous_declaration); 15150 return true; 15151 } 15152 15153 if (IsFixed && Prev->isFixed()) { 15154 if (!EnumUnderlyingTy->isDependentType() && 15155 !Prev->getIntegerType()->isDependentType() && 15156 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15157 Prev->getIntegerType())) { 15158 // TODO: Highlight the underlying type of the redeclaration. 15159 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15160 << EnumUnderlyingTy << Prev->getIntegerType(); 15161 Diag(Prev->getLocation(), diag::note_previous_declaration) 15162 << Prev->getIntegerTypeRange(); 15163 return true; 15164 } 15165 } else if (IsFixed != Prev->isFixed()) { 15166 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15167 << Prev->isFixed(); 15168 Diag(Prev->getLocation(), diag::note_previous_declaration); 15169 return true; 15170 } 15171 15172 return false; 15173 } 15174 15175 /// Get diagnostic %select index for tag kind for 15176 /// redeclaration diagnostic message. 15177 /// WARNING: Indexes apply to particular diagnostics only! 15178 /// 15179 /// \returns diagnostic %select index. 15180 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15181 switch (Tag) { 15182 case TTK_Struct: return 0; 15183 case TTK_Interface: return 1; 15184 case TTK_Class: return 2; 15185 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15186 } 15187 } 15188 15189 /// Determine if tag kind is a class-key compatible with 15190 /// class for redeclaration (class, struct, or __interface). 15191 /// 15192 /// \returns true iff the tag kind is compatible. 15193 static bool isClassCompatTagKind(TagTypeKind Tag) 15194 { 15195 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15196 } 15197 15198 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15199 TagTypeKind TTK) { 15200 if (isa<TypedefDecl>(PrevDecl)) 15201 return NTK_Typedef; 15202 else if (isa<TypeAliasDecl>(PrevDecl)) 15203 return NTK_TypeAlias; 15204 else if (isa<ClassTemplateDecl>(PrevDecl)) 15205 return NTK_Template; 15206 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15207 return NTK_TypeAliasTemplate; 15208 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15209 return NTK_TemplateTemplateArgument; 15210 switch (TTK) { 15211 case TTK_Struct: 15212 case TTK_Interface: 15213 case TTK_Class: 15214 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15215 case TTK_Union: 15216 return NTK_NonUnion; 15217 case TTK_Enum: 15218 return NTK_NonEnum; 15219 } 15220 llvm_unreachable("invalid TTK"); 15221 } 15222 15223 /// Determine whether a tag with a given kind is acceptable 15224 /// as a redeclaration of the given tag declaration. 15225 /// 15226 /// \returns true if the new tag kind is acceptable, false otherwise. 15227 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15228 TagTypeKind NewTag, bool isDefinition, 15229 SourceLocation NewTagLoc, 15230 const IdentifierInfo *Name) { 15231 // C++ [dcl.type.elab]p3: 15232 // The class-key or enum keyword present in the 15233 // elaborated-type-specifier shall agree in kind with the 15234 // declaration to which the name in the elaborated-type-specifier 15235 // refers. This rule also applies to the form of 15236 // elaborated-type-specifier that declares a class-name or 15237 // friend class since it can be construed as referring to the 15238 // definition of the class. Thus, in any 15239 // elaborated-type-specifier, the enum keyword shall be used to 15240 // refer to an enumeration (7.2), the union class-key shall be 15241 // used to refer to a union (clause 9), and either the class or 15242 // struct class-key shall be used to refer to a class (clause 9) 15243 // declared using the class or struct class-key. 15244 TagTypeKind OldTag = Previous->getTagKind(); 15245 if (OldTag != NewTag && 15246 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15247 return false; 15248 15249 // Tags are compatible, but we might still want to warn on mismatched tags. 15250 // Non-class tags can't be mismatched at this point. 15251 if (!isClassCompatTagKind(NewTag)) 15252 return true; 15253 15254 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15255 // by our warning analysis. We don't want to warn about mismatches with (eg) 15256 // declarations in system headers that are designed to be specialized, but if 15257 // a user asks us to warn, we should warn if their code contains mismatched 15258 // declarations. 15259 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15260 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15261 Loc); 15262 }; 15263 if (IsIgnoredLoc(NewTagLoc)) 15264 return true; 15265 15266 auto IsIgnored = [&](const TagDecl *Tag) { 15267 return IsIgnoredLoc(Tag->getLocation()); 15268 }; 15269 while (IsIgnored(Previous)) { 15270 Previous = Previous->getPreviousDecl(); 15271 if (!Previous) 15272 return true; 15273 OldTag = Previous->getTagKind(); 15274 } 15275 15276 bool isTemplate = false; 15277 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15278 isTemplate = Record->getDescribedClassTemplate(); 15279 15280 if (inTemplateInstantiation()) { 15281 if (OldTag != NewTag) { 15282 // In a template instantiation, do not offer fix-its for tag mismatches 15283 // since they usually mess up the template instead of fixing the problem. 15284 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15285 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15286 << getRedeclDiagFromTagKind(OldTag); 15287 // FIXME: Note previous location? 15288 } 15289 return true; 15290 } 15291 15292 if (isDefinition) { 15293 // On definitions, check all previous tags and issue a fix-it for each 15294 // one that doesn't match the current tag. 15295 if (Previous->getDefinition()) { 15296 // Don't suggest fix-its for redefinitions. 15297 return true; 15298 } 15299 15300 bool previousMismatch = false; 15301 for (const TagDecl *I : Previous->redecls()) { 15302 if (I->getTagKind() != NewTag) { 15303 // Ignore previous declarations for which the warning was disabled. 15304 if (IsIgnored(I)) 15305 continue; 15306 15307 if (!previousMismatch) { 15308 previousMismatch = true; 15309 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15310 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15311 << getRedeclDiagFromTagKind(I->getTagKind()); 15312 } 15313 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15314 << getRedeclDiagFromTagKind(NewTag) 15315 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15316 TypeWithKeyword::getTagTypeKindName(NewTag)); 15317 } 15318 } 15319 return true; 15320 } 15321 15322 // Identify the prevailing tag kind: this is the kind of the definition (if 15323 // there is a non-ignored definition), or otherwise the kind of the prior 15324 // (non-ignored) declaration. 15325 const TagDecl *PrevDef = Previous->getDefinition(); 15326 if (PrevDef && IsIgnored(PrevDef)) 15327 PrevDef = nullptr; 15328 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15329 if (Redecl->getTagKind() != NewTag) { 15330 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15331 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15332 << getRedeclDiagFromTagKind(OldTag); 15333 Diag(Redecl->getLocation(), diag::note_previous_use); 15334 15335 // If there is a previous definition, suggest a fix-it. 15336 if (PrevDef) { 15337 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15338 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15339 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15340 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15341 } 15342 } 15343 15344 return true; 15345 } 15346 15347 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15348 /// from an outer enclosing namespace or file scope inside a friend declaration. 15349 /// This should provide the commented out code in the following snippet: 15350 /// namespace N { 15351 /// struct X; 15352 /// namespace M { 15353 /// struct Y { friend struct /*N::*/ X; }; 15354 /// } 15355 /// } 15356 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15357 SourceLocation NameLoc) { 15358 // While the decl is in a namespace, do repeated lookup of that name and see 15359 // if we get the same namespace back. If we do not, continue until 15360 // translation unit scope, at which point we have a fully qualified NNS. 15361 SmallVector<IdentifierInfo *, 4> Namespaces; 15362 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15363 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15364 // This tag should be declared in a namespace, which can only be enclosed by 15365 // other namespaces. Bail if there's an anonymous namespace in the chain. 15366 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15367 if (!Namespace || Namespace->isAnonymousNamespace()) 15368 return FixItHint(); 15369 IdentifierInfo *II = Namespace->getIdentifier(); 15370 Namespaces.push_back(II); 15371 NamedDecl *Lookup = SemaRef.LookupSingleName( 15372 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15373 if (Lookup == Namespace) 15374 break; 15375 } 15376 15377 // Once we have all the namespaces, reverse them to go outermost first, and 15378 // build an NNS. 15379 SmallString<64> Insertion; 15380 llvm::raw_svector_ostream OS(Insertion); 15381 if (DC->isTranslationUnit()) 15382 OS << "::"; 15383 std::reverse(Namespaces.begin(), Namespaces.end()); 15384 for (auto *II : Namespaces) 15385 OS << II->getName() << "::"; 15386 return FixItHint::CreateInsertion(NameLoc, Insertion); 15387 } 15388 15389 /// Determine whether a tag originally declared in context \p OldDC can 15390 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15391 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15392 /// using-declaration). 15393 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15394 DeclContext *NewDC) { 15395 OldDC = OldDC->getRedeclContext(); 15396 NewDC = NewDC->getRedeclContext(); 15397 15398 if (OldDC->Equals(NewDC)) 15399 return true; 15400 15401 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15402 // encloses the other). 15403 if (S.getLangOpts().MSVCCompat && 15404 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15405 return true; 15406 15407 return false; 15408 } 15409 15410 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15411 /// former case, Name will be non-null. In the later case, Name will be null. 15412 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15413 /// reference/declaration/definition of a tag. 15414 /// 15415 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15416 /// trailing-type-specifier) other than one in an alias-declaration. 15417 /// 15418 /// \param SkipBody If non-null, will be set to indicate if the caller should 15419 /// skip the definition of this tag and treat it as if it were a declaration. 15420 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15421 SourceLocation KWLoc, CXXScopeSpec &SS, 15422 IdentifierInfo *Name, SourceLocation NameLoc, 15423 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15424 SourceLocation ModulePrivateLoc, 15425 MultiTemplateParamsArg TemplateParameterLists, 15426 bool &OwnedDecl, bool &IsDependent, 15427 SourceLocation ScopedEnumKWLoc, 15428 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15429 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15430 SkipBodyInfo *SkipBody) { 15431 // If this is not a definition, it must have a name. 15432 IdentifierInfo *OrigName = Name; 15433 assert((Name != nullptr || TUK == TUK_Definition) && 15434 "Nameless record must be a definition!"); 15435 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15436 15437 OwnedDecl = false; 15438 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15439 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15440 15441 // FIXME: Check member specializations more carefully. 15442 bool isMemberSpecialization = false; 15443 bool Invalid = false; 15444 15445 // We only need to do this matching if we have template parameters 15446 // or a scope specifier, which also conveniently avoids this work 15447 // for non-C++ cases. 15448 if (TemplateParameterLists.size() > 0 || 15449 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15450 if (TemplateParameterList *TemplateParams = 15451 MatchTemplateParametersToScopeSpecifier( 15452 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15453 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15454 if (Kind == TTK_Enum) { 15455 Diag(KWLoc, diag::err_enum_template); 15456 return nullptr; 15457 } 15458 15459 if (TemplateParams->size() > 0) { 15460 // This is a declaration or definition of a class template (which may 15461 // be a member of another template). 15462 15463 if (Invalid) 15464 return nullptr; 15465 15466 OwnedDecl = false; 15467 DeclResult Result = CheckClassTemplate( 15468 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15469 AS, ModulePrivateLoc, 15470 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15471 TemplateParameterLists.data(), SkipBody); 15472 return Result.get(); 15473 } else { 15474 // The "template<>" header is extraneous. 15475 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15476 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15477 isMemberSpecialization = true; 15478 } 15479 } 15480 15481 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15482 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15483 return nullptr; 15484 } 15485 15486 // Figure out the underlying type if this a enum declaration. We need to do 15487 // this early, because it's needed to detect if this is an incompatible 15488 // redeclaration. 15489 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15490 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15491 15492 if (Kind == TTK_Enum) { 15493 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15494 // No underlying type explicitly specified, or we failed to parse the 15495 // type, default to int. 15496 EnumUnderlying = Context.IntTy.getTypePtr(); 15497 } else if (UnderlyingType.get()) { 15498 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15499 // integral type; any cv-qualification is ignored. 15500 TypeSourceInfo *TI = nullptr; 15501 GetTypeFromParser(UnderlyingType.get(), &TI); 15502 EnumUnderlying = TI; 15503 15504 if (CheckEnumUnderlyingType(TI)) 15505 // Recover by falling back to int. 15506 EnumUnderlying = Context.IntTy.getTypePtr(); 15507 15508 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15509 UPPC_FixedUnderlyingType)) 15510 EnumUnderlying = Context.IntTy.getTypePtr(); 15511 15512 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15513 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15514 // of 'int'. However, if this is an unfixed forward declaration, don't set 15515 // the underlying type unless the user enables -fms-compatibility. This 15516 // makes unfixed forward declared enums incomplete and is more conforming. 15517 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15518 EnumUnderlying = Context.IntTy.getTypePtr(); 15519 } 15520 } 15521 15522 DeclContext *SearchDC = CurContext; 15523 DeclContext *DC = CurContext; 15524 bool isStdBadAlloc = false; 15525 bool isStdAlignValT = false; 15526 15527 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15528 if (TUK == TUK_Friend || TUK == TUK_Reference) 15529 Redecl = NotForRedeclaration; 15530 15531 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15532 /// implemented asks for structural equivalence checking, the returned decl 15533 /// here is passed back to the parser, allowing the tag body to be parsed. 15534 auto createTagFromNewDecl = [&]() -> TagDecl * { 15535 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15536 // If there is an identifier, use the location of the identifier as the 15537 // location of the decl, otherwise use the location of the struct/union 15538 // keyword. 15539 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15540 TagDecl *New = nullptr; 15541 15542 if (Kind == TTK_Enum) { 15543 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15544 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15545 // If this is an undefined enum, bail. 15546 if (TUK != TUK_Definition && !Invalid) 15547 return nullptr; 15548 if (EnumUnderlying) { 15549 EnumDecl *ED = cast<EnumDecl>(New); 15550 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15551 ED->setIntegerTypeSourceInfo(TI); 15552 else 15553 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15554 ED->setPromotionType(ED->getIntegerType()); 15555 } 15556 } else { // struct/union 15557 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15558 nullptr); 15559 } 15560 15561 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15562 // Add alignment attributes if necessary; these attributes are checked 15563 // when the ASTContext lays out the structure. 15564 // 15565 // It is important for implementing the correct semantics that this 15566 // happen here (in ActOnTag). The #pragma pack stack is 15567 // maintained as a result of parser callbacks which can occur at 15568 // many points during the parsing of a struct declaration (because 15569 // the #pragma tokens are effectively skipped over during the 15570 // parsing of the struct). 15571 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15572 AddAlignmentAttributesForRecord(RD); 15573 AddMsStructLayoutForRecord(RD); 15574 } 15575 } 15576 New->setLexicalDeclContext(CurContext); 15577 return New; 15578 }; 15579 15580 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15581 if (Name && SS.isNotEmpty()) { 15582 // We have a nested-name tag ('struct foo::bar'). 15583 15584 // Check for invalid 'foo::'. 15585 if (SS.isInvalid()) { 15586 Name = nullptr; 15587 goto CreateNewDecl; 15588 } 15589 15590 // If this is a friend or a reference to a class in a dependent 15591 // context, don't try to make a decl for it. 15592 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15593 DC = computeDeclContext(SS, false); 15594 if (!DC) { 15595 IsDependent = true; 15596 return nullptr; 15597 } 15598 } else { 15599 DC = computeDeclContext(SS, true); 15600 if (!DC) { 15601 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15602 << SS.getRange(); 15603 return nullptr; 15604 } 15605 } 15606 15607 if (RequireCompleteDeclContext(SS, DC)) 15608 return nullptr; 15609 15610 SearchDC = DC; 15611 // Look-up name inside 'foo::'. 15612 LookupQualifiedName(Previous, DC); 15613 15614 if (Previous.isAmbiguous()) 15615 return nullptr; 15616 15617 if (Previous.empty()) { 15618 // Name lookup did not find anything. However, if the 15619 // nested-name-specifier refers to the current instantiation, 15620 // and that current instantiation has any dependent base 15621 // classes, we might find something at instantiation time: treat 15622 // this as a dependent elaborated-type-specifier. 15623 // But this only makes any sense for reference-like lookups. 15624 if (Previous.wasNotFoundInCurrentInstantiation() && 15625 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15626 IsDependent = true; 15627 return nullptr; 15628 } 15629 15630 // A tag 'foo::bar' must already exist. 15631 Diag(NameLoc, diag::err_not_tag_in_scope) 15632 << Kind << Name << DC << SS.getRange(); 15633 Name = nullptr; 15634 Invalid = true; 15635 goto CreateNewDecl; 15636 } 15637 } else if (Name) { 15638 // C++14 [class.mem]p14: 15639 // If T is the name of a class, then each of the following shall have a 15640 // name different from T: 15641 // -- every member of class T that is itself a type 15642 if (TUK != TUK_Reference && TUK != TUK_Friend && 15643 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15644 return nullptr; 15645 15646 // If this is a named struct, check to see if there was a previous forward 15647 // declaration or definition. 15648 // FIXME: We're looking into outer scopes here, even when we 15649 // shouldn't be. Doing so can result in ambiguities that we 15650 // shouldn't be diagnosing. 15651 LookupName(Previous, S); 15652 15653 // When declaring or defining a tag, ignore ambiguities introduced 15654 // by types using'ed into this scope. 15655 if (Previous.isAmbiguous() && 15656 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15657 LookupResult::Filter F = Previous.makeFilter(); 15658 while (F.hasNext()) { 15659 NamedDecl *ND = F.next(); 15660 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15661 SearchDC->getRedeclContext())) 15662 F.erase(); 15663 } 15664 F.done(); 15665 } 15666 15667 // C++11 [namespace.memdef]p3: 15668 // If the name in a friend declaration is neither qualified nor 15669 // a template-id and the declaration is a function or an 15670 // elaborated-type-specifier, the lookup to determine whether 15671 // the entity has been previously declared shall not consider 15672 // any scopes outside the innermost enclosing namespace. 15673 // 15674 // MSVC doesn't implement the above rule for types, so a friend tag 15675 // declaration may be a redeclaration of a type declared in an enclosing 15676 // scope. They do implement this rule for friend functions. 15677 // 15678 // Does it matter that this should be by scope instead of by 15679 // semantic context? 15680 if (!Previous.empty() && TUK == TUK_Friend) { 15681 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15682 LookupResult::Filter F = Previous.makeFilter(); 15683 bool FriendSawTagOutsideEnclosingNamespace = false; 15684 while (F.hasNext()) { 15685 NamedDecl *ND = F.next(); 15686 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15687 if (DC->isFileContext() && 15688 !EnclosingNS->Encloses(ND->getDeclContext())) { 15689 if (getLangOpts().MSVCCompat) 15690 FriendSawTagOutsideEnclosingNamespace = true; 15691 else 15692 F.erase(); 15693 } 15694 } 15695 F.done(); 15696 15697 // Diagnose this MSVC extension in the easy case where lookup would have 15698 // unambiguously found something outside the enclosing namespace. 15699 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15700 NamedDecl *ND = Previous.getFoundDecl(); 15701 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15702 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15703 } 15704 } 15705 15706 // Note: there used to be some attempt at recovery here. 15707 if (Previous.isAmbiguous()) 15708 return nullptr; 15709 15710 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15711 // FIXME: This makes sure that we ignore the contexts associated 15712 // with C structs, unions, and enums when looking for a matching 15713 // tag declaration or definition. See the similar lookup tweak 15714 // in Sema::LookupName; is there a better way to deal with this? 15715 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15716 SearchDC = SearchDC->getParent(); 15717 } 15718 } 15719 15720 if (Previous.isSingleResult() && 15721 Previous.getFoundDecl()->isTemplateParameter()) { 15722 // Maybe we will complain about the shadowed template parameter. 15723 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15724 // Just pretend that we didn't see the previous declaration. 15725 Previous.clear(); 15726 } 15727 15728 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15729 DC->Equals(getStdNamespace())) { 15730 if (Name->isStr("bad_alloc")) { 15731 // This is a declaration of or a reference to "std::bad_alloc". 15732 isStdBadAlloc = true; 15733 15734 // If std::bad_alloc has been implicitly declared (but made invisible to 15735 // name lookup), fill in this implicit declaration as the previous 15736 // declaration, so that the declarations get chained appropriately. 15737 if (Previous.empty() && StdBadAlloc) 15738 Previous.addDecl(getStdBadAlloc()); 15739 } else if (Name->isStr("align_val_t")) { 15740 isStdAlignValT = true; 15741 if (Previous.empty() && StdAlignValT) 15742 Previous.addDecl(getStdAlignValT()); 15743 } 15744 } 15745 15746 // If we didn't find a previous declaration, and this is a reference 15747 // (or friend reference), move to the correct scope. In C++, we 15748 // also need to do a redeclaration lookup there, just in case 15749 // there's a shadow friend decl. 15750 if (Name && Previous.empty() && 15751 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15752 if (Invalid) goto CreateNewDecl; 15753 assert(SS.isEmpty()); 15754 15755 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15756 // C++ [basic.scope.pdecl]p5: 15757 // -- for an elaborated-type-specifier of the form 15758 // 15759 // class-key identifier 15760 // 15761 // if the elaborated-type-specifier is used in the 15762 // decl-specifier-seq or parameter-declaration-clause of a 15763 // function defined in namespace scope, the identifier is 15764 // declared as a class-name in the namespace that contains 15765 // the declaration; otherwise, except as a friend 15766 // declaration, the identifier is declared in the smallest 15767 // non-class, non-function-prototype scope that contains the 15768 // declaration. 15769 // 15770 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15771 // C structs and unions. 15772 // 15773 // It is an error in C++ to declare (rather than define) an enum 15774 // type, including via an elaborated type specifier. We'll 15775 // diagnose that later; for now, declare the enum in the same 15776 // scope as we would have picked for any other tag type. 15777 // 15778 // GNU C also supports this behavior as part of its incomplete 15779 // enum types extension, while GNU C++ does not. 15780 // 15781 // Find the context where we'll be declaring the tag. 15782 // FIXME: We would like to maintain the current DeclContext as the 15783 // lexical context, 15784 SearchDC = getTagInjectionContext(SearchDC); 15785 15786 // Find the scope where we'll be declaring the tag. 15787 S = getTagInjectionScope(S, getLangOpts()); 15788 } else { 15789 assert(TUK == TUK_Friend); 15790 // C++ [namespace.memdef]p3: 15791 // If a friend declaration in a non-local class first declares a 15792 // class or function, the friend class or function is a member of 15793 // the innermost enclosing namespace. 15794 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15795 } 15796 15797 // In C++, we need to do a redeclaration lookup to properly 15798 // diagnose some problems. 15799 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15800 // hidden declaration so that we don't get ambiguity errors when using a 15801 // type declared by an elaborated-type-specifier. In C that is not correct 15802 // and we should instead merge compatible types found by lookup. 15803 if (getLangOpts().CPlusPlus) { 15804 // FIXME: This can perform qualified lookups into function contexts, 15805 // which are meaningless. 15806 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15807 LookupQualifiedName(Previous, SearchDC); 15808 } else { 15809 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15810 LookupName(Previous, S); 15811 } 15812 } 15813 15814 // If we have a known previous declaration to use, then use it. 15815 if (Previous.empty() && SkipBody && SkipBody->Previous) 15816 Previous.addDecl(SkipBody->Previous); 15817 15818 if (!Previous.empty()) { 15819 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15820 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15821 15822 // It's okay to have a tag decl in the same scope as a typedef 15823 // which hides a tag decl in the same scope. Finding this 15824 // insanity with a redeclaration lookup can only actually happen 15825 // in C++. 15826 // 15827 // This is also okay for elaborated-type-specifiers, which is 15828 // technically forbidden by the current standard but which is 15829 // okay according to the likely resolution of an open issue; 15830 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15831 if (getLangOpts().CPlusPlus) { 15832 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15833 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15834 TagDecl *Tag = TT->getDecl(); 15835 if (Tag->getDeclName() == Name && 15836 Tag->getDeclContext()->getRedeclContext() 15837 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15838 PrevDecl = Tag; 15839 Previous.clear(); 15840 Previous.addDecl(Tag); 15841 Previous.resolveKind(); 15842 } 15843 } 15844 } 15845 } 15846 15847 // If this is a redeclaration of a using shadow declaration, it must 15848 // declare a tag in the same context. In MSVC mode, we allow a 15849 // redefinition if either context is within the other. 15850 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15851 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15852 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15853 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15854 !(OldTag && isAcceptableTagRedeclContext( 15855 *this, OldTag->getDeclContext(), SearchDC))) { 15856 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15857 Diag(Shadow->getTargetDecl()->getLocation(), 15858 diag::note_using_decl_target); 15859 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15860 << 0; 15861 // Recover by ignoring the old declaration. 15862 Previous.clear(); 15863 goto CreateNewDecl; 15864 } 15865 } 15866 15867 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15868 // If this is a use of a previous tag, or if the tag is already declared 15869 // in the same scope (so that the definition/declaration completes or 15870 // rementions the tag), reuse the decl. 15871 if (TUK == TUK_Reference || TUK == TUK_Friend || 15872 isDeclInScope(DirectPrevDecl, SearchDC, S, 15873 SS.isNotEmpty() || isMemberSpecialization)) { 15874 // Make sure that this wasn't declared as an enum and now used as a 15875 // struct or something similar. 15876 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15877 TUK == TUK_Definition, KWLoc, 15878 Name)) { 15879 bool SafeToContinue 15880 = (PrevTagDecl->getTagKind() != TTK_Enum && 15881 Kind != TTK_Enum); 15882 if (SafeToContinue) 15883 Diag(KWLoc, diag::err_use_with_wrong_tag) 15884 << Name 15885 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15886 PrevTagDecl->getKindName()); 15887 else 15888 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15889 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15890 15891 if (SafeToContinue) 15892 Kind = PrevTagDecl->getTagKind(); 15893 else { 15894 // Recover by making this an anonymous redefinition. 15895 Name = nullptr; 15896 Previous.clear(); 15897 Invalid = true; 15898 } 15899 } 15900 15901 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15902 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15903 if (TUK == TUK_Reference || TUK == TUK_Friend) 15904 return PrevTagDecl; 15905 15906 QualType EnumUnderlyingTy; 15907 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15908 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15909 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15910 EnumUnderlyingTy = QualType(T, 0); 15911 15912 // All conflicts with previous declarations are recovered by 15913 // returning the previous declaration, unless this is a definition, 15914 // in which case we want the caller to bail out. 15915 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15916 ScopedEnum, EnumUnderlyingTy, 15917 IsFixed, PrevEnum)) 15918 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15919 } 15920 15921 // C++11 [class.mem]p1: 15922 // A member shall not be declared twice in the member-specification, 15923 // except that a nested class or member class template can be declared 15924 // and then later defined. 15925 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15926 S->isDeclScope(PrevDecl)) { 15927 Diag(NameLoc, diag::ext_member_redeclared); 15928 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15929 } 15930 15931 if (!Invalid) { 15932 // If this is a use, just return the declaration we found, unless 15933 // we have attributes. 15934 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15935 if (!Attrs.empty()) { 15936 // FIXME: Diagnose these attributes. For now, we create a new 15937 // declaration to hold them. 15938 } else if (TUK == TUK_Reference && 15939 (PrevTagDecl->getFriendObjectKind() == 15940 Decl::FOK_Undeclared || 15941 PrevDecl->getOwningModule() != getCurrentModule()) && 15942 SS.isEmpty()) { 15943 // This declaration is a reference to an existing entity, but 15944 // has different visibility from that entity: it either makes 15945 // a friend visible or it makes a type visible in a new module. 15946 // In either case, create a new declaration. We only do this if 15947 // the declaration would have meant the same thing if no prior 15948 // declaration were found, that is, if it was found in the same 15949 // scope where we would have injected a declaration. 15950 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15951 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15952 return PrevTagDecl; 15953 // This is in the injected scope, create a new declaration in 15954 // that scope. 15955 S = getTagInjectionScope(S, getLangOpts()); 15956 } else { 15957 return PrevTagDecl; 15958 } 15959 } 15960 15961 // Diagnose attempts to redefine a tag. 15962 if (TUK == TUK_Definition) { 15963 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15964 // If we're defining a specialization and the previous definition 15965 // is from an implicit instantiation, don't emit an error 15966 // here; we'll catch this in the general case below. 15967 bool IsExplicitSpecializationAfterInstantiation = false; 15968 if (isMemberSpecialization) { 15969 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15970 IsExplicitSpecializationAfterInstantiation = 15971 RD->getTemplateSpecializationKind() != 15972 TSK_ExplicitSpecialization; 15973 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15974 IsExplicitSpecializationAfterInstantiation = 15975 ED->getTemplateSpecializationKind() != 15976 TSK_ExplicitSpecialization; 15977 } 15978 15979 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15980 // not keep more that one definition around (merge them). However, 15981 // ensure the decl passes the structural compatibility check in 15982 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15983 NamedDecl *Hidden = nullptr; 15984 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15985 // There is a definition of this tag, but it is not visible. We 15986 // explicitly make use of C++'s one definition rule here, and 15987 // assume that this definition is identical to the hidden one 15988 // we already have. Make the existing definition visible and 15989 // use it in place of this one. 15990 if (!getLangOpts().CPlusPlus) { 15991 // Postpone making the old definition visible until after we 15992 // complete parsing the new one and do the structural 15993 // comparison. 15994 SkipBody->CheckSameAsPrevious = true; 15995 SkipBody->New = createTagFromNewDecl(); 15996 SkipBody->Previous = Def; 15997 return Def; 15998 } else { 15999 SkipBody->ShouldSkip = true; 16000 SkipBody->Previous = Def; 16001 makeMergedDefinitionVisible(Hidden); 16002 // Carry on and handle it like a normal definition. We'll 16003 // skip starting the definitiion later. 16004 } 16005 } else if (!IsExplicitSpecializationAfterInstantiation) { 16006 // A redeclaration in function prototype scope in C isn't 16007 // visible elsewhere, so merely issue a warning. 16008 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16009 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16010 else 16011 Diag(NameLoc, diag::err_redefinition) << Name; 16012 notePreviousDefinition(Def, 16013 NameLoc.isValid() ? NameLoc : KWLoc); 16014 // If this is a redefinition, recover by making this 16015 // struct be anonymous, which will make any later 16016 // references get the previous definition. 16017 Name = nullptr; 16018 Previous.clear(); 16019 Invalid = true; 16020 } 16021 } else { 16022 // If the type is currently being defined, complain 16023 // about a nested redefinition. 16024 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16025 if (TD->isBeingDefined()) { 16026 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16027 Diag(PrevTagDecl->getLocation(), 16028 diag::note_previous_definition); 16029 Name = nullptr; 16030 Previous.clear(); 16031 Invalid = true; 16032 } 16033 } 16034 16035 // Okay, this is definition of a previously declared or referenced 16036 // tag. We're going to create a new Decl for it. 16037 } 16038 16039 // Okay, we're going to make a redeclaration. If this is some kind 16040 // of reference, make sure we build the redeclaration in the same DC 16041 // as the original, and ignore the current access specifier. 16042 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16043 SearchDC = PrevTagDecl->getDeclContext(); 16044 AS = AS_none; 16045 } 16046 } 16047 // If we get here we have (another) forward declaration or we 16048 // have a definition. Just create a new decl. 16049 16050 } else { 16051 // If we get here, this is a definition of a new tag type in a nested 16052 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16053 // new decl/type. We set PrevDecl to NULL so that the entities 16054 // have distinct types. 16055 Previous.clear(); 16056 } 16057 // If we get here, we're going to create a new Decl. If PrevDecl 16058 // is non-NULL, it's a definition of the tag declared by 16059 // PrevDecl. If it's NULL, we have a new definition. 16060 16061 // Otherwise, PrevDecl is not a tag, but was found with tag 16062 // lookup. This is only actually possible in C++, where a few 16063 // things like templates still live in the tag namespace. 16064 } else { 16065 // Use a better diagnostic if an elaborated-type-specifier 16066 // found the wrong kind of type on the first 16067 // (non-redeclaration) lookup. 16068 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16069 !Previous.isForRedeclaration()) { 16070 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16071 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16072 << Kind; 16073 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16074 Invalid = true; 16075 16076 // Otherwise, only diagnose if the declaration is in scope. 16077 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16078 SS.isNotEmpty() || isMemberSpecialization)) { 16079 // do nothing 16080 16081 // Diagnose implicit declarations introduced by elaborated types. 16082 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16083 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16084 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16085 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16086 Invalid = true; 16087 16088 // Otherwise it's a declaration. Call out a particularly common 16089 // case here. 16090 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16091 unsigned Kind = 0; 16092 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16093 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16094 << Name << Kind << TND->getUnderlyingType(); 16095 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16096 Invalid = true; 16097 16098 // Otherwise, diagnose. 16099 } else { 16100 // The tag name clashes with something else in the target scope, 16101 // issue an error and recover by making this tag be anonymous. 16102 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16103 notePreviousDefinition(PrevDecl, NameLoc); 16104 Name = nullptr; 16105 Invalid = true; 16106 } 16107 16108 // The existing declaration isn't relevant to us; we're in a 16109 // new scope, so clear out the previous declaration. 16110 Previous.clear(); 16111 } 16112 } 16113 16114 CreateNewDecl: 16115 16116 TagDecl *PrevDecl = nullptr; 16117 if (Previous.isSingleResult()) 16118 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16119 16120 // If there is an identifier, use the location of the identifier as the 16121 // location of the decl, otherwise use the location of the struct/union 16122 // keyword. 16123 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16124 16125 // Otherwise, create a new declaration. If there is a previous 16126 // declaration of the same entity, the two will be linked via 16127 // PrevDecl. 16128 TagDecl *New; 16129 16130 if (Kind == TTK_Enum) { 16131 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16132 // enum X { A, B, C } D; D should chain to X. 16133 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16134 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16135 ScopedEnumUsesClassTag, IsFixed); 16136 16137 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16138 StdAlignValT = cast<EnumDecl>(New); 16139 16140 // If this is an undefined enum, warn. 16141 if (TUK != TUK_Definition && !Invalid) { 16142 TagDecl *Def; 16143 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16144 // C++0x: 7.2p2: opaque-enum-declaration. 16145 // Conflicts are diagnosed above. Do nothing. 16146 } 16147 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16148 Diag(Loc, diag::ext_forward_ref_enum_def) 16149 << New; 16150 Diag(Def->getLocation(), diag::note_previous_definition); 16151 } else { 16152 unsigned DiagID = diag::ext_forward_ref_enum; 16153 if (getLangOpts().MSVCCompat) 16154 DiagID = diag::ext_ms_forward_ref_enum; 16155 else if (getLangOpts().CPlusPlus) 16156 DiagID = diag::err_forward_ref_enum; 16157 Diag(Loc, DiagID); 16158 } 16159 } 16160 16161 if (EnumUnderlying) { 16162 EnumDecl *ED = cast<EnumDecl>(New); 16163 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16164 ED->setIntegerTypeSourceInfo(TI); 16165 else 16166 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16167 ED->setPromotionType(ED->getIntegerType()); 16168 assert(ED->isComplete() && "enum with type should be complete"); 16169 } 16170 } else { 16171 // struct/union/class 16172 16173 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16174 // struct X { int A; } D; D should chain to X. 16175 if (getLangOpts().CPlusPlus) { 16176 // FIXME: Look for a way to use RecordDecl for simple structs. 16177 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16178 cast_or_null<CXXRecordDecl>(PrevDecl)); 16179 16180 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16181 StdBadAlloc = cast<CXXRecordDecl>(New); 16182 } else 16183 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16184 cast_or_null<RecordDecl>(PrevDecl)); 16185 } 16186 16187 // C++11 [dcl.type]p3: 16188 // A type-specifier-seq shall not define a class or enumeration [...]. 16189 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16190 TUK == TUK_Definition) { 16191 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16192 << Context.getTagDeclType(New); 16193 Invalid = true; 16194 } 16195 16196 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16197 DC->getDeclKind() == Decl::Enum) { 16198 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16199 << Context.getTagDeclType(New); 16200 Invalid = true; 16201 } 16202 16203 // Maybe add qualifier info. 16204 if (SS.isNotEmpty()) { 16205 if (SS.isSet()) { 16206 // If this is either a declaration or a definition, check the 16207 // nested-name-specifier against the current context. 16208 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16209 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16210 isMemberSpecialization)) 16211 Invalid = true; 16212 16213 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16214 if (TemplateParameterLists.size() > 0) { 16215 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16216 } 16217 } 16218 else 16219 Invalid = true; 16220 } 16221 16222 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16223 // Add alignment attributes if necessary; these attributes are checked when 16224 // the ASTContext lays out the structure. 16225 // 16226 // It is important for implementing the correct semantics that this 16227 // happen here (in ActOnTag). The #pragma pack stack is 16228 // maintained as a result of parser callbacks which can occur at 16229 // many points during the parsing of a struct declaration (because 16230 // the #pragma tokens are effectively skipped over during the 16231 // parsing of the struct). 16232 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16233 AddAlignmentAttributesForRecord(RD); 16234 AddMsStructLayoutForRecord(RD); 16235 } 16236 } 16237 16238 if (ModulePrivateLoc.isValid()) { 16239 if (isMemberSpecialization) 16240 Diag(New->getLocation(), diag::err_module_private_specialization) 16241 << 2 16242 << FixItHint::CreateRemoval(ModulePrivateLoc); 16243 // __module_private__ does not apply to local classes. However, we only 16244 // diagnose this as an error when the declaration specifiers are 16245 // freestanding. Here, we just ignore the __module_private__. 16246 else if (!SearchDC->isFunctionOrMethod()) 16247 New->setModulePrivate(); 16248 } 16249 16250 // If this is a specialization of a member class (of a class template), 16251 // check the specialization. 16252 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16253 Invalid = true; 16254 16255 // If we're declaring or defining a tag in function prototype scope in C, 16256 // note that this type can only be used within the function and add it to 16257 // the list of decls to inject into the function definition scope. 16258 if ((Name || Kind == TTK_Enum) && 16259 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16260 if (getLangOpts().CPlusPlus) { 16261 // C++ [dcl.fct]p6: 16262 // Types shall not be defined in return or parameter types. 16263 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16264 Diag(Loc, diag::err_type_defined_in_param_type) 16265 << Name; 16266 Invalid = true; 16267 } 16268 } else if (!PrevDecl) { 16269 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16270 } 16271 } 16272 16273 if (Invalid) 16274 New->setInvalidDecl(); 16275 16276 // Set the lexical context. If the tag has a C++ scope specifier, the 16277 // lexical context will be different from the semantic context. 16278 New->setLexicalDeclContext(CurContext); 16279 16280 // Mark this as a friend decl if applicable. 16281 // In Microsoft mode, a friend declaration also acts as a forward 16282 // declaration so we always pass true to setObjectOfFriendDecl to make 16283 // the tag name visible. 16284 if (TUK == TUK_Friend) 16285 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16286 16287 // Set the access specifier. 16288 if (!Invalid && SearchDC->isRecord()) 16289 SetMemberAccessSpecifier(New, PrevDecl, AS); 16290 16291 if (PrevDecl) 16292 CheckRedeclarationModuleOwnership(New, PrevDecl); 16293 16294 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16295 New->startDefinition(); 16296 16297 ProcessDeclAttributeList(S, New, Attrs); 16298 AddPragmaAttributes(S, New); 16299 16300 // If this has an identifier, add it to the scope stack. 16301 if (TUK == TUK_Friend) { 16302 // We might be replacing an existing declaration in the lookup tables; 16303 // if so, borrow its access specifier. 16304 if (PrevDecl) 16305 New->setAccess(PrevDecl->getAccess()); 16306 16307 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16308 DC->makeDeclVisibleInContext(New); 16309 if (Name) // can be null along some error paths 16310 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16311 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16312 } else if (Name) { 16313 S = getNonFieldDeclScope(S); 16314 PushOnScopeChains(New, S, true); 16315 } else { 16316 CurContext->addDecl(New); 16317 } 16318 16319 // If this is the C FILE type, notify the AST context. 16320 if (IdentifierInfo *II = New->getIdentifier()) 16321 if (!New->isInvalidDecl() && 16322 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16323 II->isStr("FILE")) 16324 Context.setFILEDecl(New); 16325 16326 if (PrevDecl) 16327 mergeDeclAttributes(New, PrevDecl); 16328 16329 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16330 inferGslOwnerPointerAttribute(CXXRD); 16331 16332 // If there's a #pragma GCC visibility in scope, set the visibility of this 16333 // record. 16334 AddPushedVisibilityAttribute(New); 16335 16336 if (isMemberSpecialization && !New->isInvalidDecl()) 16337 CompleteMemberSpecialization(New, Previous); 16338 16339 OwnedDecl = true; 16340 // In C++, don't return an invalid declaration. We can't recover well from 16341 // the cases where we make the type anonymous. 16342 if (Invalid && getLangOpts().CPlusPlus) { 16343 if (New->isBeingDefined()) 16344 if (auto RD = dyn_cast<RecordDecl>(New)) 16345 RD->completeDefinition(); 16346 return nullptr; 16347 } else if (SkipBody && SkipBody->ShouldSkip) { 16348 return SkipBody->Previous; 16349 } else { 16350 return New; 16351 } 16352 } 16353 16354 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16355 AdjustDeclIfTemplate(TagD); 16356 TagDecl *Tag = cast<TagDecl>(TagD); 16357 16358 // Enter the tag context. 16359 PushDeclContext(S, Tag); 16360 16361 ActOnDocumentableDecl(TagD); 16362 16363 // If there's a #pragma GCC visibility in scope, set the visibility of this 16364 // record. 16365 AddPushedVisibilityAttribute(Tag); 16366 } 16367 16368 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16369 SkipBodyInfo &SkipBody) { 16370 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16371 return false; 16372 16373 // Make the previous decl visible. 16374 makeMergedDefinitionVisible(SkipBody.Previous); 16375 return true; 16376 } 16377 16378 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16379 assert(isa<ObjCContainerDecl>(IDecl) && 16380 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16381 DeclContext *OCD = cast<DeclContext>(IDecl); 16382 assert(OCD->getLexicalParent() == CurContext && 16383 "The next DeclContext should be lexically contained in the current one."); 16384 CurContext = OCD; 16385 return IDecl; 16386 } 16387 16388 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16389 SourceLocation FinalLoc, 16390 bool IsFinalSpelledSealed, 16391 SourceLocation LBraceLoc) { 16392 AdjustDeclIfTemplate(TagD); 16393 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16394 16395 FieldCollector->StartClass(); 16396 16397 if (!Record->getIdentifier()) 16398 return; 16399 16400 if (FinalLoc.isValid()) 16401 Record->addAttr(FinalAttr::Create( 16402 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16403 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16404 16405 // C++ [class]p2: 16406 // [...] The class-name is also inserted into the scope of the 16407 // class itself; this is known as the injected-class-name. For 16408 // purposes of access checking, the injected-class-name is treated 16409 // as if it were a public member name. 16410 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16411 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16412 Record->getLocation(), Record->getIdentifier(), 16413 /*PrevDecl=*/nullptr, 16414 /*DelayTypeCreation=*/true); 16415 Context.getTypeDeclType(InjectedClassName, Record); 16416 InjectedClassName->setImplicit(); 16417 InjectedClassName->setAccess(AS_public); 16418 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16419 InjectedClassName->setDescribedClassTemplate(Template); 16420 PushOnScopeChains(InjectedClassName, S); 16421 assert(InjectedClassName->isInjectedClassName() && 16422 "Broken injected-class-name"); 16423 } 16424 16425 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16426 SourceRange BraceRange) { 16427 AdjustDeclIfTemplate(TagD); 16428 TagDecl *Tag = cast<TagDecl>(TagD); 16429 Tag->setBraceRange(BraceRange); 16430 16431 // Make sure we "complete" the definition even it is invalid. 16432 if (Tag->isBeingDefined()) { 16433 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16434 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16435 RD->completeDefinition(); 16436 } 16437 16438 if (isa<CXXRecordDecl>(Tag)) { 16439 FieldCollector->FinishClass(); 16440 } 16441 16442 // Exit this scope of this tag's definition. 16443 PopDeclContext(); 16444 16445 if (getCurLexicalContext()->isObjCContainer() && 16446 Tag->getDeclContext()->isFileContext()) 16447 Tag->setTopLevelDeclInObjCContainer(); 16448 16449 // Notify the consumer that we've defined a tag. 16450 if (!Tag->isInvalidDecl()) 16451 Consumer.HandleTagDeclDefinition(Tag); 16452 } 16453 16454 void Sema::ActOnObjCContainerFinishDefinition() { 16455 // Exit this scope of this interface definition. 16456 PopDeclContext(); 16457 } 16458 16459 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16460 assert(DC == CurContext && "Mismatch of container contexts"); 16461 OriginalLexicalContext = DC; 16462 ActOnObjCContainerFinishDefinition(); 16463 } 16464 16465 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16466 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16467 OriginalLexicalContext = nullptr; 16468 } 16469 16470 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16471 AdjustDeclIfTemplate(TagD); 16472 TagDecl *Tag = cast<TagDecl>(TagD); 16473 Tag->setInvalidDecl(); 16474 16475 // Make sure we "complete" the definition even it is invalid. 16476 if (Tag->isBeingDefined()) { 16477 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16478 RD->completeDefinition(); 16479 } 16480 16481 // We're undoing ActOnTagStartDefinition here, not 16482 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16483 // the FieldCollector. 16484 16485 PopDeclContext(); 16486 } 16487 16488 // Note that FieldName may be null for anonymous bitfields. 16489 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16490 IdentifierInfo *FieldName, 16491 QualType FieldTy, bool IsMsStruct, 16492 Expr *BitWidth, bool *ZeroWidth) { 16493 assert(BitWidth); 16494 if (BitWidth->containsErrors()) 16495 return ExprError(); 16496 16497 // Default to true; that shouldn't confuse checks for emptiness 16498 if (ZeroWidth) 16499 *ZeroWidth = true; 16500 16501 // C99 6.7.2.1p4 - verify the field type. 16502 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16503 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16504 // Handle incomplete and sizeless types with a specific error. 16505 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16506 diag::err_field_incomplete_or_sizeless)) 16507 return ExprError(); 16508 if (FieldName) 16509 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16510 << FieldName << FieldTy << BitWidth->getSourceRange(); 16511 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16512 << FieldTy << BitWidth->getSourceRange(); 16513 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16514 UPPC_BitFieldWidth)) 16515 return ExprError(); 16516 16517 // If the bit-width is type- or value-dependent, don't try to check 16518 // it now. 16519 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16520 return BitWidth; 16521 16522 llvm::APSInt Value; 16523 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16524 if (ICE.isInvalid()) 16525 return ICE; 16526 BitWidth = ICE.get(); 16527 16528 if (Value != 0 && ZeroWidth) 16529 *ZeroWidth = false; 16530 16531 // Zero-width bitfield is ok for anonymous field. 16532 if (Value == 0 && FieldName) 16533 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16534 16535 if (Value.isSigned() && Value.isNegative()) { 16536 if (FieldName) 16537 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16538 << FieldName << Value.toString(10); 16539 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16540 << Value.toString(10); 16541 } 16542 16543 // The size of the bit-field must not exceed our maximum permitted object 16544 // size. 16545 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16546 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16547 << !FieldName << FieldName << Value.toString(10); 16548 } 16549 16550 if (!FieldTy->isDependentType()) { 16551 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16552 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16553 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16554 16555 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16556 // ABI. 16557 bool CStdConstraintViolation = 16558 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16559 bool MSBitfieldViolation = 16560 Value.ugt(TypeStorageSize) && 16561 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16562 if (CStdConstraintViolation || MSBitfieldViolation) { 16563 unsigned DiagWidth = 16564 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16565 if (FieldName) 16566 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16567 << FieldName << Value.toString(10) 16568 << !CStdConstraintViolation << DiagWidth; 16569 16570 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16571 << Value.toString(10) << !CStdConstraintViolation 16572 << DiagWidth; 16573 } 16574 16575 // Warn on types where the user might conceivably expect to get all 16576 // specified bits as value bits: that's all integral types other than 16577 // 'bool'. 16578 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16579 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16580 << FieldName << Value.toString(10) 16581 << (unsigned)TypeWidth; 16582 } 16583 } 16584 16585 return BitWidth; 16586 } 16587 16588 /// ActOnField - Each field of a C struct/union is passed into this in order 16589 /// to create a FieldDecl object for it. 16590 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16591 Declarator &D, Expr *BitfieldWidth) { 16592 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16593 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16594 /*InitStyle=*/ICIS_NoInit, AS_public); 16595 return Res; 16596 } 16597 16598 /// HandleField - Analyze a field of a C struct or a C++ data member. 16599 /// 16600 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16601 SourceLocation DeclStart, 16602 Declarator &D, Expr *BitWidth, 16603 InClassInitStyle InitStyle, 16604 AccessSpecifier AS) { 16605 if (D.isDecompositionDeclarator()) { 16606 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16607 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16608 << Decomp.getSourceRange(); 16609 return nullptr; 16610 } 16611 16612 IdentifierInfo *II = D.getIdentifier(); 16613 SourceLocation Loc = DeclStart; 16614 if (II) Loc = D.getIdentifierLoc(); 16615 16616 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16617 QualType T = TInfo->getType(); 16618 if (getLangOpts().CPlusPlus) { 16619 CheckExtraCXXDefaultArguments(D); 16620 16621 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16622 UPPC_DataMemberType)) { 16623 D.setInvalidType(); 16624 T = Context.IntTy; 16625 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16626 } 16627 } 16628 16629 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16630 16631 if (D.getDeclSpec().isInlineSpecified()) 16632 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16633 << getLangOpts().CPlusPlus17; 16634 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16635 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16636 diag::err_invalid_thread) 16637 << DeclSpec::getSpecifierName(TSCS); 16638 16639 // Check to see if this name was declared as a member previously 16640 NamedDecl *PrevDecl = nullptr; 16641 LookupResult Previous(*this, II, Loc, LookupMemberName, 16642 ForVisibleRedeclaration); 16643 LookupName(Previous, S); 16644 switch (Previous.getResultKind()) { 16645 case LookupResult::Found: 16646 case LookupResult::FoundUnresolvedValue: 16647 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16648 break; 16649 16650 case LookupResult::FoundOverloaded: 16651 PrevDecl = Previous.getRepresentativeDecl(); 16652 break; 16653 16654 case LookupResult::NotFound: 16655 case LookupResult::NotFoundInCurrentInstantiation: 16656 case LookupResult::Ambiguous: 16657 break; 16658 } 16659 Previous.suppressDiagnostics(); 16660 16661 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16662 // Maybe we will complain about the shadowed template parameter. 16663 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16664 // Just pretend that we didn't see the previous declaration. 16665 PrevDecl = nullptr; 16666 } 16667 16668 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16669 PrevDecl = nullptr; 16670 16671 bool Mutable 16672 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16673 SourceLocation TSSL = D.getBeginLoc(); 16674 FieldDecl *NewFD 16675 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16676 TSSL, AS, PrevDecl, &D); 16677 16678 if (NewFD->isInvalidDecl()) 16679 Record->setInvalidDecl(); 16680 16681 if (D.getDeclSpec().isModulePrivateSpecified()) 16682 NewFD->setModulePrivate(); 16683 16684 if (NewFD->isInvalidDecl() && PrevDecl) { 16685 // Don't introduce NewFD into scope; there's already something 16686 // with the same name in the same scope. 16687 } else if (II) { 16688 PushOnScopeChains(NewFD, S); 16689 } else 16690 Record->addDecl(NewFD); 16691 16692 return NewFD; 16693 } 16694 16695 /// Build a new FieldDecl and check its well-formedness. 16696 /// 16697 /// This routine builds a new FieldDecl given the fields name, type, 16698 /// record, etc. \p PrevDecl should refer to any previous declaration 16699 /// with the same name and in the same scope as the field to be 16700 /// created. 16701 /// 16702 /// \returns a new FieldDecl. 16703 /// 16704 /// \todo The Declarator argument is a hack. It will be removed once 16705 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16706 TypeSourceInfo *TInfo, 16707 RecordDecl *Record, SourceLocation Loc, 16708 bool Mutable, Expr *BitWidth, 16709 InClassInitStyle InitStyle, 16710 SourceLocation TSSL, 16711 AccessSpecifier AS, NamedDecl *PrevDecl, 16712 Declarator *D) { 16713 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16714 bool InvalidDecl = false; 16715 if (D) InvalidDecl = D->isInvalidType(); 16716 16717 // If we receive a broken type, recover by assuming 'int' and 16718 // marking this declaration as invalid. 16719 if (T.isNull() || T->containsErrors()) { 16720 InvalidDecl = true; 16721 T = Context.IntTy; 16722 } 16723 16724 QualType EltTy = Context.getBaseElementType(T); 16725 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16726 if (RequireCompleteSizedType(Loc, EltTy, 16727 diag::err_field_incomplete_or_sizeless)) { 16728 // Fields of incomplete type force their record to be invalid. 16729 Record->setInvalidDecl(); 16730 InvalidDecl = true; 16731 } else { 16732 NamedDecl *Def; 16733 EltTy->isIncompleteType(&Def); 16734 if (Def && Def->isInvalidDecl()) { 16735 Record->setInvalidDecl(); 16736 InvalidDecl = true; 16737 } 16738 } 16739 } 16740 16741 // TR 18037 does not allow fields to be declared with address space 16742 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16743 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16744 Diag(Loc, diag::err_field_with_address_space); 16745 Record->setInvalidDecl(); 16746 InvalidDecl = true; 16747 } 16748 16749 if (LangOpts.OpenCL) { 16750 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16751 // used as structure or union field: image, sampler, event or block types. 16752 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16753 T->isBlockPointerType()) { 16754 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16755 Record->setInvalidDecl(); 16756 InvalidDecl = true; 16757 } 16758 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16759 if (BitWidth) { 16760 Diag(Loc, diag::err_opencl_bitfields); 16761 InvalidDecl = true; 16762 } 16763 } 16764 16765 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16766 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16767 T.hasQualifiers()) { 16768 InvalidDecl = true; 16769 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16770 } 16771 16772 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16773 // than a variably modified type. 16774 if (!InvalidDecl && T->isVariablyModifiedType()) { 16775 if (!tryToFixVariablyModifiedVarType( 16776 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16777 InvalidDecl = true; 16778 } 16779 16780 // Fields can not have abstract class types 16781 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16782 diag::err_abstract_type_in_decl, 16783 AbstractFieldType)) 16784 InvalidDecl = true; 16785 16786 bool ZeroWidth = false; 16787 if (InvalidDecl) 16788 BitWidth = nullptr; 16789 // If this is declared as a bit-field, check the bit-field. 16790 if (BitWidth) { 16791 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16792 &ZeroWidth).get(); 16793 if (!BitWidth) { 16794 InvalidDecl = true; 16795 BitWidth = nullptr; 16796 ZeroWidth = false; 16797 } 16798 } 16799 16800 // Check that 'mutable' is consistent with the type of the declaration. 16801 if (!InvalidDecl && Mutable) { 16802 unsigned DiagID = 0; 16803 if (T->isReferenceType()) 16804 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16805 : diag::err_mutable_reference; 16806 else if (T.isConstQualified()) 16807 DiagID = diag::err_mutable_const; 16808 16809 if (DiagID) { 16810 SourceLocation ErrLoc = Loc; 16811 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16812 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16813 Diag(ErrLoc, DiagID); 16814 if (DiagID != diag::ext_mutable_reference) { 16815 Mutable = false; 16816 InvalidDecl = true; 16817 } 16818 } 16819 } 16820 16821 // C++11 [class.union]p8 (DR1460): 16822 // At most one variant member of a union may have a 16823 // brace-or-equal-initializer. 16824 if (InitStyle != ICIS_NoInit) 16825 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16826 16827 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16828 BitWidth, Mutable, InitStyle); 16829 if (InvalidDecl) 16830 NewFD->setInvalidDecl(); 16831 16832 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16833 Diag(Loc, diag::err_duplicate_member) << II; 16834 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16835 NewFD->setInvalidDecl(); 16836 } 16837 16838 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16839 if (Record->isUnion()) { 16840 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16841 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16842 if (RDecl->getDefinition()) { 16843 // C++ [class.union]p1: An object of a class with a non-trivial 16844 // constructor, a non-trivial copy constructor, a non-trivial 16845 // destructor, or a non-trivial copy assignment operator 16846 // cannot be a member of a union, nor can an array of such 16847 // objects. 16848 if (CheckNontrivialField(NewFD)) 16849 NewFD->setInvalidDecl(); 16850 } 16851 } 16852 16853 // C++ [class.union]p1: If a union contains a member of reference type, 16854 // the program is ill-formed, except when compiling with MSVC extensions 16855 // enabled. 16856 if (EltTy->isReferenceType()) { 16857 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16858 diag::ext_union_member_of_reference_type : 16859 diag::err_union_member_of_reference_type) 16860 << NewFD->getDeclName() << EltTy; 16861 if (!getLangOpts().MicrosoftExt) 16862 NewFD->setInvalidDecl(); 16863 } 16864 } 16865 } 16866 16867 // FIXME: We need to pass in the attributes given an AST 16868 // representation, not a parser representation. 16869 if (D) { 16870 // FIXME: The current scope is almost... but not entirely... correct here. 16871 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16872 16873 if (NewFD->hasAttrs()) 16874 CheckAlignasUnderalignment(NewFD); 16875 } 16876 16877 // In auto-retain/release, infer strong retension for fields of 16878 // retainable type. 16879 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16880 NewFD->setInvalidDecl(); 16881 16882 if (T.isObjCGCWeak()) 16883 Diag(Loc, diag::warn_attribute_weak_on_field); 16884 16885 // PPC MMA non-pointer types are not allowed as field types. 16886 if (Context.getTargetInfo().getTriple().isPPC64() && 16887 CheckPPCMMAType(T, NewFD->getLocation())) 16888 NewFD->setInvalidDecl(); 16889 16890 NewFD->setAccess(AS); 16891 return NewFD; 16892 } 16893 16894 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16895 assert(FD); 16896 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16897 16898 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16899 return false; 16900 16901 QualType EltTy = Context.getBaseElementType(FD->getType()); 16902 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16903 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16904 if (RDecl->getDefinition()) { 16905 // We check for copy constructors before constructors 16906 // because otherwise we'll never get complaints about 16907 // copy constructors. 16908 16909 CXXSpecialMember member = CXXInvalid; 16910 // We're required to check for any non-trivial constructors. Since the 16911 // implicit default constructor is suppressed if there are any 16912 // user-declared constructors, we just need to check that there is a 16913 // trivial default constructor and a trivial copy constructor. (We don't 16914 // worry about move constructors here, since this is a C++98 check.) 16915 if (RDecl->hasNonTrivialCopyConstructor()) 16916 member = CXXCopyConstructor; 16917 else if (!RDecl->hasTrivialDefaultConstructor()) 16918 member = CXXDefaultConstructor; 16919 else if (RDecl->hasNonTrivialCopyAssignment()) 16920 member = CXXCopyAssignment; 16921 else if (RDecl->hasNonTrivialDestructor()) 16922 member = CXXDestructor; 16923 16924 if (member != CXXInvalid) { 16925 if (!getLangOpts().CPlusPlus11 && 16926 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16927 // Objective-C++ ARC: it is an error to have a non-trivial field of 16928 // a union. However, system headers in Objective-C programs 16929 // occasionally have Objective-C lifetime objects within unions, 16930 // and rather than cause the program to fail, we make those 16931 // members unavailable. 16932 SourceLocation Loc = FD->getLocation(); 16933 if (getSourceManager().isInSystemHeader(Loc)) { 16934 if (!FD->hasAttr<UnavailableAttr>()) 16935 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16936 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16937 return false; 16938 } 16939 } 16940 16941 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16942 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16943 diag::err_illegal_union_or_anon_struct_member) 16944 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16945 DiagnoseNontrivial(RDecl, member); 16946 return !getLangOpts().CPlusPlus11; 16947 } 16948 } 16949 } 16950 16951 return false; 16952 } 16953 16954 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16955 /// AST enum value. 16956 static ObjCIvarDecl::AccessControl 16957 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16958 switch (ivarVisibility) { 16959 default: llvm_unreachable("Unknown visitibility kind"); 16960 case tok::objc_private: return ObjCIvarDecl::Private; 16961 case tok::objc_public: return ObjCIvarDecl::Public; 16962 case tok::objc_protected: return ObjCIvarDecl::Protected; 16963 case tok::objc_package: return ObjCIvarDecl::Package; 16964 } 16965 } 16966 16967 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16968 /// in order to create an IvarDecl object for it. 16969 Decl *Sema::ActOnIvar(Scope *S, 16970 SourceLocation DeclStart, 16971 Declarator &D, Expr *BitfieldWidth, 16972 tok::ObjCKeywordKind Visibility) { 16973 16974 IdentifierInfo *II = D.getIdentifier(); 16975 Expr *BitWidth = (Expr*)BitfieldWidth; 16976 SourceLocation Loc = DeclStart; 16977 if (II) Loc = D.getIdentifierLoc(); 16978 16979 // FIXME: Unnamed fields can be handled in various different ways, for 16980 // example, unnamed unions inject all members into the struct namespace! 16981 16982 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16983 QualType T = TInfo->getType(); 16984 16985 if (BitWidth) { 16986 // 6.7.2.1p3, 6.7.2.1p4 16987 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16988 if (!BitWidth) 16989 D.setInvalidType(); 16990 } else { 16991 // Not a bitfield. 16992 16993 // validate II. 16994 16995 } 16996 if (T->isReferenceType()) { 16997 Diag(Loc, diag::err_ivar_reference_type); 16998 D.setInvalidType(); 16999 } 17000 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17001 // than a variably modified type. 17002 else if (T->isVariablyModifiedType()) { 17003 if (!tryToFixVariablyModifiedVarType( 17004 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17005 D.setInvalidType(); 17006 } 17007 17008 // Get the visibility (access control) for this ivar. 17009 ObjCIvarDecl::AccessControl ac = 17010 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17011 : ObjCIvarDecl::None; 17012 // Must set ivar's DeclContext to its enclosing interface. 17013 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17014 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17015 return nullptr; 17016 ObjCContainerDecl *EnclosingContext; 17017 if (ObjCImplementationDecl *IMPDecl = 17018 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17019 if (LangOpts.ObjCRuntime.isFragile()) { 17020 // Case of ivar declared in an implementation. Context is that of its class. 17021 EnclosingContext = IMPDecl->getClassInterface(); 17022 assert(EnclosingContext && "Implementation has no class interface!"); 17023 } 17024 else 17025 EnclosingContext = EnclosingDecl; 17026 } else { 17027 if (ObjCCategoryDecl *CDecl = 17028 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17029 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17030 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17031 return nullptr; 17032 } 17033 } 17034 EnclosingContext = EnclosingDecl; 17035 } 17036 17037 // Construct the decl. 17038 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17039 DeclStart, Loc, II, T, 17040 TInfo, ac, (Expr *)BitfieldWidth); 17041 17042 if (II) { 17043 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17044 ForVisibleRedeclaration); 17045 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17046 && !isa<TagDecl>(PrevDecl)) { 17047 Diag(Loc, diag::err_duplicate_member) << II; 17048 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17049 NewID->setInvalidDecl(); 17050 } 17051 } 17052 17053 // Process attributes attached to the ivar. 17054 ProcessDeclAttributes(S, NewID, D); 17055 17056 if (D.isInvalidType()) 17057 NewID->setInvalidDecl(); 17058 17059 // In ARC, infer 'retaining' for ivars of retainable type. 17060 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17061 NewID->setInvalidDecl(); 17062 17063 if (D.getDeclSpec().isModulePrivateSpecified()) 17064 NewID->setModulePrivate(); 17065 17066 if (II) { 17067 // FIXME: When interfaces are DeclContexts, we'll need to add 17068 // these to the interface. 17069 S->AddDecl(NewID); 17070 IdResolver.AddDecl(NewID); 17071 } 17072 17073 if (LangOpts.ObjCRuntime.isNonFragile() && 17074 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17075 Diag(Loc, diag::warn_ivars_in_interface); 17076 17077 return NewID; 17078 } 17079 17080 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17081 /// class and class extensions. For every class \@interface and class 17082 /// extension \@interface, if the last ivar is a bitfield of any type, 17083 /// then add an implicit `char :0` ivar to the end of that interface. 17084 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17085 SmallVectorImpl<Decl *> &AllIvarDecls) { 17086 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17087 return; 17088 17089 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17090 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17091 17092 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17093 return; 17094 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17095 if (!ID) { 17096 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17097 if (!CD->IsClassExtension()) 17098 return; 17099 } 17100 // No need to add this to end of @implementation. 17101 else 17102 return; 17103 } 17104 // All conditions are met. Add a new bitfield to the tail end of ivars. 17105 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17106 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17107 17108 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17109 DeclLoc, DeclLoc, nullptr, 17110 Context.CharTy, 17111 Context.getTrivialTypeSourceInfo(Context.CharTy, 17112 DeclLoc), 17113 ObjCIvarDecl::Private, BW, 17114 true); 17115 AllIvarDecls.push_back(Ivar); 17116 } 17117 17118 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17119 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17120 SourceLocation RBrac, 17121 const ParsedAttributesView &Attrs) { 17122 assert(EnclosingDecl && "missing record or interface decl"); 17123 17124 // If this is an Objective-C @implementation or category and we have 17125 // new fields here we should reset the layout of the interface since 17126 // it will now change. 17127 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17128 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17129 switch (DC->getKind()) { 17130 default: break; 17131 case Decl::ObjCCategory: 17132 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17133 break; 17134 case Decl::ObjCImplementation: 17135 Context. 17136 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17137 break; 17138 } 17139 } 17140 17141 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17142 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17143 17144 // Start counting up the number of named members; make sure to include 17145 // members of anonymous structs and unions in the total. 17146 unsigned NumNamedMembers = 0; 17147 if (Record) { 17148 for (const auto *I : Record->decls()) { 17149 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17150 if (IFD->getDeclName()) 17151 ++NumNamedMembers; 17152 } 17153 } 17154 17155 // Verify that all the fields are okay. 17156 SmallVector<FieldDecl*, 32> RecFields; 17157 17158 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17159 i != end; ++i) { 17160 FieldDecl *FD = cast<FieldDecl>(*i); 17161 17162 // Get the type for the field. 17163 const Type *FDTy = FD->getType().getTypePtr(); 17164 17165 if (!FD->isAnonymousStructOrUnion()) { 17166 // Remember all fields written by the user. 17167 RecFields.push_back(FD); 17168 } 17169 17170 // If the field is already invalid for some reason, don't emit more 17171 // diagnostics about it. 17172 if (FD->isInvalidDecl()) { 17173 EnclosingDecl->setInvalidDecl(); 17174 continue; 17175 } 17176 17177 // C99 6.7.2.1p2: 17178 // A structure or union shall not contain a member with 17179 // incomplete or function type (hence, a structure shall not 17180 // contain an instance of itself, but may contain a pointer to 17181 // an instance of itself), except that the last member of a 17182 // structure with more than one named member may have incomplete 17183 // array type; such a structure (and any union containing, 17184 // possibly recursively, a member that is such a structure) 17185 // shall not be a member of a structure or an element of an 17186 // array. 17187 bool IsLastField = (i + 1 == Fields.end()); 17188 if (FDTy->isFunctionType()) { 17189 // Field declared as a function. 17190 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17191 << FD->getDeclName(); 17192 FD->setInvalidDecl(); 17193 EnclosingDecl->setInvalidDecl(); 17194 continue; 17195 } else if (FDTy->isIncompleteArrayType() && 17196 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17197 if (Record) { 17198 // Flexible array member. 17199 // Microsoft and g++ is more permissive regarding flexible array. 17200 // It will accept flexible array in union and also 17201 // as the sole element of a struct/class. 17202 unsigned DiagID = 0; 17203 if (!Record->isUnion() && !IsLastField) { 17204 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17205 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17206 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17207 FD->setInvalidDecl(); 17208 EnclosingDecl->setInvalidDecl(); 17209 continue; 17210 } else if (Record->isUnion()) 17211 DiagID = getLangOpts().MicrosoftExt 17212 ? diag::ext_flexible_array_union_ms 17213 : getLangOpts().CPlusPlus 17214 ? diag::ext_flexible_array_union_gnu 17215 : diag::err_flexible_array_union; 17216 else if (NumNamedMembers < 1) 17217 DiagID = getLangOpts().MicrosoftExt 17218 ? diag::ext_flexible_array_empty_aggregate_ms 17219 : getLangOpts().CPlusPlus 17220 ? diag::ext_flexible_array_empty_aggregate_gnu 17221 : diag::err_flexible_array_empty_aggregate; 17222 17223 if (DiagID) 17224 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17225 << Record->getTagKind(); 17226 // While the layout of types that contain virtual bases is not specified 17227 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17228 // virtual bases after the derived members. This would make a flexible 17229 // array member declared at the end of an object not adjacent to the end 17230 // of the type. 17231 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17232 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17233 << FD->getDeclName() << Record->getTagKind(); 17234 if (!getLangOpts().C99) 17235 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17236 << FD->getDeclName() << Record->getTagKind(); 17237 17238 // If the element type has a non-trivial destructor, we would not 17239 // implicitly destroy the elements, so disallow it for now. 17240 // 17241 // FIXME: GCC allows this. We should probably either implicitly delete 17242 // the destructor of the containing class, or just allow this. 17243 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17244 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17245 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17246 << FD->getDeclName() << FD->getType(); 17247 FD->setInvalidDecl(); 17248 EnclosingDecl->setInvalidDecl(); 17249 continue; 17250 } 17251 // Okay, we have a legal flexible array member at the end of the struct. 17252 Record->setHasFlexibleArrayMember(true); 17253 } else { 17254 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17255 // unless they are followed by another ivar. That check is done 17256 // elsewhere, after synthesized ivars are known. 17257 } 17258 } else if (!FDTy->isDependentType() && 17259 RequireCompleteSizedType( 17260 FD->getLocation(), FD->getType(), 17261 diag::err_field_incomplete_or_sizeless)) { 17262 // Incomplete type 17263 FD->setInvalidDecl(); 17264 EnclosingDecl->setInvalidDecl(); 17265 continue; 17266 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17267 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17268 // A type which contains a flexible array member is considered to be a 17269 // flexible array member. 17270 Record->setHasFlexibleArrayMember(true); 17271 if (!Record->isUnion()) { 17272 // If this is a struct/class and this is not the last element, reject 17273 // it. Note that GCC supports variable sized arrays in the middle of 17274 // structures. 17275 if (!IsLastField) 17276 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17277 << FD->getDeclName() << FD->getType(); 17278 else { 17279 // We support flexible arrays at the end of structs in 17280 // other structs as an extension. 17281 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17282 << FD->getDeclName(); 17283 } 17284 } 17285 } 17286 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17287 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17288 diag::err_abstract_type_in_decl, 17289 AbstractIvarType)) { 17290 // Ivars can not have abstract class types 17291 FD->setInvalidDecl(); 17292 } 17293 if (Record && FDTTy->getDecl()->hasObjectMember()) 17294 Record->setHasObjectMember(true); 17295 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17296 Record->setHasVolatileMember(true); 17297 } else if (FDTy->isObjCObjectType()) { 17298 /// A field cannot be an Objective-c object 17299 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17300 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17301 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17302 FD->setType(T); 17303 } else if (Record && Record->isUnion() && 17304 FD->getType().hasNonTrivialObjCLifetime() && 17305 getSourceManager().isInSystemHeader(FD->getLocation()) && 17306 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17307 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17308 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17309 // For backward compatibility, fields of C unions declared in system 17310 // headers that have non-trivial ObjC ownership qualifications are marked 17311 // as unavailable unless the qualifier is explicit and __strong. This can 17312 // break ABI compatibility between programs compiled with ARC and MRR, but 17313 // is a better option than rejecting programs using those unions under 17314 // ARC. 17315 FD->addAttr(UnavailableAttr::CreateImplicit( 17316 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17317 FD->getLocation())); 17318 } else if (getLangOpts().ObjC && 17319 getLangOpts().getGC() != LangOptions::NonGC && Record && 17320 !Record->hasObjectMember()) { 17321 if (FD->getType()->isObjCObjectPointerType() || 17322 FD->getType().isObjCGCStrong()) 17323 Record->setHasObjectMember(true); 17324 else if (Context.getAsArrayType(FD->getType())) { 17325 QualType BaseType = Context.getBaseElementType(FD->getType()); 17326 if (BaseType->isRecordType() && 17327 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17328 Record->setHasObjectMember(true); 17329 else if (BaseType->isObjCObjectPointerType() || 17330 BaseType.isObjCGCStrong()) 17331 Record->setHasObjectMember(true); 17332 } 17333 } 17334 17335 if (Record && !getLangOpts().CPlusPlus && 17336 !shouldIgnoreForRecordTriviality(FD)) { 17337 QualType FT = FD->getType(); 17338 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17339 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17340 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17341 Record->isUnion()) 17342 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17343 } 17344 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17345 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17346 Record->setNonTrivialToPrimitiveCopy(true); 17347 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17348 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17349 } 17350 if (FT.isDestructedType()) { 17351 Record->setNonTrivialToPrimitiveDestroy(true); 17352 Record->setParamDestroyedInCallee(true); 17353 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17354 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17355 } 17356 17357 if (const auto *RT = FT->getAs<RecordType>()) { 17358 if (RT->getDecl()->getArgPassingRestrictions() == 17359 RecordDecl::APK_CanNeverPassInRegs) 17360 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17361 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17362 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17363 } 17364 17365 if (Record && FD->getType().isVolatileQualified()) 17366 Record->setHasVolatileMember(true); 17367 // Keep track of the number of named members. 17368 if (FD->getIdentifier()) 17369 ++NumNamedMembers; 17370 } 17371 17372 // Okay, we successfully defined 'Record'. 17373 if (Record) { 17374 bool Completed = false; 17375 if (CXXRecord) { 17376 if (!CXXRecord->isInvalidDecl()) { 17377 // Set access bits correctly on the directly-declared conversions. 17378 for (CXXRecordDecl::conversion_iterator 17379 I = CXXRecord->conversion_begin(), 17380 E = CXXRecord->conversion_end(); I != E; ++I) 17381 I.setAccess((*I)->getAccess()); 17382 } 17383 17384 // Add any implicitly-declared members to this class. 17385 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17386 17387 if (!CXXRecord->isDependentType()) { 17388 if (!CXXRecord->isInvalidDecl()) { 17389 // If we have virtual base classes, we may end up finding multiple 17390 // final overriders for a given virtual function. Check for this 17391 // problem now. 17392 if (CXXRecord->getNumVBases()) { 17393 CXXFinalOverriderMap FinalOverriders; 17394 CXXRecord->getFinalOverriders(FinalOverriders); 17395 17396 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17397 MEnd = FinalOverriders.end(); 17398 M != MEnd; ++M) { 17399 for (OverridingMethods::iterator SO = M->second.begin(), 17400 SOEnd = M->second.end(); 17401 SO != SOEnd; ++SO) { 17402 assert(SO->second.size() > 0 && 17403 "Virtual function without overriding functions?"); 17404 if (SO->second.size() == 1) 17405 continue; 17406 17407 // C++ [class.virtual]p2: 17408 // In a derived class, if a virtual member function of a base 17409 // class subobject has more than one final overrider the 17410 // program is ill-formed. 17411 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17412 << (const NamedDecl *)M->first << Record; 17413 Diag(M->first->getLocation(), 17414 diag::note_overridden_virtual_function); 17415 for (OverridingMethods::overriding_iterator 17416 OM = SO->second.begin(), 17417 OMEnd = SO->second.end(); 17418 OM != OMEnd; ++OM) 17419 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17420 << (const NamedDecl *)M->first << OM->Method->getParent(); 17421 17422 Record->setInvalidDecl(); 17423 } 17424 } 17425 CXXRecord->completeDefinition(&FinalOverriders); 17426 Completed = true; 17427 } 17428 } 17429 } 17430 } 17431 17432 if (!Completed) 17433 Record->completeDefinition(); 17434 17435 // Handle attributes before checking the layout. 17436 ProcessDeclAttributeList(S, Record, Attrs); 17437 17438 // We may have deferred checking for a deleted destructor. Check now. 17439 if (CXXRecord) { 17440 auto *Dtor = CXXRecord->getDestructor(); 17441 if (Dtor && Dtor->isImplicit() && 17442 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17443 CXXRecord->setImplicitDestructorIsDeleted(); 17444 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17445 } 17446 } 17447 17448 if (Record->hasAttrs()) { 17449 CheckAlignasUnderalignment(Record); 17450 17451 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17452 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17453 IA->getRange(), IA->getBestCase(), 17454 IA->getInheritanceModel()); 17455 } 17456 17457 // Check if the structure/union declaration is a type that can have zero 17458 // size in C. For C this is a language extension, for C++ it may cause 17459 // compatibility problems. 17460 bool CheckForZeroSize; 17461 if (!getLangOpts().CPlusPlus) { 17462 CheckForZeroSize = true; 17463 } else { 17464 // For C++ filter out types that cannot be referenced in C code. 17465 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17466 CheckForZeroSize = 17467 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17468 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17469 CXXRecord->isCLike(); 17470 } 17471 if (CheckForZeroSize) { 17472 bool ZeroSize = true; 17473 bool IsEmpty = true; 17474 unsigned NonBitFields = 0; 17475 for (RecordDecl::field_iterator I = Record->field_begin(), 17476 E = Record->field_end(); 17477 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17478 IsEmpty = false; 17479 if (I->isUnnamedBitfield()) { 17480 if (!I->isZeroLengthBitField(Context)) 17481 ZeroSize = false; 17482 } else { 17483 ++NonBitFields; 17484 QualType FieldType = I->getType(); 17485 if (FieldType->isIncompleteType() || 17486 !Context.getTypeSizeInChars(FieldType).isZero()) 17487 ZeroSize = false; 17488 } 17489 } 17490 17491 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17492 // allowed in C++, but warn if its declaration is inside 17493 // extern "C" block. 17494 if (ZeroSize) { 17495 Diag(RecLoc, getLangOpts().CPlusPlus ? 17496 diag::warn_zero_size_struct_union_in_extern_c : 17497 diag::warn_zero_size_struct_union_compat) 17498 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17499 } 17500 17501 // Structs without named members are extension in C (C99 6.7.2.1p7), 17502 // but are accepted by GCC. 17503 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17504 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17505 diag::ext_no_named_members_in_struct_union) 17506 << Record->isUnion(); 17507 } 17508 } 17509 } else { 17510 ObjCIvarDecl **ClsFields = 17511 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17512 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17513 ID->setEndOfDefinitionLoc(RBrac); 17514 // Add ivar's to class's DeclContext. 17515 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17516 ClsFields[i]->setLexicalDeclContext(ID); 17517 ID->addDecl(ClsFields[i]); 17518 } 17519 // Must enforce the rule that ivars in the base classes may not be 17520 // duplicates. 17521 if (ID->getSuperClass()) 17522 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17523 } else if (ObjCImplementationDecl *IMPDecl = 17524 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17525 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17526 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17527 // Ivar declared in @implementation never belongs to the implementation. 17528 // Only it is in implementation's lexical context. 17529 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17530 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17531 IMPDecl->setIvarLBraceLoc(LBrac); 17532 IMPDecl->setIvarRBraceLoc(RBrac); 17533 } else if (ObjCCategoryDecl *CDecl = 17534 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17535 // case of ivars in class extension; all other cases have been 17536 // reported as errors elsewhere. 17537 // FIXME. Class extension does not have a LocEnd field. 17538 // CDecl->setLocEnd(RBrac); 17539 // Add ivar's to class extension's DeclContext. 17540 // Diagnose redeclaration of private ivars. 17541 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17542 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17543 if (IDecl) { 17544 if (const ObjCIvarDecl *ClsIvar = 17545 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17546 Diag(ClsFields[i]->getLocation(), 17547 diag::err_duplicate_ivar_declaration); 17548 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17549 continue; 17550 } 17551 for (const auto *Ext : IDecl->known_extensions()) { 17552 if (const ObjCIvarDecl *ClsExtIvar 17553 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17554 Diag(ClsFields[i]->getLocation(), 17555 diag::err_duplicate_ivar_declaration); 17556 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17557 continue; 17558 } 17559 } 17560 } 17561 ClsFields[i]->setLexicalDeclContext(CDecl); 17562 CDecl->addDecl(ClsFields[i]); 17563 } 17564 CDecl->setIvarLBraceLoc(LBrac); 17565 CDecl->setIvarRBraceLoc(RBrac); 17566 } 17567 } 17568 } 17569 17570 /// Determine whether the given integral value is representable within 17571 /// the given type T. 17572 static bool isRepresentableIntegerValue(ASTContext &Context, 17573 llvm::APSInt &Value, 17574 QualType T) { 17575 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17576 "Integral type required!"); 17577 unsigned BitWidth = Context.getIntWidth(T); 17578 17579 if (Value.isUnsigned() || Value.isNonNegative()) { 17580 if (T->isSignedIntegerOrEnumerationType()) 17581 --BitWidth; 17582 return Value.getActiveBits() <= BitWidth; 17583 } 17584 return Value.getMinSignedBits() <= BitWidth; 17585 } 17586 17587 // Given an integral type, return the next larger integral type 17588 // (or a NULL type of no such type exists). 17589 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17590 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17591 // enum checking below. 17592 assert((T->isIntegralType(Context) || 17593 T->isEnumeralType()) && "Integral type required!"); 17594 const unsigned NumTypes = 4; 17595 QualType SignedIntegralTypes[NumTypes] = { 17596 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17597 }; 17598 QualType UnsignedIntegralTypes[NumTypes] = { 17599 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17600 Context.UnsignedLongLongTy 17601 }; 17602 17603 unsigned BitWidth = Context.getTypeSize(T); 17604 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17605 : UnsignedIntegralTypes; 17606 for (unsigned I = 0; I != NumTypes; ++I) 17607 if (Context.getTypeSize(Types[I]) > BitWidth) 17608 return Types[I]; 17609 17610 return QualType(); 17611 } 17612 17613 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17614 EnumConstantDecl *LastEnumConst, 17615 SourceLocation IdLoc, 17616 IdentifierInfo *Id, 17617 Expr *Val) { 17618 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17619 llvm::APSInt EnumVal(IntWidth); 17620 QualType EltTy; 17621 17622 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17623 Val = nullptr; 17624 17625 if (Val) 17626 Val = DefaultLvalueConversion(Val).get(); 17627 17628 if (Val) { 17629 if (Enum->isDependentType() || Val->isTypeDependent()) 17630 EltTy = Context.DependentTy; 17631 else { 17632 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17633 // underlying type, but do allow it in all other contexts. 17634 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17635 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17636 // constant-expression in the enumerator-definition shall be a converted 17637 // constant expression of the underlying type. 17638 EltTy = Enum->getIntegerType(); 17639 ExprResult Converted = 17640 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17641 CCEK_Enumerator); 17642 if (Converted.isInvalid()) 17643 Val = nullptr; 17644 else 17645 Val = Converted.get(); 17646 } else if (!Val->isValueDependent() && 17647 !(Val = 17648 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17649 .get())) { 17650 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17651 } else { 17652 if (Enum->isComplete()) { 17653 EltTy = Enum->getIntegerType(); 17654 17655 // In Obj-C and Microsoft mode, require the enumeration value to be 17656 // representable in the underlying type of the enumeration. In C++11, 17657 // we perform a non-narrowing conversion as part of converted constant 17658 // expression checking. 17659 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17660 if (Context.getTargetInfo() 17661 .getTriple() 17662 .isWindowsMSVCEnvironment()) { 17663 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17664 } else { 17665 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17666 } 17667 } 17668 17669 // Cast to the underlying type. 17670 Val = ImpCastExprToType(Val, EltTy, 17671 EltTy->isBooleanType() ? CK_IntegralToBoolean 17672 : CK_IntegralCast) 17673 .get(); 17674 } else if (getLangOpts().CPlusPlus) { 17675 // C++11 [dcl.enum]p5: 17676 // If the underlying type is not fixed, the type of each enumerator 17677 // is the type of its initializing value: 17678 // - If an initializer is specified for an enumerator, the 17679 // initializing value has the same type as the expression. 17680 EltTy = Val->getType(); 17681 } else { 17682 // C99 6.7.2.2p2: 17683 // The expression that defines the value of an enumeration constant 17684 // shall be an integer constant expression that has a value 17685 // representable as an int. 17686 17687 // Complain if the value is not representable in an int. 17688 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17689 Diag(IdLoc, diag::ext_enum_value_not_int) 17690 << EnumVal.toString(10) << Val->getSourceRange() 17691 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17692 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17693 // Force the type of the expression to 'int'. 17694 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17695 } 17696 EltTy = Val->getType(); 17697 } 17698 } 17699 } 17700 } 17701 17702 if (!Val) { 17703 if (Enum->isDependentType()) 17704 EltTy = Context.DependentTy; 17705 else if (!LastEnumConst) { 17706 // C++0x [dcl.enum]p5: 17707 // If the underlying type is not fixed, the type of each enumerator 17708 // is the type of its initializing value: 17709 // - If no initializer is specified for the first enumerator, the 17710 // initializing value has an unspecified integral type. 17711 // 17712 // GCC uses 'int' for its unspecified integral type, as does 17713 // C99 6.7.2.2p3. 17714 if (Enum->isFixed()) { 17715 EltTy = Enum->getIntegerType(); 17716 } 17717 else { 17718 EltTy = Context.IntTy; 17719 } 17720 } else { 17721 // Assign the last value + 1. 17722 EnumVal = LastEnumConst->getInitVal(); 17723 ++EnumVal; 17724 EltTy = LastEnumConst->getType(); 17725 17726 // Check for overflow on increment. 17727 if (EnumVal < LastEnumConst->getInitVal()) { 17728 // C++0x [dcl.enum]p5: 17729 // If the underlying type is not fixed, the type of each enumerator 17730 // is the type of its initializing value: 17731 // 17732 // - Otherwise the type of the initializing value is the same as 17733 // the type of the initializing value of the preceding enumerator 17734 // unless the incremented value is not representable in that type, 17735 // in which case the type is an unspecified integral type 17736 // sufficient to contain the incremented value. If no such type 17737 // exists, the program is ill-formed. 17738 QualType T = getNextLargerIntegralType(Context, EltTy); 17739 if (T.isNull() || Enum->isFixed()) { 17740 // There is no integral type larger enough to represent this 17741 // value. Complain, then allow the value to wrap around. 17742 EnumVal = LastEnumConst->getInitVal(); 17743 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17744 ++EnumVal; 17745 if (Enum->isFixed()) 17746 // When the underlying type is fixed, this is ill-formed. 17747 Diag(IdLoc, diag::err_enumerator_wrapped) 17748 << EnumVal.toString(10) 17749 << EltTy; 17750 else 17751 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17752 << EnumVal.toString(10); 17753 } else { 17754 EltTy = T; 17755 } 17756 17757 // Retrieve the last enumerator's value, extent that type to the 17758 // type that is supposed to be large enough to represent the incremented 17759 // value, then increment. 17760 EnumVal = LastEnumConst->getInitVal(); 17761 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17762 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17763 ++EnumVal; 17764 17765 // If we're not in C++, diagnose the overflow of enumerator values, 17766 // which in C99 means that the enumerator value is not representable in 17767 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17768 // permits enumerator values that are representable in some larger 17769 // integral type. 17770 if (!getLangOpts().CPlusPlus && !T.isNull()) 17771 Diag(IdLoc, diag::warn_enum_value_overflow); 17772 } else if (!getLangOpts().CPlusPlus && 17773 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17774 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17775 Diag(IdLoc, diag::ext_enum_value_not_int) 17776 << EnumVal.toString(10) << 1; 17777 } 17778 } 17779 } 17780 17781 if (!EltTy->isDependentType()) { 17782 // Make the enumerator value match the signedness and size of the 17783 // enumerator's type. 17784 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17785 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17786 } 17787 17788 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17789 Val, EnumVal); 17790 } 17791 17792 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17793 SourceLocation IILoc) { 17794 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17795 !getLangOpts().CPlusPlus) 17796 return SkipBodyInfo(); 17797 17798 // We have an anonymous enum definition. Look up the first enumerator to 17799 // determine if we should merge the definition with an existing one and 17800 // skip the body. 17801 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17802 forRedeclarationInCurContext()); 17803 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17804 if (!PrevECD) 17805 return SkipBodyInfo(); 17806 17807 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17808 NamedDecl *Hidden; 17809 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17810 SkipBodyInfo Skip; 17811 Skip.Previous = Hidden; 17812 return Skip; 17813 } 17814 17815 return SkipBodyInfo(); 17816 } 17817 17818 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17819 SourceLocation IdLoc, IdentifierInfo *Id, 17820 const ParsedAttributesView &Attrs, 17821 SourceLocation EqualLoc, Expr *Val) { 17822 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17823 EnumConstantDecl *LastEnumConst = 17824 cast_or_null<EnumConstantDecl>(lastEnumConst); 17825 17826 // The scope passed in may not be a decl scope. Zip up the scope tree until 17827 // we find one that is. 17828 S = getNonFieldDeclScope(S); 17829 17830 // Verify that there isn't already something declared with this name in this 17831 // scope. 17832 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17833 LookupName(R, S); 17834 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17835 17836 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17837 // Maybe we will complain about the shadowed template parameter. 17838 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17839 // Just pretend that we didn't see the previous declaration. 17840 PrevDecl = nullptr; 17841 } 17842 17843 // C++ [class.mem]p15: 17844 // If T is the name of a class, then each of the following shall have a name 17845 // different from T: 17846 // - every enumerator of every member of class T that is an unscoped 17847 // enumerated type 17848 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17849 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17850 DeclarationNameInfo(Id, IdLoc)); 17851 17852 EnumConstantDecl *New = 17853 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17854 if (!New) 17855 return nullptr; 17856 17857 if (PrevDecl) { 17858 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17859 // Check for other kinds of shadowing not already handled. 17860 CheckShadow(New, PrevDecl, R); 17861 } 17862 17863 // When in C++, we may get a TagDecl with the same name; in this case the 17864 // enum constant will 'hide' the tag. 17865 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17866 "Received TagDecl when not in C++!"); 17867 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17868 if (isa<EnumConstantDecl>(PrevDecl)) 17869 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17870 else 17871 Diag(IdLoc, diag::err_redefinition) << Id; 17872 notePreviousDefinition(PrevDecl, IdLoc); 17873 return nullptr; 17874 } 17875 } 17876 17877 // Process attributes. 17878 ProcessDeclAttributeList(S, New, Attrs); 17879 AddPragmaAttributes(S, New); 17880 17881 // Register this decl in the current scope stack. 17882 New->setAccess(TheEnumDecl->getAccess()); 17883 PushOnScopeChains(New, S); 17884 17885 ActOnDocumentableDecl(New); 17886 17887 return New; 17888 } 17889 17890 // Returns true when the enum initial expression does not trigger the 17891 // duplicate enum warning. A few common cases are exempted as follows: 17892 // Element2 = Element1 17893 // Element2 = Element1 + 1 17894 // Element2 = Element1 - 1 17895 // Where Element2 and Element1 are from the same enum. 17896 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17897 Expr *InitExpr = ECD->getInitExpr(); 17898 if (!InitExpr) 17899 return true; 17900 InitExpr = InitExpr->IgnoreImpCasts(); 17901 17902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17903 if (!BO->isAdditiveOp()) 17904 return true; 17905 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17906 if (!IL) 17907 return true; 17908 if (IL->getValue() != 1) 17909 return true; 17910 17911 InitExpr = BO->getLHS(); 17912 } 17913 17914 // This checks if the elements are from the same enum. 17915 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17916 if (!DRE) 17917 return true; 17918 17919 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17920 if (!EnumConstant) 17921 return true; 17922 17923 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17924 Enum) 17925 return true; 17926 17927 return false; 17928 } 17929 17930 // Emits a warning when an element is implicitly set a value that 17931 // a previous element has already been set to. 17932 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17933 EnumDecl *Enum, QualType EnumType) { 17934 // Avoid anonymous enums 17935 if (!Enum->getIdentifier()) 17936 return; 17937 17938 // Only check for small enums. 17939 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17940 return; 17941 17942 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17943 return; 17944 17945 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17946 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17947 17948 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17949 17950 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17951 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17952 17953 // Use int64_t as a key to avoid needing special handling for map keys. 17954 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17955 llvm::APSInt Val = D->getInitVal(); 17956 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17957 }; 17958 17959 DuplicatesVector DupVector; 17960 ValueToVectorMap EnumMap; 17961 17962 // Populate the EnumMap with all values represented by enum constants without 17963 // an initializer. 17964 for (auto *Element : Elements) { 17965 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17966 17967 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17968 // this constant. Skip this enum since it may be ill-formed. 17969 if (!ECD) { 17970 return; 17971 } 17972 17973 // Constants with initalizers are handled in the next loop. 17974 if (ECD->getInitExpr()) 17975 continue; 17976 17977 // Duplicate values are handled in the next loop. 17978 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17979 } 17980 17981 if (EnumMap.size() == 0) 17982 return; 17983 17984 // Create vectors for any values that has duplicates. 17985 for (auto *Element : Elements) { 17986 // The last loop returned if any constant was null. 17987 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17988 if (!ValidDuplicateEnum(ECD, Enum)) 17989 continue; 17990 17991 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17992 if (Iter == EnumMap.end()) 17993 continue; 17994 17995 DeclOrVector& Entry = Iter->second; 17996 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17997 // Ensure constants are different. 17998 if (D == ECD) 17999 continue; 18000 18001 // Create new vector and push values onto it. 18002 auto Vec = std::make_unique<ECDVector>(); 18003 Vec->push_back(D); 18004 Vec->push_back(ECD); 18005 18006 // Update entry to point to the duplicates vector. 18007 Entry = Vec.get(); 18008 18009 // Store the vector somewhere we can consult later for quick emission of 18010 // diagnostics. 18011 DupVector.emplace_back(std::move(Vec)); 18012 continue; 18013 } 18014 18015 ECDVector *Vec = Entry.get<ECDVector*>(); 18016 // Make sure constants are not added more than once. 18017 if (*Vec->begin() == ECD) 18018 continue; 18019 18020 Vec->push_back(ECD); 18021 } 18022 18023 // Emit diagnostics. 18024 for (const auto &Vec : DupVector) { 18025 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18026 18027 // Emit warning for one enum constant. 18028 auto *FirstECD = Vec->front(); 18029 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18030 << FirstECD << FirstECD->getInitVal().toString(10) 18031 << FirstECD->getSourceRange(); 18032 18033 // Emit one note for each of the remaining enum constants with 18034 // the same value. 18035 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18036 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18037 << ECD << ECD->getInitVal().toString(10) 18038 << ECD->getSourceRange(); 18039 } 18040 } 18041 18042 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18043 bool AllowMask) const { 18044 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18045 assert(ED->isCompleteDefinition() && "expected enum definition"); 18046 18047 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18048 llvm::APInt &FlagBits = R.first->second; 18049 18050 if (R.second) { 18051 for (auto *E : ED->enumerators()) { 18052 const auto &EVal = E->getInitVal(); 18053 // Only single-bit enumerators introduce new flag values. 18054 if (EVal.isPowerOf2()) 18055 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18056 } 18057 } 18058 18059 // A value is in a flag enum if either its bits are a subset of the enum's 18060 // flag bits (the first condition) or we are allowing masks and the same is 18061 // true of its complement (the second condition). When masks are allowed, we 18062 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18063 // 18064 // While it's true that any value could be used as a mask, the assumption is 18065 // that a mask will have all of the insignificant bits set. Anything else is 18066 // likely a logic error. 18067 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18068 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18069 } 18070 18071 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18072 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18073 const ParsedAttributesView &Attrs) { 18074 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18075 QualType EnumType = Context.getTypeDeclType(Enum); 18076 18077 ProcessDeclAttributeList(S, Enum, Attrs); 18078 18079 if (Enum->isDependentType()) { 18080 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18081 EnumConstantDecl *ECD = 18082 cast_or_null<EnumConstantDecl>(Elements[i]); 18083 if (!ECD) continue; 18084 18085 ECD->setType(EnumType); 18086 } 18087 18088 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18089 return; 18090 } 18091 18092 // TODO: If the result value doesn't fit in an int, it must be a long or long 18093 // long value. ISO C does not support this, but GCC does as an extension, 18094 // emit a warning. 18095 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18096 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18097 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18098 18099 // Verify that all the values are okay, compute the size of the values, and 18100 // reverse the list. 18101 unsigned NumNegativeBits = 0; 18102 unsigned NumPositiveBits = 0; 18103 18104 // Keep track of whether all elements have type int. 18105 bool AllElementsInt = true; 18106 18107 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18108 EnumConstantDecl *ECD = 18109 cast_or_null<EnumConstantDecl>(Elements[i]); 18110 if (!ECD) continue; // Already issued a diagnostic. 18111 18112 const llvm::APSInt &InitVal = ECD->getInitVal(); 18113 18114 // Keep track of the size of positive and negative values. 18115 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18116 NumPositiveBits = std::max(NumPositiveBits, 18117 (unsigned)InitVal.getActiveBits()); 18118 else 18119 NumNegativeBits = std::max(NumNegativeBits, 18120 (unsigned)InitVal.getMinSignedBits()); 18121 18122 // Keep track of whether every enum element has type int (very common). 18123 if (AllElementsInt) 18124 AllElementsInt = ECD->getType() == Context.IntTy; 18125 } 18126 18127 // Figure out the type that should be used for this enum. 18128 QualType BestType; 18129 unsigned BestWidth; 18130 18131 // C++0x N3000 [conv.prom]p3: 18132 // An rvalue of an unscoped enumeration type whose underlying 18133 // type is not fixed can be converted to an rvalue of the first 18134 // of the following types that can represent all the values of 18135 // the enumeration: int, unsigned int, long int, unsigned long 18136 // int, long long int, or unsigned long long int. 18137 // C99 6.4.4.3p2: 18138 // An identifier declared as an enumeration constant has type int. 18139 // The C99 rule is modified by a gcc extension 18140 QualType BestPromotionType; 18141 18142 bool Packed = Enum->hasAttr<PackedAttr>(); 18143 // -fshort-enums is the equivalent to specifying the packed attribute on all 18144 // enum definitions. 18145 if (LangOpts.ShortEnums) 18146 Packed = true; 18147 18148 // If the enum already has a type because it is fixed or dictated by the 18149 // target, promote that type instead of analyzing the enumerators. 18150 if (Enum->isComplete()) { 18151 BestType = Enum->getIntegerType(); 18152 if (BestType->isPromotableIntegerType()) 18153 BestPromotionType = Context.getPromotedIntegerType(BestType); 18154 else 18155 BestPromotionType = BestType; 18156 18157 BestWidth = Context.getIntWidth(BestType); 18158 } 18159 else if (NumNegativeBits) { 18160 // If there is a negative value, figure out the smallest integer type (of 18161 // int/long/longlong) that fits. 18162 // If it's packed, check also if it fits a char or a short. 18163 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18164 BestType = Context.SignedCharTy; 18165 BestWidth = CharWidth; 18166 } else if (Packed && NumNegativeBits <= ShortWidth && 18167 NumPositiveBits < ShortWidth) { 18168 BestType = Context.ShortTy; 18169 BestWidth = ShortWidth; 18170 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18171 BestType = Context.IntTy; 18172 BestWidth = IntWidth; 18173 } else { 18174 BestWidth = Context.getTargetInfo().getLongWidth(); 18175 18176 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18177 BestType = Context.LongTy; 18178 } else { 18179 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18180 18181 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18182 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18183 BestType = Context.LongLongTy; 18184 } 18185 } 18186 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18187 } else { 18188 // If there is no negative value, figure out the smallest type that fits 18189 // all of the enumerator values. 18190 // If it's packed, check also if it fits a char or a short. 18191 if (Packed && NumPositiveBits <= CharWidth) { 18192 BestType = Context.UnsignedCharTy; 18193 BestPromotionType = Context.IntTy; 18194 BestWidth = CharWidth; 18195 } else if (Packed && NumPositiveBits <= ShortWidth) { 18196 BestType = Context.UnsignedShortTy; 18197 BestPromotionType = Context.IntTy; 18198 BestWidth = ShortWidth; 18199 } else if (NumPositiveBits <= IntWidth) { 18200 BestType = Context.UnsignedIntTy; 18201 BestWidth = IntWidth; 18202 BestPromotionType 18203 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18204 ? Context.UnsignedIntTy : Context.IntTy; 18205 } else if (NumPositiveBits <= 18206 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18207 BestType = Context.UnsignedLongTy; 18208 BestPromotionType 18209 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18210 ? Context.UnsignedLongTy : Context.LongTy; 18211 } else { 18212 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18213 assert(NumPositiveBits <= BestWidth && 18214 "How could an initializer get larger than ULL?"); 18215 BestType = Context.UnsignedLongLongTy; 18216 BestPromotionType 18217 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18218 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18219 } 18220 } 18221 18222 // Loop over all of the enumerator constants, changing their types to match 18223 // the type of the enum if needed. 18224 for (auto *D : Elements) { 18225 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18226 if (!ECD) continue; // Already issued a diagnostic. 18227 18228 // Standard C says the enumerators have int type, but we allow, as an 18229 // extension, the enumerators to be larger than int size. If each 18230 // enumerator value fits in an int, type it as an int, otherwise type it the 18231 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18232 // that X has type 'int', not 'unsigned'. 18233 18234 // Determine whether the value fits into an int. 18235 llvm::APSInt InitVal = ECD->getInitVal(); 18236 18237 // If it fits into an integer type, force it. Otherwise force it to match 18238 // the enum decl type. 18239 QualType NewTy; 18240 unsigned NewWidth; 18241 bool NewSign; 18242 if (!getLangOpts().CPlusPlus && 18243 !Enum->isFixed() && 18244 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18245 NewTy = Context.IntTy; 18246 NewWidth = IntWidth; 18247 NewSign = true; 18248 } else if (ECD->getType() == BestType) { 18249 // Already the right type! 18250 if (getLangOpts().CPlusPlus) 18251 // C++ [dcl.enum]p4: Following the closing brace of an 18252 // enum-specifier, each enumerator has the type of its 18253 // enumeration. 18254 ECD->setType(EnumType); 18255 continue; 18256 } else { 18257 NewTy = BestType; 18258 NewWidth = BestWidth; 18259 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18260 } 18261 18262 // Adjust the APSInt value. 18263 InitVal = InitVal.extOrTrunc(NewWidth); 18264 InitVal.setIsSigned(NewSign); 18265 ECD->setInitVal(InitVal); 18266 18267 // Adjust the Expr initializer and type. 18268 if (ECD->getInitExpr() && 18269 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18270 ECD->setInitExpr(ImplicitCastExpr::Create( 18271 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18272 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18273 if (getLangOpts().CPlusPlus) 18274 // C++ [dcl.enum]p4: Following the closing brace of an 18275 // enum-specifier, each enumerator has the type of its 18276 // enumeration. 18277 ECD->setType(EnumType); 18278 else 18279 ECD->setType(NewTy); 18280 } 18281 18282 Enum->completeDefinition(BestType, BestPromotionType, 18283 NumPositiveBits, NumNegativeBits); 18284 18285 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18286 18287 if (Enum->isClosedFlag()) { 18288 for (Decl *D : Elements) { 18289 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18290 if (!ECD) continue; // Already issued a diagnostic. 18291 18292 llvm::APSInt InitVal = ECD->getInitVal(); 18293 if (InitVal != 0 && !InitVal.isPowerOf2() && 18294 !IsValueInFlagEnum(Enum, InitVal, true)) 18295 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18296 << ECD << Enum; 18297 } 18298 } 18299 18300 // Now that the enum type is defined, ensure it's not been underaligned. 18301 if (Enum->hasAttrs()) 18302 CheckAlignasUnderalignment(Enum); 18303 } 18304 18305 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18306 SourceLocation StartLoc, 18307 SourceLocation EndLoc) { 18308 StringLiteral *AsmString = cast<StringLiteral>(expr); 18309 18310 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18311 AsmString, StartLoc, 18312 EndLoc); 18313 CurContext->addDecl(New); 18314 return New; 18315 } 18316 18317 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18318 IdentifierInfo* AliasName, 18319 SourceLocation PragmaLoc, 18320 SourceLocation NameLoc, 18321 SourceLocation AliasNameLoc) { 18322 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18323 LookupOrdinaryName); 18324 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18325 AttributeCommonInfo::AS_Pragma); 18326 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18327 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18328 18329 // If a declaration that: 18330 // 1) declares a function or a variable 18331 // 2) has external linkage 18332 // already exists, add a label attribute to it. 18333 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18334 if (isDeclExternC(PrevDecl)) 18335 PrevDecl->addAttr(Attr); 18336 else 18337 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18338 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18339 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18340 } else 18341 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18342 } 18343 18344 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18345 SourceLocation PragmaLoc, 18346 SourceLocation NameLoc) { 18347 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18348 18349 if (PrevDecl) { 18350 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18351 } else { 18352 (void)WeakUndeclaredIdentifiers.insert( 18353 std::pair<IdentifierInfo*,WeakInfo> 18354 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18355 } 18356 } 18357 18358 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18359 IdentifierInfo* AliasName, 18360 SourceLocation PragmaLoc, 18361 SourceLocation NameLoc, 18362 SourceLocation AliasNameLoc) { 18363 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18364 LookupOrdinaryName); 18365 WeakInfo W = WeakInfo(Name, NameLoc); 18366 18367 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18368 if (!PrevDecl->hasAttr<AliasAttr>()) 18369 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18370 DeclApplyPragmaWeak(TUScope, ND, W); 18371 } else { 18372 (void)WeakUndeclaredIdentifiers.insert( 18373 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18374 } 18375 } 18376 18377 Decl *Sema::getObjCDeclContext() const { 18378 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18379 } 18380 18381 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18382 bool Final) { 18383 assert(FD && "Expected non-null FunctionDecl"); 18384 18385 // SYCL functions can be template, so we check if they have appropriate 18386 // attribute prior to checking if it is a template. 18387 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18388 return FunctionEmissionStatus::Emitted; 18389 18390 // Templates are emitted when they're instantiated. 18391 if (FD->isDependentContext()) 18392 return FunctionEmissionStatus::TemplateDiscarded; 18393 18394 // Check whether this function is an externally visible definition. 18395 auto IsEmittedForExternalSymbol = [this, FD]() { 18396 // We have to check the GVA linkage of the function's *definition* -- if we 18397 // only have a declaration, we don't know whether or not the function will 18398 // be emitted, because (say) the definition could include "inline". 18399 FunctionDecl *Def = FD->getDefinition(); 18400 18401 return Def && !isDiscardableGVALinkage( 18402 getASTContext().GetGVALinkageForFunction(Def)); 18403 }; 18404 18405 if (LangOpts.OpenMPIsDevice) { 18406 // In OpenMP device mode we will not emit host only functions, or functions 18407 // we don't need due to their linkage. 18408 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18409 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18410 // DevTy may be changed later by 18411 // #pragma omp declare target to(*) device_type(*). 18412 // Therefore DevTyhaving no value does not imply host. The emission status 18413 // will be checked again at the end of compilation unit with Final = true. 18414 if (DevTy.hasValue()) 18415 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18416 return FunctionEmissionStatus::OMPDiscarded; 18417 // If we have an explicit value for the device type, or we are in a target 18418 // declare context, we need to emit all extern and used symbols. 18419 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18420 if (IsEmittedForExternalSymbol()) 18421 return FunctionEmissionStatus::Emitted; 18422 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18423 // we'll omit it. 18424 if (Final) 18425 return FunctionEmissionStatus::OMPDiscarded; 18426 } else if (LangOpts.OpenMP > 45) { 18427 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18428 // function. In 5.0, no_host was introduced which might cause a function to 18429 // be ommitted. 18430 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18431 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18432 if (DevTy.hasValue()) 18433 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18434 return FunctionEmissionStatus::OMPDiscarded; 18435 } 18436 18437 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18438 return FunctionEmissionStatus::Emitted; 18439 18440 if (LangOpts.CUDA) { 18441 // When compiling for device, host functions are never emitted. Similarly, 18442 // when compiling for host, device and global functions are never emitted. 18443 // (Technically, we do emit a host-side stub for global functions, but this 18444 // doesn't count for our purposes here.) 18445 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18446 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18447 return FunctionEmissionStatus::CUDADiscarded; 18448 if (!LangOpts.CUDAIsDevice && 18449 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18450 return FunctionEmissionStatus::CUDADiscarded; 18451 18452 if (IsEmittedForExternalSymbol()) 18453 return FunctionEmissionStatus::Emitted; 18454 } 18455 18456 // Otherwise, the function is known-emitted if it's in our set of 18457 // known-emitted functions. 18458 return FunctionEmissionStatus::Unknown; 18459 } 18460 18461 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18462 // Host-side references to a __global__ function refer to the stub, so the 18463 // function itself is never emitted and therefore should not be marked. 18464 // If we have host fn calls kernel fn calls host+device, the HD function 18465 // does not get instantiated on the host. We model this by omitting at the 18466 // call to the kernel from the callgraph. This ensures that, when compiling 18467 // for host, only HD functions actually called from the host get marked as 18468 // known-emitted. 18469 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18470 IdentifyCUDATarget(Callee) == CFT_Global; 18471 } 18472