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___ibm128: 145 case tok::kw_wchar_t: 146 case tok::kw_bool: 147 case tok::kw___underlying_type: 148 case tok::kw___auto_type: 149 return true; 150 151 case tok::annot_typename: 152 case tok::kw_char16_t: 153 case tok::kw_char32_t: 154 case tok::kw_typeof: 155 case tok::annot_decltype: 156 case tok::kw_decltype: 157 return getLangOpts().CPlusPlus; 158 159 case tok::kw_char8_t: 160 return getLangOpts().Char8; 161 162 default: 163 break; 164 } 165 166 return false; 167 } 168 169 namespace { 170 enum class UnqualifiedTypeNameLookupResult { 171 NotFound, 172 FoundNonType, 173 FoundType 174 }; 175 } // end anonymous namespace 176 177 /// Tries to perform unqualified lookup of the type decls in bases for 178 /// dependent class. 179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 180 /// type decl, \a FoundType if only type decls are found. 181 static UnqualifiedTypeNameLookupResult 182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 183 SourceLocation NameLoc, 184 const CXXRecordDecl *RD) { 185 if (!RD->hasDefinition()) 186 return UnqualifiedTypeNameLookupResult::NotFound; 187 // Look for type decls in base classes. 188 UnqualifiedTypeNameLookupResult FoundTypeDecl = 189 UnqualifiedTypeNameLookupResult::NotFound; 190 for (const auto &Base : RD->bases()) { 191 const CXXRecordDecl *BaseRD = nullptr; 192 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 193 BaseRD = BaseTT->getAsCXXRecordDecl(); 194 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 195 // Look for type decls in dependent base classes that have known primary 196 // templates. 197 if (!TST || !TST->isDependentType()) 198 continue; 199 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 200 if (!TD) 201 continue; 202 if (auto *BasePrimaryTemplate = 203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 204 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = BasePrimaryTemplate; 206 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 207 if (const ClassTemplatePartialSpecializationDecl *PS = 208 CTD->findPartialSpecialization(Base.getType())) 209 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 210 BaseRD = PS; 211 } 212 } 213 } 214 if (BaseRD) { 215 for (NamedDecl *ND : BaseRD->lookup(&II)) { 216 if (!isa<TypeDecl>(ND)) 217 return UnqualifiedTypeNameLookupResult::FoundNonType; 218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 219 } 220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 221 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 222 case UnqualifiedTypeNameLookupResult::FoundNonType: 223 return UnqualifiedTypeNameLookupResult::FoundNonType; 224 case UnqualifiedTypeNameLookupResult::FoundType: 225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 226 break; 227 case UnqualifiedTypeNameLookupResult::NotFound: 228 break; 229 } 230 } 231 } 232 } 233 234 return FoundTypeDecl; 235 } 236 237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 238 const IdentifierInfo &II, 239 SourceLocation NameLoc) { 240 // Lookup in the parent class template context, if any. 241 const CXXRecordDecl *RD = nullptr; 242 UnqualifiedTypeNameLookupResult FoundTypeDecl = 243 UnqualifiedTypeNameLookupResult::NotFound; 244 for (DeclContext *DC = S.CurContext; 245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 246 DC = DC->getParent()) { 247 // Look for type decls in dependent base classes that have known primary 248 // templates. 249 RD = dyn_cast<CXXRecordDecl>(DC); 250 if (RD && RD->getDescribedClassTemplate()) 251 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 252 } 253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 254 return nullptr; 255 256 // We found some types in dependent base classes. Recover as if the user 257 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 258 // lookup during template instantiation. 259 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 260 261 ASTContext &Context = S.Context; 262 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 263 cast<Type>(Context.getRecordType(RD))); 264 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 265 266 CXXScopeSpec SS; 267 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 268 269 TypeLocBuilder Builder; 270 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 271 DepTL.setNameLoc(NameLoc); 272 DepTL.setElaboratedKeywordLoc(SourceLocation()); 273 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 274 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 275 } 276 277 /// If the identifier refers to a type name within this scope, 278 /// return the declaration of that type. 279 /// 280 /// This routine performs ordinary name lookup of the identifier II 281 /// within the given scope, with optional C++ scope specifier SS, to 282 /// determine whether the name refers to a type. If so, returns an 283 /// opaque pointer (actually a QualType) corresponding to that 284 /// type. Otherwise, returns NULL. 285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 286 Scope *S, CXXScopeSpec *SS, 287 bool isClassName, bool HasTrailingDot, 288 ParsedType ObjectTypePtr, 289 bool IsCtorOrDtorName, 290 bool WantNontrivialTypeSourceInfo, 291 bool IsClassTemplateDeductionContext, 292 IdentifierInfo **CorrectedII) { 293 // FIXME: Consider allowing this outside C++1z mode as an extension. 294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 296 !isClassName && !HasTrailingDot; 297 298 // Determine where we will perform name lookup. 299 DeclContext *LookupCtx = nullptr; 300 if (ObjectTypePtr) { 301 QualType ObjectType = ObjectTypePtr.get(); 302 if (ObjectType->isRecordType()) 303 LookupCtx = computeDeclContext(ObjectType); 304 } else if (SS && SS->isNotEmpty()) { 305 LookupCtx = computeDeclContext(*SS, false); 306 307 if (!LookupCtx) { 308 if (isDependentScopeSpecifier(*SS)) { 309 // C++ [temp.res]p3: 310 // A qualified-id that refers to a type and in which the 311 // nested-name-specifier depends on a template-parameter (14.6.2) 312 // shall be prefixed by the keyword typename to indicate that the 313 // qualified-id denotes a type, forming an 314 // elaborated-type-specifier (7.1.5.3). 315 // 316 // We therefore do not perform any name lookup if the result would 317 // refer to a member of an unknown specialization. 318 if (!isClassName && !IsCtorOrDtorName) 319 return nullptr; 320 321 // We know from the grammar that this name refers to a type, 322 // so build a dependent node to describe the type. 323 if (WantNontrivialTypeSourceInfo) 324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 325 326 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 327 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 328 II, NameLoc); 329 return ParsedType::make(T); 330 } 331 332 return nullptr; 333 } 334 335 if (!LookupCtx->isDependentContext() && 336 RequireCompleteDeclContext(*SS, LookupCtx)) 337 return nullptr; 338 } 339 340 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 341 // lookup for class-names. 342 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 343 LookupOrdinaryName; 344 LookupResult Result(*this, &II, NameLoc, Kind); 345 if (LookupCtx) { 346 // Perform "qualified" name lookup into the declaration context we 347 // computed, which is either the type of the base of a member access 348 // expression or the declaration context associated with a prior 349 // nested-name-specifier. 350 LookupQualifiedName(Result, LookupCtx); 351 352 if (ObjectTypePtr && Result.empty()) { 353 // C++ [basic.lookup.classref]p3: 354 // If the unqualified-id is ~type-name, the type-name is looked up 355 // in the context of the entire postfix-expression. If the type T of 356 // the object expression is of a class type C, the type-name is also 357 // looked up in the scope of class C. At least one of the lookups shall 358 // find a name that refers to (possibly cv-qualified) T. 359 LookupName(Result, S); 360 } 361 } else { 362 // Perform unqualified name lookup. 363 LookupName(Result, S); 364 365 // For unqualified lookup in a class template in MSVC mode, look into 366 // dependent base classes where the primary class template is known. 367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 368 if (ParsedType TypeInBase = 369 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 370 return TypeInBase; 371 } 372 } 373 374 NamedDecl *IIDecl = nullptr; 375 switch (Result.getResultKind()) { 376 case LookupResult::NotFound: 377 case LookupResult::NotFoundInCurrentInstantiation: 378 if (CorrectedII) { 379 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 380 AllowDeducedTemplate); 381 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 382 S, SS, CCC, CTK_ErrorRecovery); 383 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 384 TemplateTy Template; 385 bool MemberOfUnknownSpecialization; 386 UnqualifiedId TemplateName; 387 TemplateName.setIdentifier(NewII, NameLoc); 388 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 389 CXXScopeSpec NewSS, *NewSSPtr = SS; 390 if (SS && NNS) { 391 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 392 NewSSPtr = &NewSS; 393 } 394 if (Correction && (NNS || NewII != &II) && 395 // Ignore a correction to a template type as the to-be-corrected 396 // identifier is not a template (typo correction for template names 397 // is handled elsewhere). 398 !(getLangOpts().CPlusPlus && NewSSPtr && 399 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 400 Template, MemberOfUnknownSpecialization))) { 401 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 402 isClassName, HasTrailingDot, ObjectTypePtr, 403 IsCtorOrDtorName, 404 WantNontrivialTypeSourceInfo, 405 IsClassTemplateDeductionContext); 406 if (Ty) { 407 diagnoseTypo(Correction, 408 PDiag(diag::err_unknown_type_or_class_name_suggest) 409 << Result.getLookupName() << isClassName); 410 if (SS && NNS) 411 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 412 *CorrectedII = NewII; 413 return Ty; 414 } 415 } 416 } 417 // If typo correction failed or was not performed, fall through 418 LLVM_FALLTHROUGH; 419 case LookupResult::FoundOverloaded: 420 case LookupResult::FoundUnresolvedValue: 421 Result.suppressDiagnostics(); 422 return nullptr; 423 424 case LookupResult::Ambiguous: 425 // Recover from type-hiding ambiguities by hiding the type. We'll 426 // do the lookup again when looking for an object, and we can 427 // diagnose the error then. If we don't do this, then the error 428 // about hiding the type will be immediately followed by an error 429 // that only makes sense if the identifier was treated like a type. 430 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 431 Result.suppressDiagnostics(); 432 return nullptr; 433 } 434 435 // Look to see if we have a type anywhere in the list of results. 436 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 437 Res != ResEnd; ++Res) { 438 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 439 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 440 RealRes) || 441 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 442 if (!IIDecl || 443 // Make the selection of the recovery decl deterministic. 444 RealRes->getLocation() < IIDecl->getLocation()) 445 IIDecl = RealRes; 446 } 447 } 448 449 if (!IIDecl) { 450 // None of the entities we found is a type, so there is no way 451 // to even assume that the result is a type. In this case, don't 452 // complain about the ambiguity. The parser will either try to 453 // perform this lookup again (e.g., as an object name), which 454 // will produce the ambiguity, or will complain that it expected 455 // a type name. 456 Result.suppressDiagnostics(); 457 return nullptr; 458 } 459 460 // We found a type within the ambiguous lookup; diagnose the 461 // ambiguity and then return that type. This might be the right 462 // answer, or it might not be, but it suppresses any attempt to 463 // perform the name lookup again. 464 break; 465 466 case LookupResult::Found: 467 IIDecl = Result.getFoundDecl(); 468 break; 469 } 470 471 assert(IIDecl && "Didn't find decl"); 472 473 QualType T; 474 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 475 // C++ [class.qual]p2: A lookup that would find the injected-class-name 476 // instead names the constructors of the class, except when naming a class. 477 // This is ill-formed when we're not actually forming a ctor or dtor name. 478 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 479 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 480 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 481 FoundRD->isInjectedClassName() && 482 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 483 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 484 << &II << /*Type*/1; 485 486 DiagnoseUseOfDecl(IIDecl, NameLoc); 487 488 T = Context.getTypeDeclType(TD); 489 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 490 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 491 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 492 if (!HasTrailingDot) 493 T = Context.getObjCInterfaceType(IDecl); 494 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 495 (void)DiagnoseUseOfDecl(UD, NameLoc); 496 // Recover with 'int' 497 T = Context.IntTy; 498 } else if (AllowDeducedTemplate) { 499 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 500 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 501 QualType(), false); 502 } 503 504 if (T.isNull()) { 505 // If it's not plausibly a type, suppress diagnostics. 506 Result.suppressDiagnostics(); 507 return nullptr; 508 } 509 510 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 511 // constructor or destructor name (in such a case, the scope specifier 512 // will be attached to the enclosing Expr or Decl node). 513 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 514 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 515 if (WantNontrivialTypeSourceInfo) { 516 // Construct a type with type-source information. 517 TypeLocBuilder Builder; 518 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 519 520 T = getElaboratedType(ETK_None, *SS, T); 521 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 522 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 523 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 524 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 525 } else { 526 T = getElaboratedType(ETK_None, *SS, T); 527 } 528 } 529 530 return ParsedType::make(T); 531 } 532 533 // Builds a fake NNS for the given decl context. 534 static NestedNameSpecifier * 535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 536 for (;; DC = DC->getLookupParent()) { 537 DC = DC->getPrimaryContext(); 538 auto *ND = dyn_cast<NamespaceDecl>(DC); 539 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 540 return NestedNameSpecifier::Create(Context, nullptr, ND); 541 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 542 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 543 RD->getTypeForDecl()); 544 else if (isa<TranslationUnitDecl>(DC)) 545 return NestedNameSpecifier::GlobalSpecifier(Context); 546 } 547 llvm_unreachable("something isn't in TU scope?"); 548 } 549 550 /// Find the parent class with dependent bases of the innermost enclosing method 551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 552 /// up allowing unqualified dependent type names at class-level, which MSVC 553 /// correctly rejects. 554 static const CXXRecordDecl * 555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 556 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 557 DC = DC->getPrimaryContext(); 558 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 559 if (MD->getParent()->hasAnyDependentBases()) 560 return MD->getParent(); 561 } 562 return nullptr; 563 } 564 565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 566 SourceLocation NameLoc, 567 bool IsTemplateTypeArg) { 568 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 569 570 NestedNameSpecifier *NNS = nullptr; 571 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 572 // If we weren't able to parse a default template argument, delay lookup 573 // until instantiation time by making a non-dependent DependentTypeName. We 574 // pretend we saw a NestedNameSpecifier referring to the current scope, and 575 // lookup is retried. 576 // FIXME: This hurts our diagnostic quality, since we get errors like "no 577 // type named 'Foo' in 'current_namespace'" when the user didn't write any 578 // name specifiers. 579 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 580 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 581 } else if (const CXXRecordDecl *RD = 582 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 583 // Build a DependentNameType that will perform lookup into RD at 584 // instantiation time. 585 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 586 RD->getTypeForDecl()); 587 588 // Diagnose that this identifier was undeclared, and retry the lookup during 589 // template instantiation. 590 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 591 << RD; 592 } else { 593 // This is not a situation that we should recover from. 594 return ParsedType(); 595 } 596 597 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 598 599 // Build type location information. We synthesized the qualifier, so we have 600 // to build a fake NestedNameSpecifierLoc. 601 NestedNameSpecifierLocBuilder NNSLocBuilder; 602 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 603 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 604 605 TypeLocBuilder Builder; 606 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 607 DepTL.setNameLoc(NameLoc); 608 DepTL.setElaboratedKeywordLoc(SourceLocation()); 609 DepTL.setQualifierLoc(QualifierLoc); 610 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 611 } 612 613 /// isTagName() - This method is called *for error recovery purposes only* 614 /// to determine if the specified name is a valid tag name ("struct foo"). If 615 /// so, this returns the TST for the tag corresponding to it (TST_enum, 616 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 617 /// cases in C where the user forgot to specify the tag. 618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 619 // Do a tag name lookup in this scope. 620 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 621 LookupName(R, S, false); 622 R.suppressDiagnostics(); 623 if (R.getResultKind() == LookupResult::Found) 624 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 625 switch (TD->getTagKind()) { 626 case TTK_Struct: return DeclSpec::TST_struct; 627 case TTK_Interface: return DeclSpec::TST_interface; 628 case TTK_Union: return DeclSpec::TST_union; 629 case TTK_Class: return DeclSpec::TST_class; 630 case TTK_Enum: return DeclSpec::TST_enum; 631 } 632 } 633 634 return DeclSpec::TST_unspecified; 635 } 636 637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 639 /// then downgrade the missing typename error to a warning. 640 /// This is needed for MSVC compatibility; Example: 641 /// @code 642 /// template<class T> class A { 643 /// public: 644 /// typedef int TYPE; 645 /// }; 646 /// template<class T> class B : public A<T> { 647 /// public: 648 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 649 /// }; 650 /// @endcode 651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 652 if (CurContext->isRecord()) { 653 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 654 return true; 655 656 const Type *Ty = SS->getScopeRep()->getAsType(); 657 658 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 659 for (const auto &Base : RD->bases()) 660 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 661 return true; 662 return S->isFunctionPrototypeScope(); 663 } 664 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 665 } 666 667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 668 SourceLocation IILoc, 669 Scope *S, 670 CXXScopeSpec *SS, 671 ParsedType &SuggestedType, 672 bool IsTemplateName) { 673 // Don't report typename errors for editor placeholders. 674 if (II->isEditorPlaceholder()) 675 return; 676 // We don't have anything to suggest (yet). 677 SuggestedType = nullptr; 678 679 // There may have been a typo in the name of the type. Look up typo 680 // results, in case we have something that we can suggest. 681 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 682 /*AllowTemplates=*/IsTemplateName, 683 /*AllowNonTemplates=*/!IsTemplateName); 684 if (TypoCorrection Corrected = 685 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 686 CCC, CTK_ErrorRecovery)) { 687 // FIXME: Support error recovery for the template-name case. 688 bool CanRecover = !IsTemplateName; 689 if (Corrected.isKeyword()) { 690 // We corrected to a keyword. 691 diagnoseTypo(Corrected, 692 PDiag(IsTemplateName ? diag::err_no_template_suggest 693 : diag::err_unknown_typename_suggest) 694 << II); 695 II = Corrected.getCorrectionAsIdentifierInfo(); 696 } else { 697 // We found a similarly-named type or interface; suggest that. 698 if (!SS || !SS->isSet()) { 699 diagnoseTypo(Corrected, 700 PDiag(IsTemplateName ? diag::err_no_template_suggest 701 : diag::err_unknown_typename_suggest) 702 << II, CanRecover); 703 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 704 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 705 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 706 II->getName().equals(CorrectedStr); 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName 709 ? diag::err_no_member_template_suggest 710 : diag::err_unknown_nested_typename_suggest) 711 << II << DC << DroppedSpecifier << SS->getRange(), 712 CanRecover); 713 } else { 714 llvm_unreachable("could not have corrected a typo here"); 715 } 716 717 if (!CanRecover) 718 return; 719 720 CXXScopeSpec tmpSS; 721 if (Corrected.getCorrectionSpecifier()) 722 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 723 SourceRange(IILoc)); 724 // FIXME: Support class template argument deduction here. 725 SuggestedType = 726 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 727 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 728 /*IsCtorOrDtorName=*/false, 729 /*WantNontrivialTypeSourceInfo=*/true); 730 } 731 return; 732 } 733 734 if (getLangOpts().CPlusPlus && !IsTemplateName) { 735 // See if II is a class template that the user forgot to pass arguments to. 736 UnqualifiedId Name; 737 Name.setIdentifier(II, IILoc); 738 CXXScopeSpec EmptySS; 739 TemplateTy TemplateResult; 740 bool MemberOfUnknownSpecialization; 741 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 742 Name, nullptr, true, TemplateResult, 743 MemberOfUnknownSpecialization) == TNK_Type_template) { 744 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 745 return; 746 } 747 } 748 749 // FIXME: Should we move the logic that tries to recover from a missing tag 750 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 751 752 if (!SS || (!SS->isSet() && !SS->isInvalid())) 753 Diag(IILoc, IsTemplateName ? diag::err_no_template 754 : diag::err_unknown_typename) 755 << II; 756 else if (DeclContext *DC = computeDeclContext(*SS, false)) 757 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 758 : diag::err_typename_nested_not_found) 759 << II << DC << SS->getRange(); 760 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 761 SuggestedType = 762 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 763 } else if (isDependentScopeSpecifier(*SS)) { 764 unsigned DiagID = diag::err_typename_missing; 765 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 766 DiagID = diag::ext_typename_missing; 767 768 Diag(SS->getRange().getBegin(), DiagID) 769 << SS->getScopeRep() << II->getName() 770 << SourceRange(SS->getRange().getBegin(), IILoc) 771 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 772 SuggestedType = ActOnTypenameType(S, SourceLocation(), 773 *SS, *II, IILoc).get(); 774 } else { 775 assert(SS && SS->isInvalid() && 776 "Invalid scope specifier has already been diagnosed"); 777 } 778 } 779 780 /// Determine whether the given result set contains either a type name 781 /// or 782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 783 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 784 NextToken.is(tok::less); 785 786 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 787 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 788 return true; 789 790 if (CheckTemplate && isa<TemplateDecl>(*I)) 791 return true; 792 } 793 794 return false; 795 } 796 797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 798 Scope *S, CXXScopeSpec &SS, 799 IdentifierInfo *&Name, 800 SourceLocation NameLoc) { 801 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 802 SemaRef.LookupParsedName(R, S, &SS); 803 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 804 StringRef FixItTagName; 805 switch (Tag->getTagKind()) { 806 case TTK_Class: 807 FixItTagName = "class "; 808 break; 809 810 case TTK_Enum: 811 FixItTagName = "enum "; 812 break; 813 814 case TTK_Struct: 815 FixItTagName = "struct "; 816 break; 817 818 case TTK_Interface: 819 FixItTagName = "__interface "; 820 break; 821 822 case TTK_Union: 823 FixItTagName = "union "; 824 break; 825 } 826 827 StringRef TagName = FixItTagName.drop_back(); 828 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 829 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 830 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 831 832 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 833 I != IEnd; ++I) 834 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 835 << Name << TagName; 836 837 // Replace lookup results with just the tag decl. 838 Result.clear(Sema::LookupTagName); 839 SemaRef.LookupParsedName(Result, S, &SS); 840 return true; 841 } 842 843 return false; 844 } 845 846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 848 QualType T, SourceLocation NameLoc) { 849 ASTContext &Context = S.Context; 850 851 TypeLocBuilder Builder; 852 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 853 854 T = S.getElaboratedType(ETK_None, SS, T); 855 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 856 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 857 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 858 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 859 } 860 861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 862 IdentifierInfo *&Name, 863 SourceLocation NameLoc, 864 const Token &NextToken, 865 CorrectionCandidateCallback *CCC) { 866 DeclarationNameInfo NameInfo(Name, NameLoc); 867 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 868 869 assert(NextToken.isNot(tok::coloncolon) && 870 "parse nested name specifiers before calling ClassifyName"); 871 if (getLangOpts().CPlusPlus && SS.isSet() && 872 isCurrentClassName(*Name, S, &SS)) { 873 // Per [class.qual]p2, this names the constructors of SS, not the 874 // injected-class-name. We don't have a classification for that. 875 // There's not much point caching this result, since the parser 876 // will reject it later. 877 return NameClassification::Unknown(); 878 } 879 880 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 881 LookupParsedName(Result, S, &SS, !CurMethod); 882 883 if (SS.isInvalid()) 884 return NameClassification::Error(); 885 886 // For unqualified lookup in a class template in MSVC mode, look into 887 // dependent base classes where the primary class template is known. 888 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 889 if (ParsedType TypeInBase = 890 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 891 return TypeInBase; 892 } 893 894 // Perform lookup for Objective-C instance variables (including automatically 895 // synthesized instance variables), if we're in an Objective-C method. 896 // FIXME: This lookup really, really needs to be folded in to the normal 897 // unqualified lookup mechanism. 898 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 899 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 900 if (Ivar.isInvalid()) 901 return NameClassification::Error(); 902 if (Ivar.isUsable()) 903 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 904 905 // We defer builtin creation until after ivar lookup inside ObjC methods. 906 if (Result.empty()) 907 LookupBuiltin(Result); 908 } 909 910 bool SecondTry = false; 911 bool IsFilteredTemplateName = false; 912 913 Corrected: 914 switch (Result.getResultKind()) { 915 case LookupResult::NotFound: 916 // If an unqualified-id is followed by a '(', then we have a function 917 // call. 918 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 919 // In C++, this is an ADL-only call. 920 // FIXME: Reference? 921 if (getLangOpts().CPlusPlus) 922 return NameClassification::UndeclaredNonType(); 923 924 // C90 6.3.2.2: 925 // If the expression that precedes the parenthesized argument list in a 926 // function call consists solely of an identifier, and if no 927 // declaration is visible for this identifier, the identifier is 928 // implicitly declared exactly as if, in the innermost block containing 929 // the function call, the declaration 930 // 931 // extern int identifier (); 932 // 933 // appeared. 934 // 935 // We also allow this in C99 as an extension. 936 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 937 return NameClassification::NonType(D); 938 } 939 940 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 941 // In C++20 onwards, this could be an ADL-only call to a function 942 // template, and we're required to assume that this is a template name. 943 // 944 // FIXME: Find a way to still do typo correction in this case. 945 TemplateName Template = 946 Context.getAssumedTemplateName(NameInfo.getName()); 947 return NameClassification::UndeclaredTemplate(Template); 948 } 949 950 // In C, we first see whether there is a tag type by the same name, in 951 // which case it's likely that the user just forgot to write "enum", 952 // "struct", or "union". 953 if (!getLangOpts().CPlusPlus && !SecondTry && 954 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 955 break; 956 } 957 958 // Perform typo correction to determine if there is another name that is 959 // close to this name. 960 if (!SecondTry && CCC) { 961 SecondTry = true; 962 if (TypoCorrection Corrected = 963 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 964 &SS, *CCC, CTK_ErrorRecovery)) { 965 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 966 unsigned QualifiedDiag = diag::err_no_member_suggest; 967 968 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 969 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 970 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 971 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 972 UnqualifiedDiag = diag::err_no_template_suggest; 973 QualifiedDiag = diag::err_no_member_template_suggest; 974 } else if (UnderlyingFirstDecl && 975 (isa<TypeDecl>(UnderlyingFirstDecl) || 976 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 977 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 978 UnqualifiedDiag = diag::err_unknown_typename_suggest; 979 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 980 } 981 982 if (SS.isEmpty()) { 983 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 984 } else {// FIXME: is this even reachable? Test it. 985 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 986 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 987 Name->getName().equals(CorrectedStr); 988 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 989 << Name << computeDeclContext(SS, false) 990 << DroppedSpecifier << SS.getRange()); 991 } 992 993 // Update the name, so that the caller has the new name. 994 Name = Corrected.getCorrectionAsIdentifierInfo(); 995 996 // Typo correction corrected to a keyword. 997 if (Corrected.isKeyword()) 998 return Name; 999 1000 // Also update the LookupResult... 1001 // FIXME: This should probably go away at some point 1002 Result.clear(); 1003 Result.setLookupName(Corrected.getCorrection()); 1004 if (FirstDecl) 1005 Result.addDecl(FirstDecl); 1006 1007 // If we found an Objective-C instance variable, let 1008 // LookupInObjCMethod build the appropriate expression to 1009 // reference the ivar. 1010 // FIXME: This is a gross hack. 1011 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1012 DeclResult R = 1013 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1014 if (R.isInvalid()) 1015 return NameClassification::Error(); 1016 if (R.isUsable()) 1017 return NameClassification::NonType(Ivar); 1018 } 1019 1020 goto Corrected; 1021 } 1022 } 1023 1024 // We failed to correct; just fall through and let the parser deal with it. 1025 Result.suppressDiagnostics(); 1026 return NameClassification::Unknown(); 1027 1028 case LookupResult::NotFoundInCurrentInstantiation: { 1029 // We performed name lookup into the current instantiation, and there were 1030 // dependent bases, so we treat this result the same way as any other 1031 // dependent nested-name-specifier. 1032 1033 // C++ [temp.res]p2: 1034 // A name used in a template declaration or definition and that is 1035 // dependent on a template-parameter is assumed not to name a type 1036 // unless the applicable name lookup finds a type name or the name is 1037 // qualified by the keyword typename. 1038 // 1039 // FIXME: If the next token is '<', we might want to ask the parser to 1040 // perform some heroics to see if we actually have a 1041 // template-argument-list, which would indicate a missing 'template' 1042 // keyword here. 1043 return NameClassification::DependentNonType(); 1044 } 1045 1046 case LookupResult::Found: 1047 case LookupResult::FoundOverloaded: 1048 case LookupResult::FoundUnresolvedValue: 1049 break; 1050 1051 case LookupResult::Ambiguous: 1052 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1053 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1054 /*AllowDependent=*/false)) { 1055 // C++ [temp.local]p3: 1056 // A lookup that finds an injected-class-name (10.2) can result in an 1057 // ambiguity in certain cases (for example, if it is found in more than 1058 // one base class). If all of the injected-class-names that are found 1059 // refer to specializations of the same class template, and if the name 1060 // is followed by a template-argument-list, the reference refers to the 1061 // class template itself and not a specialization thereof, and is not 1062 // ambiguous. 1063 // 1064 // This filtering can make an ambiguous result into an unambiguous one, 1065 // so try again after filtering out template names. 1066 FilterAcceptableTemplateNames(Result); 1067 if (!Result.isAmbiguous()) { 1068 IsFilteredTemplateName = true; 1069 break; 1070 } 1071 } 1072 1073 // Diagnose the ambiguity and return an error. 1074 return NameClassification::Error(); 1075 } 1076 1077 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1078 (IsFilteredTemplateName || 1079 hasAnyAcceptableTemplateNames( 1080 Result, /*AllowFunctionTemplates=*/true, 1081 /*AllowDependent=*/false, 1082 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1083 getLangOpts().CPlusPlus20))) { 1084 // C++ [temp.names]p3: 1085 // After name lookup (3.4) finds that a name is a template-name or that 1086 // an operator-function-id or a literal- operator-id refers to a set of 1087 // overloaded functions any member of which is a function template if 1088 // this is followed by a <, the < is always taken as the delimiter of a 1089 // template-argument-list and never as the less-than operator. 1090 // C++2a [temp.names]p2: 1091 // A name is also considered to refer to a template if it is an 1092 // unqualified-id followed by a < and name lookup finds either one 1093 // or more functions or finds nothing. 1094 if (!IsFilteredTemplateName) 1095 FilterAcceptableTemplateNames(Result); 1096 1097 bool IsFunctionTemplate; 1098 bool IsVarTemplate; 1099 TemplateName Template; 1100 if (Result.end() - Result.begin() > 1) { 1101 IsFunctionTemplate = true; 1102 Template = Context.getOverloadedTemplateName(Result.begin(), 1103 Result.end()); 1104 } else if (!Result.empty()) { 1105 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1106 *Result.begin(), /*AllowFunctionTemplates=*/true, 1107 /*AllowDependent=*/false)); 1108 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1109 IsVarTemplate = isa<VarTemplateDecl>(TD); 1110 1111 if (SS.isNotEmpty()) 1112 Template = 1113 Context.getQualifiedTemplateName(SS.getScopeRep(), 1114 /*TemplateKeyword=*/false, TD); 1115 else 1116 Template = TemplateName(TD); 1117 } else { 1118 // All results were non-template functions. This is a function template 1119 // name. 1120 IsFunctionTemplate = true; 1121 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1122 } 1123 1124 if (IsFunctionTemplate) { 1125 // Function templates always go through overload resolution, at which 1126 // point we'll perform the various checks (e.g., accessibility) we need 1127 // to based on which function we selected. 1128 Result.suppressDiagnostics(); 1129 1130 return NameClassification::FunctionTemplate(Template); 1131 } 1132 1133 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1134 : NameClassification::TypeTemplate(Template); 1135 } 1136 1137 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1138 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1139 DiagnoseUseOfDecl(Type, NameLoc); 1140 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1141 QualType T = Context.getTypeDeclType(Type); 1142 if (SS.isNotEmpty()) 1143 return buildNestedType(*this, SS, T, NameLoc); 1144 return ParsedType::make(T); 1145 } 1146 1147 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1148 if (!Class) { 1149 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1150 if (ObjCCompatibleAliasDecl *Alias = 1151 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1152 Class = Alias->getClassInterface(); 1153 } 1154 1155 if (Class) { 1156 DiagnoseUseOfDecl(Class, NameLoc); 1157 1158 if (NextToken.is(tok::period)) { 1159 // Interface. <something> is parsed as a property reference expression. 1160 // Just return "unknown" as a fall-through for now. 1161 Result.suppressDiagnostics(); 1162 return NameClassification::Unknown(); 1163 } 1164 1165 QualType T = Context.getObjCInterfaceType(Class); 1166 return ParsedType::make(T); 1167 } 1168 1169 if (isa<ConceptDecl>(FirstDecl)) 1170 return NameClassification::Concept( 1171 TemplateName(cast<TemplateDecl>(FirstDecl))); 1172 1173 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1174 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1175 return NameClassification::Error(); 1176 } 1177 1178 // We can have a type template here if we're classifying a template argument. 1179 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1180 !isa<VarTemplateDecl>(FirstDecl)) 1181 return NameClassification::TypeTemplate( 1182 TemplateName(cast<TemplateDecl>(FirstDecl))); 1183 1184 // Check for a tag type hidden by a non-type decl in a few cases where it 1185 // seems likely a type is wanted instead of the non-type that was found. 1186 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1187 if ((NextToken.is(tok::identifier) || 1188 (NextIsOp && 1189 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1190 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1191 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1192 DiagnoseUseOfDecl(Type, NameLoc); 1193 QualType T = Context.getTypeDeclType(Type); 1194 if (SS.isNotEmpty()) 1195 return buildNestedType(*this, SS, T, NameLoc); 1196 return ParsedType::make(T); 1197 } 1198 1199 // If we already know which single declaration is referenced, just annotate 1200 // that declaration directly. Defer resolving even non-overloaded class 1201 // member accesses, as we need to defer certain access checks until we know 1202 // the context. 1203 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1204 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1205 return NameClassification::NonType(Result.getRepresentativeDecl()); 1206 1207 // Otherwise, this is an overload set that we will need to resolve later. 1208 Result.suppressDiagnostics(); 1209 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1210 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1211 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1212 Result.begin(), Result.end())); 1213 } 1214 1215 ExprResult 1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1217 SourceLocation NameLoc) { 1218 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1219 CXXScopeSpec SS; 1220 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1221 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1222 } 1223 1224 ExprResult 1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1226 IdentifierInfo *Name, 1227 SourceLocation NameLoc, 1228 bool IsAddressOfOperand) { 1229 DeclarationNameInfo NameInfo(Name, NameLoc); 1230 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1231 NameInfo, IsAddressOfOperand, 1232 /*TemplateArgs=*/nullptr); 1233 } 1234 1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1236 NamedDecl *Found, 1237 SourceLocation NameLoc, 1238 const Token &NextToken) { 1239 if (getCurMethodDecl() && SS.isEmpty()) 1240 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1241 return BuildIvarRefExpr(S, NameLoc, Ivar); 1242 1243 // Reconstruct the lookup result. 1244 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1245 Result.addDecl(Found); 1246 Result.resolveKind(); 1247 1248 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1249 return BuildDeclarationNameExpr(SS, Result, ADL); 1250 } 1251 1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1253 // For an implicit class member access, transform the result into a member 1254 // access expression if necessary. 1255 auto *ULE = cast<UnresolvedLookupExpr>(E); 1256 if ((*ULE->decls_begin())->isCXXClassMember()) { 1257 CXXScopeSpec SS; 1258 SS.Adopt(ULE->getQualifierLoc()); 1259 1260 // Reconstruct the lookup result. 1261 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1262 LookupOrdinaryName); 1263 Result.setNamingClass(ULE->getNamingClass()); 1264 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1265 Result.addDecl(*I, I.getAccess()); 1266 Result.resolveKind(); 1267 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1268 nullptr, S); 1269 } 1270 1271 // Otherwise, this is already in the form we needed, and no further checks 1272 // are necessary. 1273 return ULE; 1274 } 1275 1276 Sema::TemplateNameKindForDiagnostics 1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1278 auto *TD = Name.getAsTemplateDecl(); 1279 if (!TD) 1280 return TemplateNameKindForDiagnostics::DependentTemplate; 1281 if (isa<ClassTemplateDecl>(TD)) 1282 return TemplateNameKindForDiagnostics::ClassTemplate; 1283 if (isa<FunctionTemplateDecl>(TD)) 1284 return TemplateNameKindForDiagnostics::FunctionTemplate; 1285 if (isa<VarTemplateDecl>(TD)) 1286 return TemplateNameKindForDiagnostics::VarTemplate; 1287 if (isa<TypeAliasTemplateDecl>(TD)) 1288 return TemplateNameKindForDiagnostics::AliasTemplate; 1289 if (isa<TemplateTemplateParmDecl>(TD)) 1290 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1291 if (isa<ConceptDecl>(TD)) 1292 return TemplateNameKindForDiagnostics::Concept; 1293 return TemplateNameKindForDiagnostics::DependentTemplate; 1294 } 1295 1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1297 assert(DC->getLexicalParent() == CurContext && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = DC; 1300 S->setEntity(DC); 1301 } 1302 1303 void Sema::PopDeclContext() { 1304 assert(CurContext && "DeclContext imbalance!"); 1305 1306 CurContext = CurContext->getLexicalParent(); 1307 assert(CurContext && "Popped translation unit!"); 1308 } 1309 1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1311 Decl *D) { 1312 // Unlike PushDeclContext, the context to which we return is not necessarily 1313 // the containing DC of TD, because the new context will be some pre-existing 1314 // TagDecl definition instead of a fresh one. 1315 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1316 CurContext = cast<TagDecl>(D)->getDefinition(); 1317 assert(CurContext && "skipping definition of undefined tag"); 1318 // Start lookups from the parent of the current context; we don't want to look 1319 // into the pre-existing complete definition. 1320 S->setEntity(CurContext->getLookupParent()); 1321 return Result; 1322 } 1323 1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1325 CurContext = static_cast<decltype(CurContext)>(Context); 1326 } 1327 1328 /// EnterDeclaratorContext - Used when we must lookup names in the context 1329 /// of a declarator's nested name specifier. 1330 /// 1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1332 // C++0x [basic.lookup.unqual]p13: 1333 // A name used in the definition of a static data member of class 1334 // X (after the qualified-id of the static member) is looked up as 1335 // if the name was used in a member function of X. 1336 // C++0x [basic.lookup.unqual]p14: 1337 // If a variable member of a namespace is defined outside of the 1338 // scope of its namespace then any name used in the definition of 1339 // the variable member (after the declarator-id) is looked up as 1340 // if the definition of the variable member occurred in its 1341 // namespace. 1342 // Both of these imply that we should push a scope whose context 1343 // is the semantic context of the declaration. We can't use 1344 // PushDeclContext here because that context is not necessarily 1345 // lexically contained in the current context. Fortunately, 1346 // the containing scope should have the appropriate information. 1347 1348 assert(!S->getEntity() && "scope already has entity"); 1349 1350 #ifndef NDEBUG 1351 Scope *Ancestor = S->getParent(); 1352 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1353 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1354 #endif 1355 1356 CurContext = DC; 1357 S->setEntity(DC); 1358 1359 if (S->getParent()->isTemplateParamScope()) { 1360 // Also set the corresponding entities for all immediately-enclosing 1361 // template parameter scopes. 1362 EnterTemplatedContext(S->getParent(), DC); 1363 } 1364 } 1365 1366 void Sema::ExitDeclaratorContext(Scope *S) { 1367 assert(S->getEntity() == CurContext && "Context imbalance!"); 1368 1369 // Switch back to the lexical context. The safety of this is 1370 // enforced by an assert in EnterDeclaratorContext. 1371 Scope *Ancestor = S->getParent(); 1372 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1373 CurContext = Ancestor->getEntity(); 1374 1375 // We don't need to do anything with the scope, which is going to 1376 // disappear. 1377 } 1378 1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1380 assert(S->isTemplateParamScope() && 1381 "expected to be initializing a template parameter scope"); 1382 1383 // C++20 [temp.local]p7: 1384 // In the definition of a member of a class template that appears outside 1385 // of the class template definition, the name of a member of the class 1386 // template hides the name of a template-parameter of any enclosing class 1387 // templates (but not a template-parameter of the member if the member is a 1388 // class or function template). 1389 // C++20 [temp.local]p9: 1390 // In the definition of a class template or in the definition of a member 1391 // of such a template that appears outside of the template definition, for 1392 // each non-dependent base class (13.8.2.1), if the name of the base class 1393 // or the name of a member of the base class is the same as the name of a 1394 // template-parameter, the base class name or member name hides the 1395 // template-parameter name (6.4.10). 1396 // 1397 // This means that a template parameter scope should be searched immediately 1398 // after searching the DeclContext for which it is a template parameter 1399 // scope. For example, for 1400 // template<typename T> template<typename U> template<typename V> 1401 // void N::A<T>::B<U>::f(...) 1402 // we search V then B<U> (and base classes) then U then A<T> (and base 1403 // classes) then T then N then ::. 1404 unsigned ScopeDepth = getTemplateDepth(S); 1405 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1406 DeclContext *SearchDCAfterScope = DC; 1407 for (; DC; DC = DC->getLookupParent()) { 1408 if (const TemplateParameterList *TPL = 1409 cast<Decl>(DC)->getDescribedTemplateParams()) { 1410 unsigned DCDepth = TPL->getDepth() + 1; 1411 if (DCDepth > ScopeDepth) 1412 continue; 1413 if (ScopeDepth == DCDepth) 1414 SearchDCAfterScope = DC = DC->getLookupParent(); 1415 break; 1416 } 1417 } 1418 S->setLookupEntity(SearchDCAfterScope); 1419 } 1420 } 1421 1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1423 // We assume that the caller has already called 1424 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1425 FunctionDecl *FD = D->getAsFunction(); 1426 if (!FD) 1427 return; 1428 1429 // Same implementation as PushDeclContext, but enters the context 1430 // from the lexical parent, rather than the top-level class. 1431 assert(CurContext == FD->getLexicalParent() && 1432 "The next DeclContext should be lexically contained in the current one."); 1433 CurContext = FD; 1434 S->setEntity(CurContext); 1435 1436 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1437 ParmVarDecl *Param = FD->getParamDecl(P); 1438 // If the parameter has an identifier, then add it to the scope 1439 if (Param->getIdentifier()) { 1440 S->AddDecl(Param); 1441 IdResolver.AddDecl(Param); 1442 } 1443 } 1444 } 1445 1446 void Sema::ActOnExitFunctionContext() { 1447 // Same implementation as PopDeclContext, but returns to the lexical parent, 1448 // rather than the top-level class. 1449 assert(CurContext && "DeclContext imbalance!"); 1450 CurContext = CurContext->getLexicalParent(); 1451 assert(CurContext && "Popped translation unit!"); 1452 } 1453 1454 /// Determine whether we allow overloading of the function 1455 /// PrevDecl with another declaration. 1456 /// 1457 /// This routine determines whether overloading is possible, not 1458 /// whether some new function is actually an overload. It will return 1459 /// true in C++ (where we can always provide overloads) or, as an 1460 /// extension, in C when the previous function is already an 1461 /// overloaded function declaration or has the "overloadable" 1462 /// attribute. 1463 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1464 ASTContext &Context, 1465 const FunctionDecl *New) { 1466 if (Context.getLangOpts().CPlusPlus) 1467 return true; 1468 1469 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1470 return true; 1471 1472 return Previous.getResultKind() == LookupResult::Found && 1473 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1474 New->hasAttr<OverloadableAttr>()); 1475 } 1476 1477 /// Add this decl to the scope shadowed decl chains. 1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1479 // Move up the scope chain until we find the nearest enclosing 1480 // non-transparent context. The declaration will be introduced into this 1481 // scope. 1482 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1483 S = S->getParent(); 1484 1485 // Add scoped declarations into their context, so that they can be 1486 // found later. Declarations without a context won't be inserted 1487 // into any context. 1488 if (AddToContext) 1489 CurContext->addDecl(D); 1490 1491 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1492 // are function-local declarations. 1493 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1494 return; 1495 1496 // Template instantiations should also not be pushed into scope. 1497 if (isa<FunctionDecl>(D) && 1498 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1499 return; 1500 1501 // If this replaces anything in the current scope, 1502 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1503 IEnd = IdResolver.end(); 1504 for (; I != IEnd; ++I) { 1505 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1506 S->RemoveDecl(*I); 1507 IdResolver.RemoveDecl(*I); 1508 1509 // Should only need to replace one decl. 1510 break; 1511 } 1512 } 1513 1514 S->AddDecl(D); 1515 1516 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1517 // Implicitly-generated labels may end up getting generated in an order that 1518 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1519 // the label at the appropriate place in the identifier chain. 1520 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1521 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1522 if (IDC == CurContext) { 1523 if (!S->isDeclScope(*I)) 1524 continue; 1525 } else if (IDC->Encloses(CurContext)) 1526 break; 1527 } 1528 1529 IdResolver.InsertDeclAfter(I, D); 1530 } else { 1531 IdResolver.AddDecl(D); 1532 } 1533 warnOnReservedIdentifier(D); 1534 } 1535 1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1537 bool AllowInlineNamespace) { 1538 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1539 } 1540 1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1542 DeclContext *TargetDC = DC->getPrimaryContext(); 1543 do { 1544 if (DeclContext *ScopeDC = S->getEntity()) 1545 if (ScopeDC->getPrimaryContext() == TargetDC) 1546 return S; 1547 } while ((S = S->getParent())); 1548 1549 return nullptr; 1550 } 1551 1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1553 DeclContext*, 1554 ASTContext&); 1555 1556 /// Filters out lookup results that don't fall within the given scope 1557 /// as determined by isDeclInScope. 1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1559 bool ConsiderLinkage, 1560 bool AllowInlineNamespace) { 1561 LookupResult::Filter F = R.makeFilter(); 1562 while (F.hasNext()) { 1563 NamedDecl *D = F.next(); 1564 1565 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1566 continue; 1567 1568 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1569 continue; 1570 1571 F.erase(); 1572 } 1573 1574 F.done(); 1575 } 1576 1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1578 /// have compatible owning modules. 1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1580 // FIXME: The Modules TS is not clear about how friend declarations are 1581 // to be treated. It's not meaningful to have different owning modules for 1582 // linkage in redeclarations of the same entity, so for now allow the 1583 // redeclaration and change the owning modules to match. 1584 if (New->getFriendObjectKind() && 1585 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1586 New->setLocalOwningModule(Old->getOwningModule()); 1587 makeMergedDefinitionVisible(New); 1588 return false; 1589 } 1590 1591 Module *NewM = New->getOwningModule(); 1592 Module *OldM = Old->getOwningModule(); 1593 1594 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1595 NewM = NewM->Parent; 1596 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1597 OldM = OldM->Parent; 1598 1599 if (NewM == OldM) 1600 return false; 1601 1602 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1603 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1604 if (NewIsModuleInterface || OldIsModuleInterface) { 1605 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1606 // if a declaration of D [...] appears in the purview of a module, all 1607 // other such declarations shall appear in the purview of the same module 1608 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1609 << New 1610 << NewIsModuleInterface 1611 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1612 << OldIsModuleInterface 1613 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1614 Diag(Old->getLocation(), diag::note_previous_declaration); 1615 New->setInvalidDecl(); 1616 return true; 1617 } 1618 1619 return false; 1620 } 1621 1622 static bool isUsingDecl(NamedDecl *D) { 1623 return isa<UsingShadowDecl>(D) || 1624 isa<UnresolvedUsingTypenameDecl>(D) || 1625 isa<UnresolvedUsingValueDecl>(D); 1626 } 1627 1628 /// Removes using shadow declarations from the lookup results. 1629 static void RemoveUsingDecls(LookupResult &R) { 1630 LookupResult::Filter F = R.makeFilter(); 1631 while (F.hasNext()) 1632 if (isUsingDecl(F.next())) 1633 F.erase(); 1634 1635 F.done(); 1636 } 1637 1638 /// Check for this common pattern: 1639 /// @code 1640 /// class S { 1641 /// S(const S&); // DO NOT IMPLEMENT 1642 /// void operator=(const S&); // DO NOT IMPLEMENT 1643 /// }; 1644 /// @endcode 1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1646 // FIXME: Should check for private access too but access is set after we get 1647 // the decl here. 1648 if (D->doesThisDeclarationHaveABody()) 1649 return false; 1650 1651 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1652 return CD->isCopyConstructor(); 1653 return D->isCopyAssignmentOperator(); 1654 } 1655 1656 // We need this to handle 1657 // 1658 // typedef struct { 1659 // void *foo() { return 0; } 1660 // } A; 1661 // 1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1663 // for example. If 'A', foo will have external linkage. If we have '*A', 1664 // foo will have no linkage. Since we can't know until we get to the end 1665 // of the typedef, this function finds out if D might have non-external linkage. 1666 // Callers should verify at the end of the TU if it D has external linkage or 1667 // not. 1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1669 const DeclContext *DC = D->getDeclContext(); 1670 while (!DC->isTranslationUnit()) { 1671 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1672 if (!RD->hasNameForLinkage()) 1673 return true; 1674 } 1675 DC = DC->getParent(); 1676 } 1677 1678 return !D->isExternallyVisible(); 1679 } 1680 1681 // FIXME: This needs to be refactored; some other isInMainFile users want 1682 // these semantics. 1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1684 if (S.TUKind != TU_Complete) 1685 return false; 1686 return S.SourceMgr.isInMainFile(Loc); 1687 } 1688 1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1690 assert(D); 1691 1692 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1693 return false; 1694 1695 // Ignore all entities declared within templates, and out-of-line definitions 1696 // of members of class templates. 1697 if (D->getDeclContext()->isDependentContext() || 1698 D->getLexicalDeclContext()->isDependentContext()) 1699 return false; 1700 1701 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1702 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1703 return false; 1704 // A non-out-of-line declaration of a member specialization was implicitly 1705 // instantiated; it's the out-of-line declaration that we're interested in. 1706 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1707 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1708 return false; 1709 1710 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1711 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1712 return false; 1713 } else { 1714 // 'static inline' functions are defined in headers; don't warn. 1715 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1716 return false; 1717 } 1718 1719 if (FD->doesThisDeclarationHaveABody() && 1720 Context.DeclMustBeEmitted(FD)) 1721 return false; 1722 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1723 // Constants and utility variables are defined in headers with internal 1724 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1725 // like "inline".) 1726 if (!isMainFileLoc(*this, VD->getLocation())) 1727 return false; 1728 1729 if (Context.DeclMustBeEmitted(VD)) 1730 return false; 1731 1732 if (VD->isStaticDataMember() && 1733 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1734 return false; 1735 if (VD->isStaticDataMember() && 1736 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1737 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1738 return false; 1739 1740 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1741 return false; 1742 } else { 1743 return false; 1744 } 1745 1746 // Only warn for unused decls internal to the translation unit. 1747 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1748 // for inline functions defined in the main source file, for instance. 1749 return mightHaveNonExternalLinkage(D); 1750 } 1751 1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1753 if (!D) 1754 return; 1755 1756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1757 const FunctionDecl *First = FD->getFirstDecl(); 1758 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1759 return; // First should already be in the vector. 1760 } 1761 1762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1763 const VarDecl *First = VD->getFirstDecl(); 1764 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1765 return; // First should already be in the vector. 1766 } 1767 1768 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1769 UnusedFileScopedDecls.push_back(D); 1770 } 1771 1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1773 if (D->isInvalidDecl()) 1774 return false; 1775 1776 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1777 // For a decomposition declaration, warn if none of the bindings are 1778 // referenced, instead of if the variable itself is referenced (which 1779 // it is, by the bindings' expressions). 1780 for (auto *BD : DD->bindings()) 1781 if (BD->isReferenced()) 1782 return false; 1783 } else if (!D->getDeclName()) { 1784 return false; 1785 } else if (D->isReferenced() || D->isUsed()) { 1786 return false; 1787 } 1788 1789 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1790 return false; 1791 1792 if (isa<LabelDecl>(D)) 1793 return true; 1794 1795 // Except for labels, we only care about unused decls that are local to 1796 // functions. 1797 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1798 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1799 // For dependent types, the diagnostic is deferred. 1800 WithinFunction = 1801 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1802 if (!WithinFunction) 1803 return false; 1804 1805 if (isa<TypedefNameDecl>(D)) 1806 return true; 1807 1808 // White-list anything that isn't a local variable. 1809 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1810 return false; 1811 1812 // Types of valid local variables should be complete, so this should succeed. 1813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1814 1815 // White-list anything with an __attribute__((unused)) type. 1816 const auto *Ty = VD->getType().getTypePtr(); 1817 1818 // Only look at the outermost level of typedef. 1819 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1820 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1821 return false; 1822 } 1823 1824 // If we failed to complete the type for some reason, or if the type is 1825 // dependent, don't diagnose the variable. 1826 if (Ty->isIncompleteType() || Ty->isDependentType()) 1827 return false; 1828 1829 // Look at the element type to ensure that the warning behaviour is 1830 // consistent for both scalars and arrays. 1831 Ty = Ty->getBaseElementTypeUnsafe(); 1832 1833 if (const TagType *TT = Ty->getAs<TagType>()) { 1834 const TagDecl *Tag = TT->getDecl(); 1835 if (Tag->hasAttr<UnusedAttr>()) 1836 return false; 1837 1838 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1839 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1840 return false; 1841 1842 if (const Expr *Init = VD->getInit()) { 1843 if (const ExprWithCleanups *Cleanups = 1844 dyn_cast<ExprWithCleanups>(Init)) 1845 Init = Cleanups->getSubExpr(); 1846 const CXXConstructExpr *Construct = 1847 dyn_cast<CXXConstructExpr>(Init); 1848 if (Construct && !Construct->isElidable()) { 1849 CXXConstructorDecl *CD = Construct->getConstructor(); 1850 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1851 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1852 return false; 1853 } 1854 1855 // Suppress the warning if we don't know how this is constructed, and 1856 // it could possibly be non-trivial constructor. 1857 if (Init->isTypeDependent()) 1858 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1859 if (!Ctor->isTrivial()) 1860 return false; 1861 } 1862 } 1863 } 1864 1865 // TODO: __attribute__((unused)) templates? 1866 } 1867 1868 return true; 1869 } 1870 1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1872 FixItHint &Hint) { 1873 if (isa<LabelDecl>(D)) { 1874 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1875 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1876 true); 1877 if (AfterColon.isInvalid()) 1878 return; 1879 Hint = FixItHint::CreateRemoval( 1880 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1881 } 1882 } 1883 1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1885 if (D->getTypeForDecl()->isDependentType()) 1886 return; 1887 1888 for (auto *TmpD : D->decls()) { 1889 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1890 DiagnoseUnusedDecl(T); 1891 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1892 DiagnoseUnusedNestedTypedefs(R); 1893 } 1894 } 1895 1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1897 /// unless they are marked attr(unused). 1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1899 if (!ShouldDiagnoseUnusedDecl(D)) 1900 return; 1901 1902 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1903 // typedefs can be referenced later on, so the diagnostics are emitted 1904 // at end-of-translation-unit. 1905 UnusedLocalTypedefNameCandidates.insert(TD); 1906 return; 1907 } 1908 1909 FixItHint Hint; 1910 GenerateFixForUnusedDecl(D, Context, Hint); 1911 1912 unsigned DiagID; 1913 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1914 DiagID = diag::warn_unused_exception_param; 1915 else if (isa<LabelDecl>(D)) 1916 DiagID = diag::warn_unused_label; 1917 else 1918 DiagID = diag::warn_unused_variable; 1919 1920 Diag(D->getLocation(), DiagID) << D << Hint; 1921 } 1922 1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1924 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 1925 // it's not really unused. 1926 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 1927 VD->hasAttr<CleanupAttr>()) 1928 return; 1929 1930 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1931 1932 if (Ty->isReferenceType() || Ty->isDependentType()) 1933 return; 1934 1935 if (const TagType *TT = Ty->getAs<TagType>()) { 1936 const TagDecl *Tag = TT->getDecl(); 1937 if (Tag->hasAttr<UnusedAttr>()) 1938 return; 1939 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1940 // mimic gcc's behavior. 1941 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1942 if (!RD->hasAttr<WarnUnusedAttr>()) 1943 return; 1944 } 1945 } 1946 1947 // Don't warn about __block Objective-C pointer variables, as they might 1948 // be assigned in the block but not used elsewhere for the purpose of lifetime 1949 // extension. 1950 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 1951 return; 1952 1953 auto iter = RefsMinusAssignments.find(VD); 1954 if (iter == RefsMinusAssignments.end()) 1955 return; 1956 1957 assert(iter->getSecond() >= 0 && 1958 "Found a negative number of references to a VarDecl"); 1959 if (iter->getSecond() != 0) 1960 return; 1961 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 1962 : diag::warn_unused_but_set_variable; 1963 Diag(VD->getLocation(), DiagID) << VD; 1964 } 1965 1966 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1967 // Verify that we have no forward references left. If so, there was a goto 1968 // or address of a label taken, but no definition of it. Label fwd 1969 // definitions are indicated with a null substmt which is also not a resolved 1970 // MS inline assembly label name. 1971 bool Diagnose = false; 1972 if (L->isMSAsmLabel()) 1973 Diagnose = !L->isResolvedMSAsmLabel(); 1974 else 1975 Diagnose = L->getStmt() == nullptr; 1976 if (Diagnose) 1977 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1978 } 1979 1980 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1981 S->mergeNRVOIntoParent(); 1982 1983 if (S->decl_empty()) return; 1984 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1985 "Scope shouldn't contain decls!"); 1986 1987 for (auto *TmpD : S->decls()) { 1988 assert(TmpD && "This decl didn't get pushed??"); 1989 1990 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1991 NamedDecl *D = cast<NamedDecl>(TmpD); 1992 1993 // Diagnose unused variables in this scope. 1994 if (!S->hasUnrecoverableErrorOccurred()) { 1995 DiagnoseUnusedDecl(D); 1996 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1997 DiagnoseUnusedNestedTypedefs(RD); 1998 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1999 DiagnoseUnusedButSetDecl(VD); 2000 RefsMinusAssignments.erase(VD); 2001 } 2002 } 2003 2004 if (!D->getDeclName()) continue; 2005 2006 // If this was a forward reference to a label, verify it was defined. 2007 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2008 CheckPoppedLabel(LD, *this); 2009 2010 // Remove this name from our lexical scope, and warn on it if we haven't 2011 // already. 2012 IdResolver.RemoveDecl(D); 2013 auto ShadowI = ShadowingDecls.find(D); 2014 if (ShadowI != ShadowingDecls.end()) { 2015 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2016 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2017 << D << FD << FD->getParent(); 2018 Diag(FD->getLocation(), diag::note_previous_declaration); 2019 } 2020 ShadowingDecls.erase(ShadowI); 2021 } 2022 } 2023 } 2024 2025 /// Look for an Objective-C class in the translation unit. 2026 /// 2027 /// \param Id The name of the Objective-C class we're looking for. If 2028 /// typo-correction fixes this name, the Id will be updated 2029 /// to the fixed name. 2030 /// 2031 /// \param IdLoc The location of the name in the translation unit. 2032 /// 2033 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2034 /// if there is no class with the given name. 2035 /// 2036 /// \returns The declaration of the named Objective-C class, or NULL if the 2037 /// class could not be found. 2038 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2039 SourceLocation IdLoc, 2040 bool DoTypoCorrection) { 2041 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2042 // creation from this context. 2043 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2044 2045 if (!IDecl && DoTypoCorrection) { 2046 // Perform typo correction at the given location, but only if we 2047 // find an Objective-C class name. 2048 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2049 if (TypoCorrection C = 2050 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2051 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2052 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2053 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2054 Id = IDecl->getIdentifier(); 2055 } 2056 } 2057 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2058 // This routine must always return a class definition, if any. 2059 if (Def && Def->getDefinition()) 2060 Def = Def->getDefinition(); 2061 return Def; 2062 } 2063 2064 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2065 /// from S, where a non-field would be declared. This routine copes 2066 /// with the difference between C and C++ scoping rules in structs and 2067 /// unions. For example, the following code is well-formed in C but 2068 /// ill-formed in C++: 2069 /// @code 2070 /// struct S6 { 2071 /// enum { BAR } e; 2072 /// }; 2073 /// 2074 /// void test_S6() { 2075 /// struct S6 a; 2076 /// a.e = BAR; 2077 /// } 2078 /// @endcode 2079 /// For the declaration of BAR, this routine will return a different 2080 /// scope. The scope S will be the scope of the unnamed enumeration 2081 /// within S6. In C++, this routine will return the scope associated 2082 /// with S6, because the enumeration's scope is a transparent 2083 /// context but structures can contain non-field names. In C, this 2084 /// routine will return the translation unit scope, since the 2085 /// enumeration's scope is a transparent context and structures cannot 2086 /// contain non-field names. 2087 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2088 while (((S->getFlags() & Scope::DeclScope) == 0) || 2089 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2090 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2091 S = S->getParent(); 2092 return S; 2093 } 2094 2095 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2096 ASTContext::GetBuiltinTypeError Error) { 2097 switch (Error) { 2098 case ASTContext::GE_None: 2099 return ""; 2100 case ASTContext::GE_Missing_type: 2101 return BuiltinInfo.getHeaderName(ID); 2102 case ASTContext::GE_Missing_stdio: 2103 return "stdio.h"; 2104 case ASTContext::GE_Missing_setjmp: 2105 return "setjmp.h"; 2106 case ASTContext::GE_Missing_ucontext: 2107 return "ucontext.h"; 2108 } 2109 llvm_unreachable("unhandled error kind"); 2110 } 2111 2112 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2113 unsigned ID, SourceLocation Loc) { 2114 DeclContext *Parent = Context.getTranslationUnitDecl(); 2115 2116 if (getLangOpts().CPlusPlus) { 2117 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2118 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2119 CLinkageDecl->setImplicit(); 2120 Parent->addDecl(CLinkageDecl); 2121 Parent = CLinkageDecl; 2122 } 2123 2124 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2125 /*TInfo=*/nullptr, SC_Extern, 2126 getCurFPFeatures().isFPConstrained(), 2127 false, Type->isFunctionProtoType()); 2128 New->setImplicit(); 2129 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2130 2131 // Create Decl objects for each parameter, adding them to the 2132 // FunctionDecl. 2133 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2134 SmallVector<ParmVarDecl *, 16> Params; 2135 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2136 ParmVarDecl *parm = ParmVarDecl::Create( 2137 Context, New, SourceLocation(), SourceLocation(), nullptr, 2138 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2139 parm->setScopeInfo(0, i); 2140 Params.push_back(parm); 2141 } 2142 New->setParams(Params); 2143 } 2144 2145 AddKnownFunctionAttributes(New); 2146 return New; 2147 } 2148 2149 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2150 /// file scope. lazily create a decl for it. ForRedeclaration is true 2151 /// if we're creating this built-in in anticipation of redeclaring the 2152 /// built-in. 2153 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2154 Scope *S, bool ForRedeclaration, 2155 SourceLocation Loc) { 2156 LookupNecessaryTypesForBuiltin(S, ID); 2157 2158 ASTContext::GetBuiltinTypeError Error; 2159 QualType R = Context.GetBuiltinType(ID, Error); 2160 if (Error) { 2161 if (!ForRedeclaration) 2162 return nullptr; 2163 2164 // If we have a builtin without an associated type we should not emit a 2165 // warning when we were not able to find a type for it. 2166 if (Error == ASTContext::GE_Missing_type || 2167 Context.BuiltinInfo.allowTypeMismatch(ID)) 2168 return nullptr; 2169 2170 // If we could not find a type for setjmp it is because the jmp_buf type was 2171 // not defined prior to the setjmp declaration. 2172 if (Error == ASTContext::GE_Missing_setjmp) { 2173 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2174 << Context.BuiltinInfo.getName(ID); 2175 return nullptr; 2176 } 2177 2178 // Generally, we emit a warning that the declaration requires the 2179 // appropriate header. 2180 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2181 << getHeaderName(Context.BuiltinInfo, ID, Error) 2182 << Context.BuiltinInfo.getName(ID); 2183 return nullptr; 2184 } 2185 2186 if (!ForRedeclaration && 2187 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2188 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2189 Diag(Loc, diag::ext_implicit_lib_function_decl) 2190 << Context.BuiltinInfo.getName(ID) << R; 2191 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2192 Diag(Loc, diag::note_include_header_or_declare) 2193 << Header << Context.BuiltinInfo.getName(ID); 2194 } 2195 2196 if (R.isNull()) 2197 return nullptr; 2198 2199 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2200 RegisterLocallyScopedExternCDecl(New, S); 2201 2202 // TUScope is the translation-unit scope to insert this function into. 2203 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2204 // relate Scopes to DeclContexts, and probably eliminate CurContext 2205 // entirely, but we're not there yet. 2206 DeclContext *SavedContext = CurContext; 2207 CurContext = New->getDeclContext(); 2208 PushOnScopeChains(New, TUScope); 2209 CurContext = SavedContext; 2210 return New; 2211 } 2212 2213 /// Typedef declarations don't have linkage, but they still denote the same 2214 /// entity if their types are the same. 2215 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2216 /// isSameEntity. 2217 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2218 TypedefNameDecl *Decl, 2219 LookupResult &Previous) { 2220 // This is only interesting when modules are enabled. 2221 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2222 return; 2223 2224 // Empty sets are uninteresting. 2225 if (Previous.empty()) 2226 return; 2227 2228 LookupResult::Filter Filter = Previous.makeFilter(); 2229 while (Filter.hasNext()) { 2230 NamedDecl *Old = Filter.next(); 2231 2232 // Non-hidden declarations are never ignored. 2233 if (S.isVisible(Old)) 2234 continue; 2235 2236 // Declarations of the same entity are not ignored, even if they have 2237 // different linkages. 2238 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2239 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2240 Decl->getUnderlyingType())) 2241 continue; 2242 2243 // If both declarations give a tag declaration a typedef name for linkage 2244 // purposes, then they declare the same entity. 2245 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2246 Decl->getAnonDeclWithTypedefName()) 2247 continue; 2248 } 2249 2250 Filter.erase(); 2251 } 2252 2253 Filter.done(); 2254 } 2255 2256 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2257 QualType OldType; 2258 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2259 OldType = OldTypedef->getUnderlyingType(); 2260 else 2261 OldType = Context.getTypeDeclType(Old); 2262 QualType NewType = New->getUnderlyingType(); 2263 2264 if (NewType->isVariablyModifiedType()) { 2265 // Must not redefine a typedef with a variably-modified type. 2266 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2267 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2268 << Kind << NewType; 2269 if (Old->getLocation().isValid()) 2270 notePreviousDefinition(Old, New->getLocation()); 2271 New->setInvalidDecl(); 2272 return true; 2273 } 2274 2275 if (OldType != NewType && 2276 !OldType->isDependentType() && 2277 !NewType->isDependentType() && 2278 !Context.hasSameType(OldType, NewType)) { 2279 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2280 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2281 << Kind << NewType << OldType; 2282 if (Old->getLocation().isValid()) 2283 notePreviousDefinition(Old, New->getLocation()); 2284 New->setInvalidDecl(); 2285 return true; 2286 } 2287 return false; 2288 } 2289 2290 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2291 /// same name and scope as a previous declaration 'Old'. Figure out 2292 /// how to resolve this situation, merging decls or emitting 2293 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2294 /// 2295 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2296 LookupResult &OldDecls) { 2297 // If the new decl is known invalid already, don't bother doing any 2298 // merging checks. 2299 if (New->isInvalidDecl()) return; 2300 2301 // Allow multiple definitions for ObjC built-in typedefs. 2302 // FIXME: Verify the underlying types are equivalent! 2303 if (getLangOpts().ObjC) { 2304 const IdentifierInfo *TypeID = New->getIdentifier(); 2305 switch (TypeID->getLength()) { 2306 default: break; 2307 case 2: 2308 { 2309 if (!TypeID->isStr("id")) 2310 break; 2311 QualType T = New->getUnderlyingType(); 2312 if (!T->isPointerType()) 2313 break; 2314 if (!T->isVoidPointerType()) { 2315 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2316 if (!PT->isStructureType()) 2317 break; 2318 } 2319 Context.setObjCIdRedefinitionType(T); 2320 // Install the built-in type for 'id', ignoring the current definition. 2321 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2322 return; 2323 } 2324 case 5: 2325 if (!TypeID->isStr("Class")) 2326 break; 2327 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2328 // Install the built-in type for 'Class', ignoring the current definition. 2329 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2330 return; 2331 case 3: 2332 if (!TypeID->isStr("SEL")) 2333 break; 2334 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2335 // Install the built-in type for 'SEL', ignoring the current definition. 2336 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2337 return; 2338 } 2339 // Fall through - the typedef name was not a builtin type. 2340 } 2341 2342 // Verify the old decl was also a type. 2343 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2344 if (!Old) { 2345 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2346 << New->getDeclName(); 2347 2348 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2349 if (OldD->getLocation().isValid()) 2350 notePreviousDefinition(OldD, New->getLocation()); 2351 2352 return New->setInvalidDecl(); 2353 } 2354 2355 // If the old declaration is invalid, just give up here. 2356 if (Old->isInvalidDecl()) 2357 return New->setInvalidDecl(); 2358 2359 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2360 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2361 auto *NewTag = New->getAnonDeclWithTypedefName(); 2362 NamedDecl *Hidden = nullptr; 2363 if (OldTag && NewTag && 2364 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2365 !hasVisibleDefinition(OldTag, &Hidden)) { 2366 // There is a definition of this tag, but it is not visible. Use it 2367 // instead of our tag. 2368 New->setTypeForDecl(OldTD->getTypeForDecl()); 2369 if (OldTD->isModed()) 2370 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2371 OldTD->getUnderlyingType()); 2372 else 2373 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2374 2375 // Make the old tag definition visible. 2376 makeMergedDefinitionVisible(Hidden); 2377 2378 // If this was an unscoped enumeration, yank all of its enumerators 2379 // out of the scope. 2380 if (isa<EnumDecl>(NewTag)) { 2381 Scope *EnumScope = getNonFieldDeclScope(S); 2382 for (auto *D : NewTag->decls()) { 2383 auto *ED = cast<EnumConstantDecl>(D); 2384 assert(EnumScope->isDeclScope(ED)); 2385 EnumScope->RemoveDecl(ED); 2386 IdResolver.RemoveDecl(ED); 2387 ED->getLexicalDeclContext()->removeDecl(ED); 2388 } 2389 } 2390 } 2391 } 2392 2393 // If the typedef types are not identical, reject them in all languages and 2394 // with any extensions enabled. 2395 if (isIncompatibleTypedef(Old, New)) 2396 return; 2397 2398 // The types match. Link up the redeclaration chain and merge attributes if 2399 // the old declaration was a typedef. 2400 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2401 New->setPreviousDecl(Typedef); 2402 mergeDeclAttributes(New, Old); 2403 } 2404 2405 if (getLangOpts().MicrosoftExt) 2406 return; 2407 2408 if (getLangOpts().CPlusPlus) { 2409 // C++ [dcl.typedef]p2: 2410 // In a given non-class scope, a typedef specifier can be used to 2411 // redefine the name of any type declared in that scope to refer 2412 // to the type to which it already refers. 2413 if (!isa<CXXRecordDecl>(CurContext)) 2414 return; 2415 2416 // C++0x [dcl.typedef]p4: 2417 // In a given class scope, a typedef specifier can be used to redefine 2418 // any class-name declared in that scope that is not also a typedef-name 2419 // to refer to the type to which it already refers. 2420 // 2421 // This wording came in via DR424, which was a correction to the 2422 // wording in DR56, which accidentally banned code like: 2423 // 2424 // struct S { 2425 // typedef struct A { } A; 2426 // }; 2427 // 2428 // in the C++03 standard. We implement the C++0x semantics, which 2429 // allow the above but disallow 2430 // 2431 // struct S { 2432 // typedef int I; 2433 // typedef int I; 2434 // }; 2435 // 2436 // since that was the intent of DR56. 2437 if (!isa<TypedefNameDecl>(Old)) 2438 return; 2439 2440 Diag(New->getLocation(), diag::err_redefinition) 2441 << New->getDeclName(); 2442 notePreviousDefinition(Old, New->getLocation()); 2443 return New->setInvalidDecl(); 2444 } 2445 2446 // Modules always permit redefinition of typedefs, as does C11. 2447 if (getLangOpts().Modules || getLangOpts().C11) 2448 return; 2449 2450 // If we have a redefinition of a typedef in C, emit a warning. This warning 2451 // is normally mapped to an error, but can be controlled with 2452 // -Wtypedef-redefinition. If either the original or the redefinition is 2453 // in a system header, don't emit this for compatibility with GCC. 2454 if (getDiagnostics().getSuppressSystemWarnings() && 2455 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2456 (Old->isImplicit() || 2457 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2458 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2459 return; 2460 2461 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2462 << New->getDeclName(); 2463 notePreviousDefinition(Old, New->getLocation()); 2464 } 2465 2466 /// DeclhasAttr - returns true if decl Declaration already has the target 2467 /// attribute. 2468 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2469 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2470 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2471 for (const auto *i : D->attrs()) 2472 if (i->getKind() == A->getKind()) { 2473 if (Ann) { 2474 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2475 return true; 2476 continue; 2477 } 2478 // FIXME: Don't hardcode this check 2479 if (OA && isa<OwnershipAttr>(i)) 2480 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2481 return true; 2482 } 2483 2484 return false; 2485 } 2486 2487 static bool isAttributeTargetADefinition(Decl *D) { 2488 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2489 return VD->isThisDeclarationADefinition(); 2490 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2491 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2492 return true; 2493 } 2494 2495 /// Merge alignment attributes from \p Old to \p New, taking into account the 2496 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2497 /// 2498 /// \return \c true if any attributes were added to \p New. 2499 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2500 // Look for alignas attributes on Old, and pick out whichever attribute 2501 // specifies the strictest alignment requirement. 2502 AlignedAttr *OldAlignasAttr = nullptr; 2503 AlignedAttr *OldStrictestAlignAttr = nullptr; 2504 unsigned OldAlign = 0; 2505 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2506 // FIXME: We have no way of representing inherited dependent alignments 2507 // in a case like: 2508 // template<int A, int B> struct alignas(A) X; 2509 // template<int A, int B> struct alignas(B) X {}; 2510 // For now, we just ignore any alignas attributes which are not on the 2511 // definition in such a case. 2512 if (I->isAlignmentDependent()) 2513 return false; 2514 2515 if (I->isAlignas()) 2516 OldAlignasAttr = I; 2517 2518 unsigned Align = I->getAlignment(S.Context); 2519 if (Align > OldAlign) { 2520 OldAlign = Align; 2521 OldStrictestAlignAttr = I; 2522 } 2523 } 2524 2525 // Look for alignas attributes on New. 2526 AlignedAttr *NewAlignasAttr = nullptr; 2527 unsigned NewAlign = 0; 2528 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2529 if (I->isAlignmentDependent()) 2530 return false; 2531 2532 if (I->isAlignas()) 2533 NewAlignasAttr = I; 2534 2535 unsigned Align = I->getAlignment(S.Context); 2536 if (Align > NewAlign) 2537 NewAlign = Align; 2538 } 2539 2540 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2541 // Both declarations have 'alignas' attributes. We require them to match. 2542 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2543 // fall short. (If two declarations both have alignas, they must both match 2544 // every definition, and so must match each other if there is a definition.) 2545 2546 // If either declaration only contains 'alignas(0)' specifiers, then it 2547 // specifies the natural alignment for the type. 2548 if (OldAlign == 0 || NewAlign == 0) { 2549 QualType Ty; 2550 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2551 Ty = VD->getType(); 2552 else 2553 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2554 2555 if (OldAlign == 0) 2556 OldAlign = S.Context.getTypeAlign(Ty); 2557 if (NewAlign == 0) 2558 NewAlign = S.Context.getTypeAlign(Ty); 2559 } 2560 2561 if (OldAlign != NewAlign) { 2562 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2563 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2564 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2565 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2566 } 2567 } 2568 2569 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2570 // C++11 [dcl.align]p6: 2571 // if any declaration of an entity has an alignment-specifier, 2572 // every defining declaration of that entity shall specify an 2573 // equivalent alignment. 2574 // C11 6.7.5/7: 2575 // If the definition of an object does not have an alignment 2576 // specifier, any other declaration of that object shall also 2577 // have no alignment specifier. 2578 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2579 << OldAlignasAttr; 2580 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2581 << OldAlignasAttr; 2582 } 2583 2584 bool AnyAdded = false; 2585 2586 // Ensure we have an attribute representing the strictest alignment. 2587 if (OldAlign > NewAlign) { 2588 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2589 Clone->setInherited(true); 2590 New->addAttr(Clone); 2591 AnyAdded = true; 2592 } 2593 2594 // Ensure we have an alignas attribute if the old declaration had one. 2595 if (OldAlignasAttr && !NewAlignasAttr && 2596 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2597 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2598 Clone->setInherited(true); 2599 New->addAttr(Clone); 2600 AnyAdded = true; 2601 } 2602 2603 return AnyAdded; 2604 } 2605 2606 #define WANT_DECL_MERGE_LOGIC 2607 #include "clang/Sema/AttrParsedAttrImpl.inc" 2608 #undef WANT_DECL_MERGE_LOGIC 2609 2610 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2611 const InheritableAttr *Attr, 2612 Sema::AvailabilityMergeKind AMK) { 2613 // Diagnose any mutual exclusions between the attribute that we want to add 2614 // and attributes that already exist on the declaration. 2615 if (!DiagnoseMutualExclusions(S, D, Attr)) 2616 return false; 2617 2618 // This function copies an attribute Attr from a previous declaration to the 2619 // new declaration D if the new declaration doesn't itself have that attribute 2620 // yet or if that attribute allows duplicates. 2621 // If you're adding a new attribute that requires logic different from 2622 // "use explicit attribute on decl if present, else use attribute from 2623 // previous decl", for example if the attribute needs to be consistent 2624 // between redeclarations, you need to call a custom merge function here. 2625 InheritableAttr *NewAttr = nullptr; 2626 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2627 NewAttr = S.mergeAvailabilityAttr( 2628 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2629 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2630 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2631 AA->getPriority()); 2632 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2633 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2634 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2635 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2636 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2637 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2638 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2639 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2640 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2641 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2642 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2643 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2644 FA->getFirstArg()); 2645 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2646 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2647 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2648 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2649 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2650 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2651 IA->getInheritanceModel()); 2652 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2653 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2654 &S.Context.Idents.get(AA->getSpelling())); 2655 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2656 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2657 isa<CUDAGlobalAttr>(Attr))) { 2658 // CUDA target attributes are part of function signature for 2659 // overloading purposes and must not be merged. 2660 return false; 2661 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2662 NewAttr = S.mergeMinSizeAttr(D, *MA); 2663 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2664 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2665 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2666 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2667 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2668 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2669 else if (isa<AlignedAttr>(Attr)) 2670 // AlignedAttrs are handled separately, because we need to handle all 2671 // such attributes on a declaration at the same time. 2672 NewAttr = nullptr; 2673 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2674 (AMK == Sema::AMK_Override || 2675 AMK == Sema::AMK_ProtocolImplementation || 2676 AMK == Sema::AMK_OptionalProtocolImplementation)) 2677 NewAttr = nullptr; 2678 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2679 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2680 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2681 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2682 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2683 NewAttr = S.mergeImportNameAttr(D, *INA); 2684 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2685 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2686 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2687 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2688 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2689 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2690 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2691 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2692 2693 if (NewAttr) { 2694 NewAttr->setInherited(true); 2695 D->addAttr(NewAttr); 2696 if (isa<MSInheritanceAttr>(NewAttr)) 2697 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2698 return true; 2699 } 2700 2701 return false; 2702 } 2703 2704 static const NamedDecl *getDefinition(const Decl *D) { 2705 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2706 return TD->getDefinition(); 2707 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2708 const VarDecl *Def = VD->getDefinition(); 2709 if (Def) 2710 return Def; 2711 return VD->getActingDefinition(); 2712 } 2713 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2714 const FunctionDecl *Def = nullptr; 2715 if (FD->isDefined(Def, true)) 2716 return Def; 2717 } 2718 return nullptr; 2719 } 2720 2721 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2722 for (const auto *Attribute : D->attrs()) 2723 if (Attribute->getKind() == Kind) 2724 return true; 2725 return false; 2726 } 2727 2728 /// checkNewAttributesAfterDef - If we already have a definition, check that 2729 /// there are no new attributes in this declaration. 2730 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2731 if (!New->hasAttrs()) 2732 return; 2733 2734 const NamedDecl *Def = getDefinition(Old); 2735 if (!Def || Def == New) 2736 return; 2737 2738 AttrVec &NewAttributes = New->getAttrs(); 2739 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2740 const Attr *NewAttribute = NewAttributes[I]; 2741 2742 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2744 Sema::SkipBodyInfo SkipBody; 2745 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2746 2747 // If we're skipping this definition, drop the "alias" attribute. 2748 if (SkipBody.ShouldSkip) { 2749 NewAttributes.erase(NewAttributes.begin() + I); 2750 --E; 2751 continue; 2752 } 2753 } else { 2754 VarDecl *VD = cast<VarDecl>(New); 2755 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2756 VarDecl::TentativeDefinition 2757 ? diag::err_alias_after_tentative 2758 : diag::err_redefinition; 2759 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2760 if (Diag == diag::err_redefinition) 2761 S.notePreviousDefinition(Def, VD->getLocation()); 2762 else 2763 S.Diag(Def->getLocation(), diag::note_previous_definition); 2764 VD->setInvalidDecl(); 2765 } 2766 ++I; 2767 continue; 2768 } 2769 2770 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2771 // Tentative definitions are only interesting for the alias check above. 2772 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2773 ++I; 2774 continue; 2775 } 2776 } 2777 2778 if (hasAttribute(Def, NewAttribute->getKind())) { 2779 ++I; 2780 continue; // regular attr merging will take care of validating this. 2781 } 2782 2783 if (isa<C11NoReturnAttr>(NewAttribute)) { 2784 // C's _Noreturn is allowed to be added to a function after it is defined. 2785 ++I; 2786 continue; 2787 } else if (isa<UuidAttr>(NewAttribute)) { 2788 // msvc will allow a subsequent definition to add an uuid to a class 2789 ++I; 2790 continue; 2791 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2792 if (AA->isAlignas()) { 2793 // C++11 [dcl.align]p6: 2794 // if any declaration of an entity has an alignment-specifier, 2795 // every defining declaration of that entity shall specify an 2796 // equivalent alignment. 2797 // C11 6.7.5/7: 2798 // If the definition of an object does not have an alignment 2799 // specifier, any other declaration of that object shall also 2800 // have no alignment specifier. 2801 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2802 << AA; 2803 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2804 << AA; 2805 NewAttributes.erase(NewAttributes.begin() + I); 2806 --E; 2807 continue; 2808 } 2809 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2810 // If there is a C definition followed by a redeclaration with this 2811 // attribute then there are two different definitions. In C++, prefer the 2812 // standard diagnostics. 2813 if (!S.getLangOpts().CPlusPlus) { 2814 S.Diag(NewAttribute->getLocation(), 2815 diag::err_loader_uninitialized_redeclaration); 2816 S.Diag(Def->getLocation(), diag::note_previous_definition); 2817 NewAttributes.erase(NewAttributes.begin() + I); 2818 --E; 2819 continue; 2820 } 2821 } else if (isa<SelectAnyAttr>(NewAttribute) && 2822 cast<VarDecl>(New)->isInline() && 2823 !cast<VarDecl>(New)->isInlineSpecified()) { 2824 // Don't warn about applying selectany to implicitly inline variables. 2825 // Older compilers and language modes would require the use of selectany 2826 // to make such variables inline, and it would have no effect if we 2827 // honored it. 2828 ++I; 2829 continue; 2830 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2831 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2832 // declarations after defintions. 2833 ++I; 2834 continue; 2835 } 2836 2837 S.Diag(NewAttribute->getLocation(), 2838 diag::warn_attribute_precede_definition); 2839 S.Diag(Def->getLocation(), diag::note_previous_definition); 2840 NewAttributes.erase(NewAttributes.begin() + I); 2841 --E; 2842 } 2843 } 2844 2845 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2846 const ConstInitAttr *CIAttr, 2847 bool AttrBeforeInit) { 2848 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2849 2850 // Figure out a good way to write this specifier on the old declaration. 2851 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2852 // enough of the attribute list spelling information to extract that without 2853 // heroics. 2854 std::string SuitableSpelling; 2855 if (S.getLangOpts().CPlusPlus20) 2856 SuitableSpelling = std::string( 2857 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2858 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2859 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2860 InsertLoc, {tok::l_square, tok::l_square, 2861 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2862 S.PP.getIdentifierInfo("require_constant_initialization"), 2863 tok::r_square, tok::r_square})); 2864 if (SuitableSpelling.empty()) 2865 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2866 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2867 S.PP.getIdentifierInfo("require_constant_initialization"), 2868 tok::r_paren, tok::r_paren})); 2869 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2870 SuitableSpelling = "constinit"; 2871 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2872 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2873 if (SuitableSpelling.empty()) 2874 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2875 SuitableSpelling += " "; 2876 2877 if (AttrBeforeInit) { 2878 // extern constinit int a; 2879 // int a = 0; // error (missing 'constinit'), accepted as extension 2880 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2881 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2882 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2883 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2884 } else { 2885 // int a = 0; 2886 // constinit extern int a; // error (missing 'constinit') 2887 S.Diag(CIAttr->getLocation(), 2888 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2889 : diag::warn_require_const_init_added_too_late) 2890 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2891 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2892 << CIAttr->isConstinit() 2893 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2894 } 2895 } 2896 2897 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2898 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2899 AvailabilityMergeKind AMK) { 2900 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2901 UsedAttr *NewAttr = OldAttr->clone(Context); 2902 NewAttr->setInherited(true); 2903 New->addAttr(NewAttr); 2904 } 2905 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2906 RetainAttr *NewAttr = OldAttr->clone(Context); 2907 NewAttr->setInherited(true); 2908 New->addAttr(NewAttr); 2909 } 2910 2911 if (!Old->hasAttrs() && !New->hasAttrs()) 2912 return; 2913 2914 // [dcl.constinit]p1: 2915 // If the [constinit] specifier is applied to any declaration of a 2916 // variable, it shall be applied to the initializing declaration. 2917 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2918 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2919 if (bool(OldConstInit) != bool(NewConstInit)) { 2920 const auto *OldVD = cast<VarDecl>(Old); 2921 auto *NewVD = cast<VarDecl>(New); 2922 2923 // Find the initializing declaration. Note that we might not have linked 2924 // the new declaration into the redeclaration chain yet. 2925 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2926 if (!InitDecl && 2927 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2928 InitDecl = NewVD; 2929 2930 if (InitDecl == NewVD) { 2931 // This is the initializing declaration. If it would inherit 'constinit', 2932 // that's ill-formed. (Note that we do not apply this to the attribute 2933 // form). 2934 if (OldConstInit && OldConstInit->isConstinit()) 2935 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2936 /*AttrBeforeInit=*/true); 2937 } else if (NewConstInit) { 2938 // This is the first time we've been told that this declaration should 2939 // have a constant initializer. If we already saw the initializing 2940 // declaration, this is too late. 2941 if (InitDecl && InitDecl != NewVD) { 2942 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2943 /*AttrBeforeInit=*/false); 2944 NewVD->dropAttr<ConstInitAttr>(); 2945 } 2946 } 2947 } 2948 2949 // Attributes declared post-definition are currently ignored. 2950 checkNewAttributesAfterDef(*this, New, Old); 2951 2952 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2953 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2954 if (!OldA->isEquivalent(NewA)) { 2955 // This redeclaration changes __asm__ label. 2956 Diag(New->getLocation(), diag::err_different_asm_label); 2957 Diag(OldA->getLocation(), diag::note_previous_declaration); 2958 } 2959 } else if (Old->isUsed()) { 2960 // This redeclaration adds an __asm__ label to a declaration that has 2961 // already been ODR-used. 2962 Diag(New->getLocation(), diag::err_late_asm_label_name) 2963 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2964 } 2965 } 2966 2967 // Re-declaration cannot add abi_tag's. 2968 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2969 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2970 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2971 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 2972 Diag(NewAbiTagAttr->getLocation(), 2973 diag::err_new_abi_tag_on_redeclaration) 2974 << NewTag; 2975 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2976 } 2977 } 2978 } else { 2979 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2980 Diag(Old->getLocation(), diag::note_previous_declaration); 2981 } 2982 } 2983 2984 // This redeclaration adds a section attribute. 2985 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2986 if (auto *VD = dyn_cast<VarDecl>(New)) { 2987 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2988 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2989 Diag(Old->getLocation(), diag::note_previous_declaration); 2990 } 2991 } 2992 } 2993 2994 // Redeclaration adds code-seg attribute. 2995 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2996 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2997 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2998 Diag(New->getLocation(), diag::warn_mismatched_section) 2999 << 0 /*codeseg*/; 3000 Diag(Old->getLocation(), diag::note_previous_declaration); 3001 } 3002 3003 if (!Old->hasAttrs()) 3004 return; 3005 3006 bool foundAny = New->hasAttrs(); 3007 3008 // Ensure that any moving of objects within the allocated map is done before 3009 // we process them. 3010 if (!foundAny) New->setAttrs(AttrVec()); 3011 3012 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3013 // Ignore deprecated/unavailable/availability attributes if requested. 3014 AvailabilityMergeKind LocalAMK = AMK_None; 3015 if (isa<DeprecatedAttr>(I) || 3016 isa<UnavailableAttr>(I) || 3017 isa<AvailabilityAttr>(I)) { 3018 switch (AMK) { 3019 case AMK_None: 3020 continue; 3021 3022 case AMK_Redeclaration: 3023 case AMK_Override: 3024 case AMK_ProtocolImplementation: 3025 case AMK_OptionalProtocolImplementation: 3026 LocalAMK = AMK; 3027 break; 3028 } 3029 } 3030 3031 // Already handled. 3032 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3033 continue; 3034 3035 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3036 foundAny = true; 3037 } 3038 3039 if (mergeAlignedAttrs(*this, New, Old)) 3040 foundAny = true; 3041 3042 if (!foundAny) New->dropAttrs(); 3043 } 3044 3045 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3046 /// to the new one. 3047 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3048 const ParmVarDecl *oldDecl, 3049 Sema &S) { 3050 // C++11 [dcl.attr.depend]p2: 3051 // The first declaration of a function shall specify the 3052 // carries_dependency attribute for its declarator-id if any declaration 3053 // of the function specifies the carries_dependency attribute. 3054 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3055 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3056 S.Diag(CDA->getLocation(), 3057 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3058 // Find the first declaration of the parameter. 3059 // FIXME: Should we build redeclaration chains for function parameters? 3060 const FunctionDecl *FirstFD = 3061 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3062 const ParmVarDecl *FirstVD = 3063 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3064 S.Diag(FirstVD->getLocation(), 3065 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3066 } 3067 3068 if (!oldDecl->hasAttrs()) 3069 return; 3070 3071 bool foundAny = newDecl->hasAttrs(); 3072 3073 // Ensure that any moving of objects within the allocated map is 3074 // done before we process them. 3075 if (!foundAny) newDecl->setAttrs(AttrVec()); 3076 3077 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3078 if (!DeclHasAttr(newDecl, I)) { 3079 InheritableAttr *newAttr = 3080 cast<InheritableParamAttr>(I->clone(S.Context)); 3081 newAttr->setInherited(true); 3082 newDecl->addAttr(newAttr); 3083 foundAny = true; 3084 } 3085 } 3086 3087 if (!foundAny) newDecl->dropAttrs(); 3088 } 3089 3090 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3091 const ParmVarDecl *OldParam, 3092 Sema &S) { 3093 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3094 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3095 if (*Oldnullability != *Newnullability) { 3096 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3097 << DiagNullabilityKind( 3098 *Newnullability, 3099 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3100 != 0)) 3101 << DiagNullabilityKind( 3102 *Oldnullability, 3103 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3104 != 0)); 3105 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3106 } 3107 } else { 3108 QualType NewT = NewParam->getType(); 3109 NewT = S.Context.getAttributedType( 3110 AttributedType::getNullabilityAttrKind(*Oldnullability), 3111 NewT, NewT); 3112 NewParam->setType(NewT); 3113 } 3114 } 3115 } 3116 3117 namespace { 3118 3119 /// Used in MergeFunctionDecl to keep track of function parameters in 3120 /// C. 3121 struct GNUCompatibleParamWarning { 3122 ParmVarDecl *OldParm; 3123 ParmVarDecl *NewParm; 3124 QualType PromotedType; 3125 }; 3126 3127 } // end anonymous namespace 3128 3129 // Determine whether the previous declaration was a definition, implicit 3130 // declaration, or a declaration. 3131 template <typename T> 3132 static std::pair<diag::kind, SourceLocation> 3133 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3134 diag::kind PrevDiag; 3135 SourceLocation OldLocation = Old->getLocation(); 3136 if (Old->isThisDeclarationADefinition()) 3137 PrevDiag = diag::note_previous_definition; 3138 else if (Old->isImplicit()) { 3139 PrevDiag = diag::note_previous_implicit_declaration; 3140 if (OldLocation.isInvalid()) 3141 OldLocation = New->getLocation(); 3142 } else 3143 PrevDiag = diag::note_previous_declaration; 3144 return std::make_pair(PrevDiag, OldLocation); 3145 } 3146 3147 /// canRedefineFunction - checks if a function can be redefined. Currently, 3148 /// only extern inline functions can be redefined, and even then only in 3149 /// GNU89 mode. 3150 static bool canRedefineFunction(const FunctionDecl *FD, 3151 const LangOptions& LangOpts) { 3152 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3153 !LangOpts.CPlusPlus && 3154 FD->isInlineSpecified() && 3155 FD->getStorageClass() == SC_Extern); 3156 } 3157 3158 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3159 const AttributedType *AT = T->getAs<AttributedType>(); 3160 while (AT && !AT->isCallingConv()) 3161 AT = AT->getModifiedType()->getAs<AttributedType>(); 3162 return AT; 3163 } 3164 3165 template <typename T> 3166 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3167 const DeclContext *DC = Old->getDeclContext(); 3168 if (DC->isRecord()) 3169 return false; 3170 3171 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3172 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3173 return true; 3174 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3175 return true; 3176 return false; 3177 } 3178 3179 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3180 static bool isExternC(VarTemplateDecl *) { return false; } 3181 static bool isExternC(FunctionTemplateDecl *) { return false; } 3182 3183 /// Check whether a redeclaration of an entity introduced by a 3184 /// using-declaration is valid, given that we know it's not an overload 3185 /// (nor a hidden tag declaration). 3186 template<typename ExpectedDecl> 3187 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3188 ExpectedDecl *New) { 3189 // C++11 [basic.scope.declarative]p4: 3190 // Given a set of declarations in a single declarative region, each of 3191 // which specifies the same unqualified name, 3192 // -- they shall all refer to the same entity, or all refer to functions 3193 // and function templates; or 3194 // -- exactly one declaration shall declare a class name or enumeration 3195 // name that is not a typedef name and the other declarations shall all 3196 // refer to the same variable or enumerator, or all refer to functions 3197 // and function templates; in this case the class name or enumeration 3198 // name is hidden (3.3.10). 3199 3200 // C++11 [namespace.udecl]p14: 3201 // If a function declaration in namespace scope or block scope has the 3202 // same name and the same parameter-type-list as a function introduced 3203 // by a using-declaration, and the declarations do not declare the same 3204 // function, the program is ill-formed. 3205 3206 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3207 if (Old && 3208 !Old->getDeclContext()->getRedeclContext()->Equals( 3209 New->getDeclContext()->getRedeclContext()) && 3210 !(isExternC(Old) && isExternC(New))) 3211 Old = nullptr; 3212 3213 if (!Old) { 3214 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3215 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3216 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3217 return true; 3218 } 3219 return false; 3220 } 3221 3222 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3223 const FunctionDecl *B) { 3224 assert(A->getNumParams() == B->getNumParams()); 3225 3226 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3227 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3228 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3229 if (AttrA == AttrB) 3230 return true; 3231 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3232 AttrA->isDynamic() == AttrB->isDynamic(); 3233 }; 3234 3235 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3236 } 3237 3238 /// If necessary, adjust the semantic declaration context for a qualified 3239 /// declaration to name the correct inline namespace within the qualifier. 3240 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3241 DeclaratorDecl *OldD) { 3242 // The only case where we need to update the DeclContext is when 3243 // redeclaration lookup for a qualified name finds a declaration 3244 // in an inline namespace within the context named by the qualifier: 3245 // 3246 // inline namespace N { int f(); } 3247 // int ::f(); // Sema DC needs adjusting from :: to N::. 3248 // 3249 // For unqualified declarations, the semantic context *can* change 3250 // along the redeclaration chain (for local extern declarations, 3251 // extern "C" declarations, and friend declarations in particular). 3252 if (!NewD->getQualifier()) 3253 return; 3254 3255 // NewD is probably already in the right context. 3256 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3257 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3258 if (NamedDC->Equals(SemaDC)) 3259 return; 3260 3261 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3262 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3263 "unexpected context for redeclaration"); 3264 3265 auto *LexDC = NewD->getLexicalDeclContext(); 3266 auto FixSemaDC = [=](NamedDecl *D) { 3267 if (!D) 3268 return; 3269 D->setDeclContext(SemaDC); 3270 D->setLexicalDeclContext(LexDC); 3271 }; 3272 3273 FixSemaDC(NewD); 3274 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3275 FixSemaDC(FD->getDescribedFunctionTemplate()); 3276 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3277 FixSemaDC(VD->getDescribedVarTemplate()); 3278 } 3279 3280 /// MergeFunctionDecl - We just parsed a function 'New' from 3281 /// declarator D which has the same name and scope as a previous 3282 /// declaration 'Old'. Figure out how to resolve this situation, 3283 /// merging decls or emitting diagnostics as appropriate. 3284 /// 3285 /// In C++, New and Old must be declarations that are not 3286 /// overloaded. Use IsOverload to determine whether New and Old are 3287 /// overloaded, and to select the Old declaration that New should be 3288 /// merged with. 3289 /// 3290 /// Returns true if there was an error, false otherwise. 3291 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3292 Scope *S, bool MergeTypeWithOld) { 3293 // Verify the old decl was also a function. 3294 FunctionDecl *Old = OldD->getAsFunction(); 3295 if (!Old) { 3296 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3297 if (New->getFriendObjectKind()) { 3298 Diag(New->getLocation(), diag::err_using_decl_friend); 3299 Diag(Shadow->getTargetDecl()->getLocation(), 3300 diag::note_using_decl_target); 3301 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3302 << 0; 3303 return true; 3304 } 3305 3306 // Check whether the two declarations might declare the same function or 3307 // function template. 3308 if (FunctionTemplateDecl *NewTemplate = 3309 New->getDescribedFunctionTemplate()) { 3310 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3311 NewTemplate)) 3312 return true; 3313 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3314 ->getAsFunction(); 3315 } else { 3316 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3317 return true; 3318 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3319 } 3320 } else { 3321 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3322 << New->getDeclName(); 3323 notePreviousDefinition(OldD, New->getLocation()); 3324 return true; 3325 } 3326 } 3327 3328 // If the old declaration was found in an inline namespace and the new 3329 // declaration was qualified, update the DeclContext to match. 3330 adjustDeclContextForDeclaratorDecl(New, Old); 3331 3332 // If the old declaration is invalid, just give up here. 3333 if (Old->isInvalidDecl()) 3334 return true; 3335 3336 // Disallow redeclaration of some builtins. 3337 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3338 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3339 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3340 << Old << Old->getType(); 3341 return true; 3342 } 3343 3344 diag::kind PrevDiag; 3345 SourceLocation OldLocation; 3346 std::tie(PrevDiag, OldLocation) = 3347 getNoteDiagForInvalidRedeclaration(Old, New); 3348 3349 // Don't complain about this if we're in GNU89 mode and the old function 3350 // is an extern inline function. 3351 // Don't complain about specializations. They are not supposed to have 3352 // storage classes. 3353 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3354 New->getStorageClass() == SC_Static && 3355 Old->hasExternalFormalLinkage() && 3356 !New->getTemplateSpecializationInfo() && 3357 !canRedefineFunction(Old, getLangOpts())) { 3358 if (getLangOpts().MicrosoftExt) { 3359 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3360 Diag(OldLocation, PrevDiag); 3361 } else { 3362 Diag(New->getLocation(), diag::err_static_non_static) << New; 3363 Diag(OldLocation, PrevDiag); 3364 return true; 3365 } 3366 } 3367 3368 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3369 if (!Old->hasAttr<InternalLinkageAttr>()) { 3370 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3371 << ILA; 3372 Diag(Old->getLocation(), diag::note_previous_declaration); 3373 New->dropAttr<InternalLinkageAttr>(); 3374 } 3375 3376 if (auto *EA = New->getAttr<ErrorAttr>()) { 3377 if (!Old->hasAttr<ErrorAttr>()) { 3378 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3379 Diag(Old->getLocation(), diag::note_previous_declaration); 3380 New->dropAttr<ErrorAttr>(); 3381 } 3382 } 3383 3384 if (CheckRedeclarationModuleOwnership(New, Old)) 3385 return true; 3386 3387 if (!getLangOpts().CPlusPlus) { 3388 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3389 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3390 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3391 << New << OldOvl; 3392 3393 // Try our best to find a decl that actually has the overloadable 3394 // attribute for the note. In most cases (e.g. programs with only one 3395 // broken declaration/definition), this won't matter. 3396 // 3397 // FIXME: We could do this if we juggled some extra state in 3398 // OverloadableAttr, rather than just removing it. 3399 const Decl *DiagOld = Old; 3400 if (OldOvl) { 3401 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3402 const auto *A = D->getAttr<OverloadableAttr>(); 3403 return A && !A->isImplicit(); 3404 }); 3405 // If we've implicitly added *all* of the overloadable attrs to this 3406 // chain, emitting a "previous redecl" note is pointless. 3407 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3408 } 3409 3410 if (DiagOld) 3411 Diag(DiagOld->getLocation(), 3412 diag::note_attribute_overloadable_prev_overload) 3413 << OldOvl; 3414 3415 if (OldOvl) 3416 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3417 else 3418 New->dropAttr<OverloadableAttr>(); 3419 } 3420 } 3421 3422 // If a function is first declared with a calling convention, but is later 3423 // declared or defined without one, all following decls assume the calling 3424 // convention of the first. 3425 // 3426 // It's OK if a function is first declared without a calling convention, 3427 // but is later declared or defined with the default calling convention. 3428 // 3429 // To test if either decl has an explicit calling convention, we look for 3430 // AttributedType sugar nodes on the type as written. If they are missing or 3431 // were canonicalized away, we assume the calling convention was implicit. 3432 // 3433 // Note also that we DO NOT return at this point, because we still have 3434 // other tests to run. 3435 QualType OldQType = Context.getCanonicalType(Old->getType()); 3436 QualType NewQType = Context.getCanonicalType(New->getType()); 3437 const FunctionType *OldType = cast<FunctionType>(OldQType); 3438 const FunctionType *NewType = cast<FunctionType>(NewQType); 3439 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3440 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3441 bool RequiresAdjustment = false; 3442 3443 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3444 FunctionDecl *First = Old->getFirstDecl(); 3445 const FunctionType *FT = 3446 First->getType().getCanonicalType()->castAs<FunctionType>(); 3447 FunctionType::ExtInfo FI = FT->getExtInfo(); 3448 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3449 if (!NewCCExplicit) { 3450 // Inherit the CC from the previous declaration if it was specified 3451 // there but not here. 3452 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3453 RequiresAdjustment = true; 3454 } else if (Old->getBuiltinID()) { 3455 // Builtin attribute isn't propagated to the new one yet at this point, 3456 // so we check if the old one is a builtin. 3457 3458 // Calling Conventions on a Builtin aren't really useful and setting a 3459 // default calling convention and cdecl'ing some builtin redeclarations is 3460 // common, so warn and ignore the calling convention on the redeclaration. 3461 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3462 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3463 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3464 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3465 RequiresAdjustment = true; 3466 } else { 3467 // Calling conventions aren't compatible, so complain. 3468 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3469 Diag(New->getLocation(), diag::err_cconv_change) 3470 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3471 << !FirstCCExplicit 3472 << (!FirstCCExplicit ? "" : 3473 FunctionType::getNameForCallConv(FI.getCC())); 3474 3475 // Put the note on the first decl, since it is the one that matters. 3476 Diag(First->getLocation(), diag::note_previous_declaration); 3477 return true; 3478 } 3479 } 3480 3481 // FIXME: diagnose the other way around? 3482 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3483 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3484 RequiresAdjustment = true; 3485 } 3486 3487 // Merge regparm attribute. 3488 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3489 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3490 if (NewTypeInfo.getHasRegParm()) { 3491 Diag(New->getLocation(), diag::err_regparm_mismatch) 3492 << NewType->getRegParmType() 3493 << OldType->getRegParmType(); 3494 Diag(OldLocation, diag::note_previous_declaration); 3495 return true; 3496 } 3497 3498 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3499 RequiresAdjustment = true; 3500 } 3501 3502 // Merge ns_returns_retained attribute. 3503 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3504 if (NewTypeInfo.getProducesResult()) { 3505 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3506 << "'ns_returns_retained'"; 3507 Diag(OldLocation, diag::note_previous_declaration); 3508 return true; 3509 } 3510 3511 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3512 RequiresAdjustment = true; 3513 } 3514 3515 if (OldTypeInfo.getNoCallerSavedRegs() != 3516 NewTypeInfo.getNoCallerSavedRegs()) { 3517 if (NewTypeInfo.getNoCallerSavedRegs()) { 3518 AnyX86NoCallerSavedRegistersAttr *Attr = 3519 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3520 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3521 Diag(OldLocation, diag::note_previous_declaration); 3522 return true; 3523 } 3524 3525 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3526 RequiresAdjustment = true; 3527 } 3528 3529 if (RequiresAdjustment) { 3530 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3531 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3532 New->setType(QualType(AdjustedType, 0)); 3533 NewQType = Context.getCanonicalType(New->getType()); 3534 } 3535 3536 // If this redeclaration makes the function inline, we may need to add it to 3537 // UndefinedButUsed. 3538 if (!Old->isInlined() && New->isInlined() && 3539 !New->hasAttr<GNUInlineAttr>() && 3540 !getLangOpts().GNUInline && 3541 Old->isUsed(false) && 3542 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3543 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3544 SourceLocation())); 3545 3546 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3547 // about it. 3548 if (New->hasAttr<GNUInlineAttr>() && 3549 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3550 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3551 } 3552 3553 // If pass_object_size params don't match up perfectly, this isn't a valid 3554 // redeclaration. 3555 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3556 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3557 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3558 << New->getDeclName(); 3559 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3560 return true; 3561 } 3562 3563 if (getLangOpts().CPlusPlus) { 3564 // C++1z [over.load]p2 3565 // Certain function declarations cannot be overloaded: 3566 // -- Function declarations that differ only in the return type, 3567 // the exception specification, or both cannot be overloaded. 3568 3569 // Check the exception specifications match. This may recompute the type of 3570 // both Old and New if it resolved exception specifications, so grab the 3571 // types again after this. Because this updates the type, we do this before 3572 // any of the other checks below, which may update the "de facto" NewQType 3573 // but do not necessarily update the type of New. 3574 if (CheckEquivalentExceptionSpec(Old, New)) 3575 return true; 3576 OldQType = Context.getCanonicalType(Old->getType()); 3577 NewQType = Context.getCanonicalType(New->getType()); 3578 3579 // Go back to the type source info to compare the declared return types, 3580 // per C++1y [dcl.type.auto]p13: 3581 // Redeclarations or specializations of a function or function template 3582 // with a declared return type that uses a placeholder type shall also 3583 // use that placeholder, not a deduced type. 3584 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3585 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3586 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3587 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3588 OldDeclaredReturnType)) { 3589 QualType ResQT; 3590 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3591 OldDeclaredReturnType->isObjCObjectPointerType()) 3592 // FIXME: This does the wrong thing for a deduced return type. 3593 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3594 if (ResQT.isNull()) { 3595 if (New->isCXXClassMember() && New->isOutOfLine()) 3596 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3597 << New << New->getReturnTypeSourceRange(); 3598 else 3599 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3600 << New->getReturnTypeSourceRange(); 3601 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3602 << Old->getReturnTypeSourceRange(); 3603 return true; 3604 } 3605 else 3606 NewQType = ResQT; 3607 } 3608 3609 QualType OldReturnType = OldType->getReturnType(); 3610 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3611 if (OldReturnType != NewReturnType) { 3612 // If this function has a deduced return type and has already been 3613 // defined, copy the deduced value from the old declaration. 3614 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3615 if (OldAT && OldAT->isDeduced()) { 3616 QualType DT = OldAT->getDeducedType(); 3617 if (DT.isNull()) { 3618 New->setType(SubstAutoTypeDependent(New->getType())); 3619 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3620 } else { 3621 New->setType(SubstAutoType(New->getType(), DT)); 3622 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3623 } 3624 } 3625 } 3626 3627 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3628 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3629 if (OldMethod && NewMethod) { 3630 // Preserve triviality. 3631 NewMethod->setTrivial(OldMethod->isTrivial()); 3632 3633 // MSVC allows explicit template specialization at class scope: 3634 // 2 CXXMethodDecls referring to the same function will be injected. 3635 // We don't want a redeclaration error. 3636 bool IsClassScopeExplicitSpecialization = 3637 OldMethod->isFunctionTemplateSpecialization() && 3638 NewMethod->isFunctionTemplateSpecialization(); 3639 bool isFriend = NewMethod->getFriendObjectKind(); 3640 3641 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3642 !IsClassScopeExplicitSpecialization) { 3643 // -- Member function declarations with the same name and the 3644 // same parameter types cannot be overloaded if any of them 3645 // is a static member function declaration. 3646 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3647 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3648 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3649 return true; 3650 } 3651 3652 // C++ [class.mem]p1: 3653 // [...] A member shall not be declared twice in the 3654 // member-specification, except that a nested class or member 3655 // class template can be declared and then later defined. 3656 if (!inTemplateInstantiation()) { 3657 unsigned NewDiag; 3658 if (isa<CXXConstructorDecl>(OldMethod)) 3659 NewDiag = diag::err_constructor_redeclared; 3660 else if (isa<CXXDestructorDecl>(NewMethod)) 3661 NewDiag = diag::err_destructor_redeclared; 3662 else if (isa<CXXConversionDecl>(NewMethod)) 3663 NewDiag = diag::err_conv_function_redeclared; 3664 else 3665 NewDiag = diag::err_member_redeclared; 3666 3667 Diag(New->getLocation(), NewDiag); 3668 } else { 3669 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3670 << New << New->getType(); 3671 } 3672 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3673 return true; 3674 3675 // Complain if this is an explicit declaration of a special 3676 // member that was initially declared implicitly. 3677 // 3678 // As an exception, it's okay to befriend such methods in order 3679 // to permit the implicit constructor/destructor/operator calls. 3680 } else if (OldMethod->isImplicit()) { 3681 if (isFriend) { 3682 NewMethod->setImplicit(); 3683 } else { 3684 Diag(NewMethod->getLocation(), 3685 diag::err_definition_of_implicitly_declared_member) 3686 << New << getSpecialMember(OldMethod); 3687 return true; 3688 } 3689 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3690 Diag(NewMethod->getLocation(), 3691 diag::err_definition_of_explicitly_defaulted_member) 3692 << getSpecialMember(OldMethod); 3693 return true; 3694 } 3695 } 3696 3697 // C++11 [dcl.attr.noreturn]p1: 3698 // The first declaration of a function shall specify the noreturn 3699 // attribute if any declaration of that function specifies the noreturn 3700 // attribute. 3701 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3702 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3703 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3704 << NRA; 3705 Diag(Old->getLocation(), diag::note_previous_declaration); 3706 } 3707 3708 // C++11 [dcl.attr.depend]p2: 3709 // The first declaration of a function shall specify the 3710 // carries_dependency attribute for its declarator-id if any declaration 3711 // of the function specifies the carries_dependency attribute. 3712 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3713 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3714 Diag(CDA->getLocation(), 3715 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3716 Diag(Old->getFirstDecl()->getLocation(), 3717 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3718 } 3719 3720 // (C++98 8.3.5p3): 3721 // All declarations for a function shall agree exactly in both the 3722 // return type and the parameter-type-list. 3723 // We also want to respect all the extended bits except noreturn. 3724 3725 // noreturn should now match unless the old type info didn't have it. 3726 QualType OldQTypeForComparison = OldQType; 3727 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3728 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3729 const FunctionType *OldTypeForComparison 3730 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3731 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3732 assert(OldQTypeForComparison.isCanonical()); 3733 } 3734 3735 if (haveIncompatibleLanguageLinkages(Old, New)) { 3736 // As a special case, retain the language linkage from previous 3737 // declarations of a friend function as an extension. 3738 // 3739 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3740 // and is useful because there's otherwise no way to specify language 3741 // linkage within class scope. 3742 // 3743 // Check cautiously as the friend object kind isn't yet complete. 3744 if (New->getFriendObjectKind() != Decl::FOK_None) { 3745 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3746 Diag(OldLocation, PrevDiag); 3747 } else { 3748 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3749 Diag(OldLocation, PrevDiag); 3750 return true; 3751 } 3752 } 3753 3754 // If the function types are compatible, merge the declarations. Ignore the 3755 // exception specifier because it was already checked above in 3756 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3757 // about incompatible types under -fms-compatibility. 3758 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3759 NewQType)) 3760 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3761 3762 // If the types are imprecise (due to dependent constructs in friends or 3763 // local extern declarations), it's OK if they differ. We'll check again 3764 // during instantiation. 3765 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3766 return false; 3767 3768 // Fall through for conflicting redeclarations and redefinitions. 3769 } 3770 3771 // C: Function types need to be compatible, not identical. This handles 3772 // duplicate function decls like "void f(int); void f(enum X);" properly. 3773 if (!getLangOpts().CPlusPlus && 3774 Context.typesAreCompatible(OldQType, NewQType)) { 3775 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3776 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3777 const FunctionProtoType *OldProto = nullptr; 3778 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3779 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3780 // The old declaration provided a function prototype, but the 3781 // new declaration does not. Merge in the prototype. 3782 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3783 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3784 NewQType = 3785 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3786 OldProto->getExtProtoInfo()); 3787 New->setType(NewQType); 3788 New->setHasInheritedPrototype(); 3789 3790 // Synthesize parameters with the same types. 3791 SmallVector<ParmVarDecl*, 16> Params; 3792 for (const auto &ParamType : OldProto->param_types()) { 3793 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3794 SourceLocation(), nullptr, 3795 ParamType, /*TInfo=*/nullptr, 3796 SC_None, nullptr); 3797 Param->setScopeInfo(0, Params.size()); 3798 Param->setImplicit(); 3799 Params.push_back(Param); 3800 } 3801 3802 New->setParams(Params); 3803 } 3804 3805 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3806 } 3807 3808 // Check if the function types are compatible when pointer size address 3809 // spaces are ignored. 3810 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3811 return false; 3812 3813 // GNU C permits a K&R definition to follow a prototype declaration 3814 // if the declared types of the parameters in the K&R definition 3815 // match the types in the prototype declaration, even when the 3816 // promoted types of the parameters from the K&R definition differ 3817 // from the types in the prototype. GCC then keeps the types from 3818 // the prototype. 3819 // 3820 // If a variadic prototype is followed by a non-variadic K&R definition, 3821 // the K&R definition becomes variadic. This is sort of an edge case, but 3822 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3823 // C99 6.9.1p8. 3824 if (!getLangOpts().CPlusPlus && 3825 Old->hasPrototype() && !New->hasPrototype() && 3826 New->getType()->getAs<FunctionProtoType>() && 3827 Old->getNumParams() == New->getNumParams()) { 3828 SmallVector<QualType, 16> ArgTypes; 3829 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3830 const FunctionProtoType *OldProto 3831 = Old->getType()->getAs<FunctionProtoType>(); 3832 const FunctionProtoType *NewProto 3833 = New->getType()->getAs<FunctionProtoType>(); 3834 3835 // Determine whether this is the GNU C extension. 3836 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3837 NewProto->getReturnType()); 3838 bool LooseCompatible = !MergedReturn.isNull(); 3839 for (unsigned Idx = 0, End = Old->getNumParams(); 3840 LooseCompatible && Idx != End; ++Idx) { 3841 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3842 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3843 if (Context.typesAreCompatible(OldParm->getType(), 3844 NewProto->getParamType(Idx))) { 3845 ArgTypes.push_back(NewParm->getType()); 3846 } else if (Context.typesAreCompatible(OldParm->getType(), 3847 NewParm->getType(), 3848 /*CompareUnqualified=*/true)) { 3849 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3850 NewProto->getParamType(Idx) }; 3851 Warnings.push_back(Warn); 3852 ArgTypes.push_back(NewParm->getType()); 3853 } else 3854 LooseCompatible = false; 3855 } 3856 3857 if (LooseCompatible) { 3858 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3859 Diag(Warnings[Warn].NewParm->getLocation(), 3860 diag::ext_param_promoted_not_compatible_with_prototype) 3861 << Warnings[Warn].PromotedType 3862 << Warnings[Warn].OldParm->getType(); 3863 if (Warnings[Warn].OldParm->getLocation().isValid()) 3864 Diag(Warnings[Warn].OldParm->getLocation(), 3865 diag::note_previous_declaration); 3866 } 3867 3868 if (MergeTypeWithOld) 3869 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3870 OldProto->getExtProtoInfo())); 3871 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3872 } 3873 3874 // Fall through to diagnose conflicting types. 3875 } 3876 3877 // A function that has already been declared has been redeclared or 3878 // defined with a different type; show an appropriate diagnostic. 3879 3880 // If the previous declaration was an implicitly-generated builtin 3881 // declaration, then at the very least we should use a specialized note. 3882 unsigned BuiltinID; 3883 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3884 // If it's actually a library-defined builtin function like 'malloc' 3885 // or 'printf', just warn about the incompatible redeclaration. 3886 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3887 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3888 Diag(OldLocation, diag::note_previous_builtin_declaration) 3889 << Old << Old->getType(); 3890 return false; 3891 } 3892 3893 PrevDiag = diag::note_previous_builtin_declaration; 3894 } 3895 3896 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3897 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3898 return true; 3899 } 3900 3901 /// Completes the merge of two function declarations that are 3902 /// known to be compatible. 3903 /// 3904 /// This routine handles the merging of attributes and other 3905 /// properties of function declarations from the old declaration to 3906 /// the new declaration, once we know that New is in fact a 3907 /// redeclaration of Old. 3908 /// 3909 /// \returns false 3910 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3911 Scope *S, bool MergeTypeWithOld) { 3912 // Merge the attributes 3913 mergeDeclAttributes(New, Old); 3914 3915 // Merge "pure" flag. 3916 if (Old->isPure()) 3917 New->setPure(); 3918 3919 // Merge "used" flag. 3920 if (Old->getMostRecentDecl()->isUsed(false)) 3921 New->setIsUsed(); 3922 3923 // Merge attributes from the parameters. These can mismatch with K&R 3924 // declarations. 3925 if (New->getNumParams() == Old->getNumParams()) 3926 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3927 ParmVarDecl *NewParam = New->getParamDecl(i); 3928 ParmVarDecl *OldParam = Old->getParamDecl(i); 3929 mergeParamDeclAttributes(NewParam, OldParam, *this); 3930 mergeParamDeclTypes(NewParam, OldParam, *this); 3931 } 3932 3933 if (getLangOpts().CPlusPlus) 3934 return MergeCXXFunctionDecl(New, Old, S); 3935 3936 // Merge the function types so the we get the composite types for the return 3937 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3938 // was visible. 3939 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3940 if (!Merged.isNull() && MergeTypeWithOld) 3941 New->setType(Merged); 3942 3943 return false; 3944 } 3945 3946 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3947 ObjCMethodDecl *oldMethod) { 3948 // Merge the attributes, including deprecated/unavailable 3949 AvailabilityMergeKind MergeKind = 3950 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3951 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3952 : AMK_ProtocolImplementation) 3953 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3954 : AMK_Override; 3955 3956 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3957 3958 // Merge attributes from the parameters. 3959 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3960 oe = oldMethod->param_end(); 3961 for (ObjCMethodDecl::param_iterator 3962 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3963 ni != ne && oi != oe; ++ni, ++oi) 3964 mergeParamDeclAttributes(*ni, *oi, *this); 3965 3966 CheckObjCMethodOverride(newMethod, oldMethod); 3967 } 3968 3969 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3970 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3971 3972 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3973 ? diag::err_redefinition_different_type 3974 : diag::err_redeclaration_different_type) 3975 << New->getDeclName() << New->getType() << Old->getType(); 3976 3977 diag::kind PrevDiag; 3978 SourceLocation OldLocation; 3979 std::tie(PrevDiag, OldLocation) 3980 = getNoteDiagForInvalidRedeclaration(Old, New); 3981 S.Diag(OldLocation, PrevDiag); 3982 New->setInvalidDecl(); 3983 } 3984 3985 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3986 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3987 /// emitting diagnostics as appropriate. 3988 /// 3989 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3990 /// to here in AddInitializerToDecl. We can't check them before the initializer 3991 /// is attached. 3992 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3993 bool MergeTypeWithOld) { 3994 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3995 return; 3996 3997 QualType MergedT; 3998 if (getLangOpts().CPlusPlus) { 3999 if (New->getType()->isUndeducedType()) { 4000 // We don't know what the new type is until the initializer is attached. 4001 return; 4002 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4003 // These could still be something that needs exception specs checked. 4004 return MergeVarDeclExceptionSpecs(New, Old); 4005 } 4006 // C++ [basic.link]p10: 4007 // [...] the types specified by all declarations referring to a given 4008 // object or function shall be identical, except that declarations for an 4009 // array object can specify array types that differ by the presence or 4010 // absence of a major array bound (8.3.4). 4011 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4012 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4013 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4014 4015 // We are merging a variable declaration New into Old. If it has an array 4016 // bound, and that bound differs from Old's bound, we should diagnose the 4017 // mismatch. 4018 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4019 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4020 PrevVD = PrevVD->getPreviousDecl()) { 4021 QualType PrevVDTy = PrevVD->getType(); 4022 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4023 continue; 4024 4025 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4026 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4027 } 4028 } 4029 4030 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4031 if (Context.hasSameType(OldArray->getElementType(), 4032 NewArray->getElementType())) 4033 MergedT = New->getType(); 4034 } 4035 // FIXME: Check visibility. New is hidden but has a complete type. If New 4036 // has no array bound, it should not inherit one from Old, if Old is not 4037 // visible. 4038 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4039 if (Context.hasSameType(OldArray->getElementType(), 4040 NewArray->getElementType())) 4041 MergedT = Old->getType(); 4042 } 4043 } 4044 else if (New->getType()->isObjCObjectPointerType() && 4045 Old->getType()->isObjCObjectPointerType()) { 4046 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4047 Old->getType()); 4048 } 4049 } else { 4050 // C 6.2.7p2: 4051 // All declarations that refer to the same object or function shall have 4052 // compatible type. 4053 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4054 } 4055 if (MergedT.isNull()) { 4056 // It's OK if we couldn't merge types if either type is dependent, for a 4057 // block-scope variable. In other cases (static data members of class 4058 // templates, variable templates, ...), we require the types to be 4059 // equivalent. 4060 // FIXME: The C++ standard doesn't say anything about this. 4061 if ((New->getType()->isDependentType() || 4062 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4063 // If the old type was dependent, we can't merge with it, so the new type 4064 // becomes dependent for now. We'll reproduce the original type when we 4065 // instantiate the TypeSourceInfo for the variable. 4066 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4067 New->setType(Context.DependentTy); 4068 return; 4069 } 4070 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4071 } 4072 4073 // Don't actually update the type on the new declaration if the old 4074 // declaration was an extern declaration in a different scope. 4075 if (MergeTypeWithOld) 4076 New->setType(MergedT); 4077 } 4078 4079 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4080 LookupResult &Previous) { 4081 // C11 6.2.7p4: 4082 // For an identifier with internal or external linkage declared 4083 // in a scope in which a prior declaration of that identifier is 4084 // visible, if the prior declaration specifies internal or 4085 // external linkage, the type of the identifier at the later 4086 // declaration becomes the composite type. 4087 // 4088 // If the variable isn't visible, we do not merge with its type. 4089 if (Previous.isShadowed()) 4090 return false; 4091 4092 if (S.getLangOpts().CPlusPlus) { 4093 // C++11 [dcl.array]p3: 4094 // If there is a preceding declaration of the entity in the same 4095 // scope in which the bound was specified, an omitted array bound 4096 // is taken to be the same as in that earlier declaration. 4097 return NewVD->isPreviousDeclInSameBlockScope() || 4098 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4099 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4100 } else { 4101 // If the old declaration was function-local, don't merge with its 4102 // type unless we're in the same function. 4103 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4104 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4105 } 4106 } 4107 4108 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4109 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4110 /// situation, merging decls or emitting diagnostics as appropriate. 4111 /// 4112 /// Tentative definition rules (C99 6.9.2p2) are checked by 4113 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4114 /// definitions here, since the initializer hasn't been attached. 4115 /// 4116 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4117 // If the new decl is already invalid, don't do any other checking. 4118 if (New->isInvalidDecl()) 4119 return; 4120 4121 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4122 return; 4123 4124 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4125 4126 // Verify the old decl was also a variable or variable template. 4127 VarDecl *Old = nullptr; 4128 VarTemplateDecl *OldTemplate = nullptr; 4129 if (Previous.isSingleResult()) { 4130 if (NewTemplate) { 4131 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4132 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4133 4134 if (auto *Shadow = 4135 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4136 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4137 return New->setInvalidDecl(); 4138 } else { 4139 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4140 4141 if (auto *Shadow = 4142 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4143 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4144 return New->setInvalidDecl(); 4145 } 4146 } 4147 if (!Old) { 4148 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4149 << New->getDeclName(); 4150 notePreviousDefinition(Previous.getRepresentativeDecl(), 4151 New->getLocation()); 4152 return New->setInvalidDecl(); 4153 } 4154 4155 // If the old declaration was found in an inline namespace and the new 4156 // declaration was qualified, update the DeclContext to match. 4157 adjustDeclContextForDeclaratorDecl(New, Old); 4158 4159 // Ensure the template parameters are compatible. 4160 if (NewTemplate && 4161 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4162 OldTemplate->getTemplateParameters(), 4163 /*Complain=*/true, TPL_TemplateMatch)) 4164 return New->setInvalidDecl(); 4165 4166 // C++ [class.mem]p1: 4167 // A member shall not be declared twice in the member-specification [...] 4168 // 4169 // Here, we need only consider static data members. 4170 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4171 Diag(New->getLocation(), diag::err_duplicate_member) 4172 << New->getIdentifier(); 4173 Diag(Old->getLocation(), diag::note_previous_declaration); 4174 New->setInvalidDecl(); 4175 } 4176 4177 mergeDeclAttributes(New, Old); 4178 // Warn if an already-declared variable is made a weak_import in a subsequent 4179 // declaration 4180 if (New->hasAttr<WeakImportAttr>() && 4181 Old->getStorageClass() == SC_None && 4182 !Old->hasAttr<WeakImportAttr>()) { 4183 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4184 Diag(Old->getLocation(), diag::note_previous_declaration); 4185 // Remove weak_import attribute on new declaration. 4186 New->dropAttr<WeakImportAttr>(); 4187 } 4188 4189 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4190 if (!Old->hasAttr<InternalLinkageAttr>()) { 4191 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4192 << ILA; 4193 Diag(Old->getLocation(), diag::note_previous_declaration); 4194 New->dropAttr<InternalLinkageAttr>(); 4195 } 4196 4197 // Merge the types. 4198 VarDecl *MostRecent = Old->getMostRecentDecl(); 4199 if (MostRecent != Old) { 4200 MergeVarDeclTypes(New, MostRecent, 4201 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4202 if (New->isInvalidDecl()) 4203 return; 4204 } 4205 4206 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4207 if (New->isInvalidDecl()) 4208 return; 4209 4210 diag::kind PrevDiag; 4211 SourceLocation OldLocation; 4212 std::tie(PrevDiag, OldLocation) = 4213 getNoteDiagForInvalidRedeclaration(Old, New); 4214 4215 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4216 if (New->getStorageClass() == SC_Static && 4217 !New->isStaticDataMember() && 4218 Old->hasExternalFormalLinkage()) { 4219 if (getLangOpts().MicrosoftExt) { 4220 Diag(New->getLocation(), diag::ext_static_non_static) 4221 << New->getDeclName(); 4222 Diag(OldLocation, PrevDiag); 4223 } else { 4224 Diag(New->getLocation(), diag::err_static_non_static) 4225 << New->getDeclName(); 4226 Diag(OldLocation, PrevDiag); 4227 return New->setInvalidDecl(); 4228 } 4229 } 4230 // C99 6.2.2p4: 4231 // For an identifier declared with the storage-class specifier 4232 // extern in a scope in which a prior declaration of that 4233 // identifier is visible,23) if the prior declaration specifies 4234 // internal or external linkage, the linkage of the identifier at 4235 // the later declaration is the same as the linkage specified at 4236 // the prior declaration. If no prior declaration is visible, or 4237 // if the prior declaration specifies no linkage, then the 4238 // identifier has external linkage. 4239 if (New->hasExternalStorage() && Old->hasLinkage()) 4240 /* Okay */; 4241 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4242 !New->isStaticDataMember() && 4243 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4244 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4245 Diag(OldLocation, PrevDiag); 4246 return New->setInvalidDecl(); 4247 } 4248 4249 // Check if extern is followed by non-extern and vice-versa. 4250 if (New->hasExternalStorage() && 4251 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4252 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4253 Diag(OldLocation, PrevDiag); 4254 return New->setInvalidDecl(); 4255 } 4256 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4257 !New->hasExternalStorage()) { 4258 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4259 Diag(OldLocation, PrevDiag); 4260 return New->setInvalidDecl(); 4261 } 4262 4263 if (CheckRedeclarationModuleOwnership(New, Old)) 4264 return; 4265 4266 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4267 4268 // FIXME: The test for external storage here seems wrong? We still 4269 // need to check for mismatches. 4270 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4271 // Don't complain about out-of-line definitions of static members. 4272 !(Old->getLexicalDeclContext()->isRecord() && 4273 !New->getLexicalDeclContext()->isRecord())) { 4274 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4275 Diag(OldLocation, PrevDiag); 4276 return New->setInvalidDecl(); 4277 } 4278 4279 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4280 if (VarDecl *Def = Old->getDefinition()) { 4281 // C++1z [dcl.fcn.spec]p4: 4282 // If the definition of a variable appears in a translation unit before 4283 // its first declaration as inline, the program is ill-formed. 4284 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4285 Diag(Def->getLocation(), diag::note_previous_definition); 4286 } 4287 } 4288 4289 // If this redeclaration makes the variable inline, we may need to add it to 4290 // UndefinedButUsed. 4291 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4292 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4293 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4294 SourceLocation())); 4295 4296 if (New->getTLSKind() != Old->getTLSKind()) { 4297 if (!Old->getTLSKind()) { 4298 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4299 Diag(OldLocation, PrevDiag); 4300 } else if (!New->getTLSKind()) { 4301 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4302 Diag(OldLocation, PrevDiag); 4303 } else { 4304 // Do not allow redeclaration to change the variable between requiring 4305 // static and dynamic initialization. 4306 // FIXME: GCC allows this, but uses the TLS keyword on the first 4307 // declaration to determine the kind. Do we need to be compatible here? 4308 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4309 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4310 Diag(OldLocation, PrevDiag); 4311 } 4312 } 4313 4314 // C++ doesn't have tentative definitions, so go right ahead and check here. 4315 if (getLangOpts().CPlusPlus && 4316 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4317 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4318 Old->getCanonicalDecl()->isConstexpr()) { 4319 // This definition won't be a definition any more once it's been merged. 4320 Diag(New->getLocation(), 4321 diag::warn_deprecated_redundant_constexpr_static_def); 4322 } else if (VarDecl *Def = Old->getDefinition()) { 4323 if (checkVarDeclRedefinition(Def, New)) 4324 return; 4325 } 4326 } 4327 4328 if (haveIncompatibleLanguageLinkages(Old, New)) { 4329 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4330 Diag(OldLocation, PrevDiag); 4331 New->setInvalidDecl(); 4332 return; 4333 } 4334 4335 // Merge "used" flag. 4336 if (Old->getMostRecentDecl()->isUsed(false)) 4337 New->setIsUsed(); 4338 4339 // Keep a chain of previous declarations. 4340 New->setPreviousDecl(Old); 4341 if (NewTemplate) 4342 NewTemplate->setPreviousDecl(OldTemplate); 4343 4344 // Inherit access appropriately. 4345 New->setAccess(Old->getAccess()); 4346 if (NewTemplate) 4347 NewTemplate->setAccess(New->getAccess()); 4348 4349 if (Old->isInline()) 4350 New->setImplicitlyInline(); 4351 } 4352 4353 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4354 SourceManager &SrcMgr = getSourceManager(); 4355 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4356 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4357 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4358 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4359 auto &HSI = PP.getHeaderSearchInfo(); 4360 StringRef HdrFilename = 4361 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4362 4363 auto noteFromModuleOrInclude = [&](Module *Mod, 4364 SourceLocation IncLoc) -> bool { 4365 // Redefinition errors with modules are common with non modular mapped 4366 // headers, example: a non-modular header H in module A that also gets 4367 // included directly in a TU. Pointing twice to the same header/definition 4368 // is confusing, try to get better diagnostics when modules is on. 4369 if (IncLoc.isValid()) { 4370 if (Mod) { 4371 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4372 << HdrFilename.str() << Mod->getFullModuleName(); 4373 if (!Mod->DefinitionLoc.isInvalid()) 4374 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4375 << Mod->getFullModuleName(); 4376 } else { 4377 Diag(IncLoc, diag::note_redefinition_include_same_file) 4378 << HdrFilename.str(); 4379 } 4380 return true; 4381 } 4382 4383 return false; 4384 }; 4385 4386 // Is it the same file and same offset? Provide more information on why 4387 // this leads to a redefinition error. 4388 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4389 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4390 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4391 bool EmittedDiag = 4392 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4393 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4394 4395 // If the header has no guards, emit a note suggesting one. 4396 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4397 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4398 4399 if (EmittedDiag) 4400 return; 4401 } 4402 4403 // Redefinition coming from different files or couldn't do better above. 4404 if (Old->getLocation().isValid()) 4405 Diag(Old->getLocation(), diag::note_previous_definition); 4406 } 4407 4408 /// We've just determined that \p Old and \p New both appear to be definitions 4409 /// of the same variable. Either diagnose or fix the problem. 4410 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4411 if (!hasVisibleDefinition(Old) && 4412 (New->getFormalLinkage() == InternalLinkage || 4413 New->isInline() || 4414 New->getDescribedVarTemplate() || 4415 New->getNumTemplateParameterLists() || 4416 New->getDeclContext()->isDependentContext())) { 4417 // The previous definition is hidden, and multiple definitions are 4418 // permitted (in separate TUs). Demote this to a declaration. 4419 New->demoteThisDefinitionToDeclaration(); 4420 4421 // Make the canonical definition visible. 4422 if (auto *OldTD = Old->getDescribedVarTemplate()) 4423 makeMergedDefinitionVisible(OldTD); 4424 makeMergedDefinitionVisible(Old); 4425 return false; 4426 } else { 4427 Diag(New->getLocation(), diag::err_redefinition) << New; 4428 notePreviousDefinition(Old, New->getLocation()); 4429 New->setInvalidDecl(); 4430 return true; 4431 } 4432 } 4433 4434 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4435 /// no declarator (e.g. "struct foo;") is parsed. 4436 Decl * 4437 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4438 RecordDecl *&AnonRecord) { 4439 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4440 AnonRecord); 4441 } 4442 4443 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4444 // disambiguate entities defined in different scopes. 4445 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4446 // compatibility. 4447 // We will pick our mangling number depending on which version of MSVC is being 4448 // targeted. 4449 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4450 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4451 ? S->getMSCurManglingNumber() 4452 : S->getMSLastManglingNumber(); 4453 } 4454 4455 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4456 if (!Context.getLangOpts().CPlusPlus) 4457 return; 4458 4459 if (isa<CXXRecordDecl>(Tag->getParent())) { 4460 // If this tag is the direct child of a class, number it if 4461 // it is anonymous. 4462 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4463 return; 4464 MangleNumberingContext &MCtx = 4465 Context.getManglingNumberContext(Tag->getParent()); 4466 Context.setManglingNumber( 4467 Tag, MCtx.getManglingNumber( 4468 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4469 return; 4470 } 4471 4472 // If this tag isn't a direct child of a class, number it if it is local. 4473 MangleNumberingContext *MCtx; 4474 Decl *ManglingContextDecl; 4475 std::tie(MCtx, ManglingContextDecl) = 4476 getCurrentMangleNumberContext(Tag->getDeclContext()); 4477 if (MCtx) { 4478 Context.setManglingNumber( 4479 Tag, MCtx->getManglingNumber( 4480 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4481 } 4482 } 4483 4484 namespace { 4485 struct NonCLikeKind { 4486 enum { 4487 None, 4488 BaseClass, 4489 DefaultMemberInit, 4490 Lambda, 4491 Friend, 4492 OtherMember, 4493 Invalid, 4494 } Kind = None; 4495 SourceRange Range; 4496 4497 explicit operator bool() { return Kind != None; } 4498 }; 4499 } 4500 4501 /// Determine whether a class is C-like, according to the rules of C++ 4502 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4503 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4504 if (RD->isInvalidDecl()) 4505 return {NonCLikeKind::Invalid, {}}; 4506 4507 // C++ [dcl.typedef]p9: [P1766R1] 4508 // An unnamed class with a typedef name for linkage purposes shall not 4509 // 4510 // -- have any base classes 4511 if (RD->getNumBases()) 4512 return {NonCLikeKind::BaseClass, 4513 SourceRange(RD->bases_begin()->getBeginLoc(), 4514 RD->bases_end()[-1].getEndLoc())}; 4515 bool Invalid = false; 4516 for (Decl *D : RD->decls()) { 4517 // Don't complain about things we already diagnosed. 4518 if (D->isInvalidDecl()) { 4519 Invalid = true; 4520 continue; 4521 } 4522 4523 // -- have any [...] default member initializers 4524 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4525 if (FD->hasInClassInitializer()) { 4526 auto *Init = FD->getInClassInitializer(); 4527 return {NonCLikeKind::DefaultMemberInit, 4528 Init ? Init->getSourceRange() : D->getSourceRange()}; 4529 } 4530 continue; 4531 } 4532 4533 // FIXME: We don't allow friend declarations. This violates the wording of 4534 // P1766, but not the intent. 4535 if (isa<FriendDecl>(D)) 4536 return {NonCLikeKind::Friend, D->getSourceRange()}; 4537 4538 // -- declare any members other than non-static data members, member 4539 // enumerations, or member classes, 4540 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4541 isa<EnumDecl>(D)) 4542 continue; 4543 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4544 if (!MemberRD) { 4545 if (D->isImplicit()) 4546 continue; 4547 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4548 } 4549 4550 // -- contain a lambda-expression, 4551 if (MemberRD->isLambda()) 4552 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4553 4554 // and all member classes shall also satisfy these requirements 4555 // (recursively). 4556 if (MemberRD->isThisDeclarationADefinition()) { 4557 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4558 return Kind; 4559 } 4560 } 4561 4562 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4563 } 4564 4565 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4566 TypedefNameDecl *NewTD) { 4567 if (TagFromDeclSpec->isInvalidDecl()) 4568 return; 4569 4570 // Do nothing if the tag already has a name for linkage purposes. 4571 if (TagFromDeclSpec->hasNameForLinkage()) 4572 return; 4573 4574 // A well-formed anonymous tag must always be a TUK_Definition. 4575 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4576 4577 // The type must match the tag exactly; no qualifiers allowed. 4578 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4579 Context.getTagDeclType(TagFromDeclSpec))) { 4580 if (getLangOpts().CPlusPlus) 4581 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4582 return; 4583 } 4584 4585 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4586 // An unnamed class with a typedef name for linkage purposes shall [be 4587 // C-like]. 4588 // 4589 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4590 // shouldn't happen, but there are constructs that the language rule doesn't 4591 // disallow for which we can't reasonably avoid computing linkage early. 4592 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4593 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4594 : NonCLikeKind(); 4595 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4596 if (NonCLike || ChangesLinkage) { 4597 if (NonCLike.Kind == NonCLikeKind::Invalid) 4598 return; 4599 4600 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4601 if (ChangesLinkage) { 4602 // If the linkage changes, we can't accept this as an extension. 4603 if (NonCLike.Kind == NonCLikeKind::None) 4604 DiagID = diag::err_typedef_changes_linkage; 4605 else 4606 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4607 } 4608 4609 SourceLocation FixitLoc = 4610 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4611 llvm::SmallString<40> TextToInsert; 4612 TextToInsert += ' '; 4613 TextToInsert += NewTD->getIdentifier()->getName(); 4614 4615 Diag(FixitLoc, DiagID) 4616 << isa<TypeAliasDecl>(NewTD) 4617 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4618 if (NonCLike.Kind != NonCLikeKind::None) { 4619 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4620 << NonCLike.Kind - 1 << NonCLike.Range; 4621 } 4622 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4623 << NewTD << isa<TypeAliasDecl>(NewTD); 4624 4625 if (ChangesLinkage) 4626 return; 4627 } 4628 4629 // Otherwise, set this as the anon-decl typedef for the tag. 4630 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4631 } 4632 4633 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4634 switch (T) { 4635 case DeclSpec::TST_class: 4636 return 0; 4637 case DeclSpec::TST_struct: 4638 return 1; 4639 case DeclSpec::TST_interface: 4640 return 2; 4641 case DeclSpec::TST_union: 4642 return 3; 4643 case DeclSpec::TST_enum: 4644 return 4; 4645 default: 4646 llvm_unreachable("unexpected type specifier"); 4647 } 4648 } 4649 4650 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4651 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4652 /// parameters to cope with template friend declarations. 4653 Decl * 4654 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4655 MultiTemplateParamsArg TemplateParams, 4656 bool IsExplicitInstantiation, 4657 RecordDecl *&AnonRecord) { 4658 Decl *TagD = nullptr; 4659 TagDecl *Tag = nullptr; 4660 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4661 DS.getTypeSpecType() == DeclSpec::TST_struct || 4662 DS.getTypeSpecType() == DeclSpec::TST_interface || 4663 DS.getTypeSpecType() == DeclSpec::TST_union || 4664 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4665 TagD = DS.getRepAsDecl(); 4666 4667 if (!TagD) // We probably had an error 4668 return nullptr; 4669 4670 // Note that the above type specs guarantee that the 4671 // type rep is a Decl, whereas in many of the others 4672 // it's a Type. 4673 if (isa<TagDecl>(TagD)) 4674 Tag = cast<TagDecl>(TagD); 4675 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4676 Tag = CTD->getTemplatedDecl(); 4677 } 4678 4679 if (Tag) { 4680 handleTagNumbering(Tag, S); 4681 Tag->setFreeStanding(); 4682 if (Tag->isInvalidDecl()) 4683 return Tag; 4684 } 4685 4686 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4687 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4688 // or incomplete types shall not be restrict-qualified." 4689 if (TypeQuals & DeclSpec::TQ_restrict) 4690 Diag(DS.getRestrictSpecLoc(), 4691 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4692 << DS.getSourceRange(); 4693 } 4694 4695 if (DS.isInlineSpecified()) 4696 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4697 << getLangOpts().CPlusPlus17; 4698 4699 if (DS.hasConstexprSpecifier()) { 4700 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4701 // and definitions of functions and variables. 4702 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4703 // the declaration of a function or function template 4704 if (Tag) 4705 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4706 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4707 << static_cast<int>(DS.getConstexprSpecifier()); 4708 else 4709 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4710 << static_cast<int>(DS.getConstexprSpecifier()); 4711 // Don't emit warnings after this error. 4712 return TagD; 4713 } 4714 4715 DiagnoseFunctionSpecifiers(DS); 4716 4717 if (DS.isFriendSpecified()) { 4718 // If we're dealing with a decl but not a TagDecl, assume that 4719 // whatever routines created it handled the friendship aspect. 4720 if (TagD && !Tag) 4721 return nullptr; 4722 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4723 } 4724 4725 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4726 bool IsExplicitSpecialization = 4727 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4728 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4729 !IsExplicitInstantiation && !IsExplicitSpecialization && 4730 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4731 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4732 // nested-name-specifier unless it is an explicit instantiation 4733 // or an explicit specialization. 4734 // 4735 // FIXME: We allow class template partial specializations here too, per the 4736 // obvious intent of DR1819. 4737 // 4738 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4739 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4740 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4741 return nullptr; 4742 } 4743 4744 // Track whether this decl-specifier declares anything. 4745 bool DeclaresAnything = true; 4746 4747 // Handle anonymous struct definitions. 4748 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4749 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4750 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4751 if (getLangOpts().CPlusPlus || 4752 Record->getDeclContext()->isRecord()) { 4753 // If CurContext is a DeclContext that can contain statements, 4754 // RecursiveASTVisitor won't visit the decls that 4755 // BuildAnonymousStructOrUnion() will put into CurContext. 4756 // Also store them here so that they can be part of the 4757 // DeclStmt that gets created in this case. 4758 // FIXME: Also return the IndirectFieldDecls created by 4759 // BuildAnonymousStructOr union, for the same reason? 4760 if (CurContext->isFunctionOrMethod()) 4761 AnonRecord = Record; 4762 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4763 Context.getPrintingPolicy()); 4764 } 4765 4766 DeclaresAnything = false; 4767 } 4768 } 4769 4770 // C11 6.7.2.1p2: 4771 // A struct-declaration that does not declare an anonymous structure or 4772 // anonymous union shall contain a struct-declarator-list. 4773 // 4774 // This rule also existed in C89 and C99; the grammar for struct-declaration 4775 // did not permit a struct-declaration without a struct-declarator-list. 4776 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4777 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4778 // Check for Microsoft C extension: anonymous struct/union member. 4779 // Handle 2 kinds of anonymous struct/union: 4780 // struct STRUCT; 4781 // union UNION; 4782 // and 4783 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4784 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4785 if ((Tag && Tag->getDeclName()) || 4786 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4787 RecordDecl *Record = nullptr; 4788 if (Tag) 4789 Record = dyn_cast<RecordDecl>(Tag); 4790 else if (const RecordType *RT = 4791 DS.getRepAsType().get()->getAsStructureType()) 4792 Record = RT->getDecl(); 4793 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4794 Record = UT->getDecl(); 4795 4796 if (Record && getLangOpts().MicrosoftExt) { 4797 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4798 << Record->isUnion() << DS.getSourceRange(); 4799 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4800 } 4801 4802 DeclaresAnything = false; 4803 } 4804 } 4805 4806 // Skip all the checks below if we have a type error. 4807 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4808 (TagD && TagD->isInvalidDecl())) 4809 return TagD; 4810 4811 if (getLangOpts().CPlusPlus && 4812 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4813 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4814 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4815 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4816 DeclaresAnything = false; 4817 4818 if (!DS.isMissingDeclaratorOk()) { 4819 // Customize diagnostic for a typedef missing a name. 4820 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4821 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4822 << DS.getSourceRange(); 4823 else 4824 DeclaresAnything = false; 4825 } 4826 4827 if (DS.isModulePrivateSpecified() && 4828 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4829 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4830 << Tag->getTagKind() 4831 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4832 4833 ActOnDocumentableDecl(TagD); 4834 4835 // C 6.7/2: 4836 // A declaration [...] shall declare at least a declarator [...], a tag, 4837 // or the members of an enumeration. 4838 // C++ [dcl.dcl]p3: 4839 // [If there are no declarators], and except for the declaration of an 4840 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4841 // names into the program, or shall redeclare a name introduced by a 4842 // previous declaration. 4843 if (!DeclaresAnything) { 4844 // In C, we allow this as a (popular) extension / bug. Don't bother 4845 // producing further diagnostics for redundant qualifiers after this. 4846 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4847 ? diag::err_no_declarators 4848 : diag::ext_no_declarators) 4849 << DS.getSourceRange(); 4850 return TagD; 4851 } 4852 4853 // C++ [dcl.stc]p1: 4854 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4855 // init-declarator-list of the declaration shall not be empty. 4856 // C++ [dcl.fct.spec]p1: 4857 // If a cv-qualifier appears in a decl-specifier-seq, the 4858 // init-declarator-list of the declaration shall not be empty. 4859 // 4860 // Spurious qualifiers here appear to be valid in C. 4861 unsigned DiagID = diag::warn_standalone_specifier; 4862 if (getLangOpts().CPlusPlus) 4863 DiagID = diag::ext_standalone_specifier; 4864 4865 // Note that a linkage-specification sets a storage class, but 4866 // 'extern "C" struct foo;' is actually valid and not theoretically 4867 // useless. 4868 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4869 if (SCS == DeclSpec::SCS_mutable) 4870 // Since mutable is not a viable storage class specifier in C, there is 4871 // no reason to treat it as an extension. Instead, diagnose as an error. 4872 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4873 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4874 Diag(DS.getStorageClassSpecLoc(), DiagID) 4875 << DeclSpec::getSpecifierName(SCS); 4876 } 4877 4878 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4879 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4880 << DeclSpec::getSpecifierName(TSCS); 4881 if (DS.getTypeQualifiers()) { 4882 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4883 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4884 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4885 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4886 // Restrict is covered above. 4887 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4888 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4889 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4890 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4891 } 4892 4893 // Warn about ignored type attributes, for example: 4894 // __attribute__((aligned)) struct A; 4895 // Attributes should be placed after tag to apply to type declaration. 4896 if (!DS.getAttributes().empty()) { 4897 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4898 if (TypeSpecType == DeclSpec::TST_class || 4899 TypeSpecType == DeclSpec::TST_struct || 4900 TypeSpecType == DeclSpec::TST_interface || 4901 TypeSpecType == DeclSpec::TST_union || 4902 TypeSpecType == DeclSpec::TST_enum) { 4903 for (const ParsedAttr &AL : DS.getAttributes()) 4904 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4905 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4906 } 4907 } 4908 4909 return TagD; 4910 } 4911 4912 /// We are trying to inject an anonymous member into the given scope; 4913 /// check if there's an existing declaration that can't be overloaded. 4914 /// 4915 /// \return true if this is a forbidden redeclaration 4916 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4917 Scope *S, 4918 DeclContext *Owner, 4919 DeclarationName Name, 4920 SourceLocation NameLoc, 4921 bool IsUnion) { 4922 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4923 Sema::ForVisibleRedeclaration); 4924 if (!SemaRef.LookupName(R, S)) return false; 4925 4926 // Pick a representative declaration. 4927 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4928 assert(PrevDecl && "Expected a non-null Decl"); 4929 4930 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4931 return false; 4932 4933 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4934 << IsUnion << Name; 4935 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4936 4937 return true; 4938 } 4939 4940 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4941 /// anonymous struct or union AnonRecord into the owning context Owner 4942 /// and scope S. This routine will be invoked just after we realize 4943 /// that an unnamed union or struct is actually an anonymous union or 4944 /// struct, e.g., 4945 /// 4946 /// @code 4947 /// union { 4948 /// int i; 4949 /// float f; 4950 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4951 /// // f into the surrounding scope.x 4952 /// @endcode 4953 /// 4954 /// This routine is recursive, injecting the names of nested anonymous 4955 /// structs/unions into the owning context and scope as well. 4956 static bool 4957 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4958 RecordDecl *AnonRecord, AccessSpecifier AS, 4959 SmallVectorImpl<NamedDecl *> &Chaining) { 4960 bool Invalid = false; 4961 4962 // Look every FieldDecl and IndirectFieldDecl with a name. 4963 for (auto *D : AnonRecord->decls()) { 4964 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4965 cast<NamedDecl>(D)->getDeclName()) { 4966 ValueDecl *VD = cast<ValueDecl>(D); 4967 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4968 VD->getLocation(), 4969 AnonRecord->isUnion())) { 4970 // C++ [class.union]p2: 4971 // The names of the members of an anonymous union shall be 4972 // distinct from the names of any other entity in the 4973 // scope in which the anonymous union is declared. 4974 Invalid = true; 4975 } else { 4976 // C++ [class.union]p2: 4977 // For the purpose of name lookup, after the anonymous union 4978 // definition, the members of the anonymous union are 4979 // considered to have been defined in the scope in which the 4980 // anonymous union is declared. 4981 unsigned OldChainingSize = Chaining.size(); 4982 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4983 Chaining.append(IF->chain_begin(), IF->chain_end()); 4984 else 4985 Chaining.push_back(VD); 4986 4987 assert(Chaining.size() >= 2); 4988 NamedDecl **NamedChain = 4989 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4990 for (unsigned i = 0; i < Chaining.size(); i++) 4991 NamedChain[i] = Chaining[i]; 4992 4993 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4994 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4995 VD->getType(), {NamedChain, Chaining.size()}); 4996 4997 for (const auto *Attr : VD->attrs()) 4998 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4999 5000 IndirectField->setAccess(AS); 5001 IndirectField->setImplicit(); 5002 SemaRef.PushOnScopeChains(IndirectField, S); 5003 5004 // That includes picking up the appropriate access specifier. 5005 if (AS != AS_none) IndirectField->setAccess(AS); 5006 5007 Chaining.resize(OldChainingSize); 5008 } 5009 } 5010 } 5011 5012 return Invalid; 5013 } 5014 5015 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5016 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5017 /// illegal input values are mapped to SC_None. 5018 static StorageClass 5019 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5020 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5021 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5022 "Parser allowed 'typedef' as storage class VarDecl."); 5023 switch (StorageClassSpec) { 5024 case DeclSpec::SCS_unspecified: return SC_None; 5025 case DeclSpec::SCS_extern: 5026 if (DS.isExternInLinkageSpec()) 5027 return SC_None; 5028 return SC_Extern; 5029 case DeclSpec::SCS_static: return SC_Static; 5030 case DeclSpec::SCS_auto: return SC_Auto; 5031 case DeclSpec::SCS_register: return SC_Register; 5032 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5033 // Illegal SCSs map to None: error reporting is up to the caller. 5034 case DeclSpec::SCS_mutable: // Fall through. 5035 case DeclSpec::SCS_typedef: return SC_None; 5036 } 5037 llvm_unreachable("unknown storage class specifier"); 5038 } 5039 5040 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5041 assert(Record->hasInClassInitializer()); 5042 5043 for (const auto *I : Record->decls()) { 5044 const auto *FD = dyn_cast<FieldDecl>(I); 5045 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5046 FD = IFD->getAnonField(); 5047 if (FD && FD->hasInClassInitializer()) 5048 return FD->getLocation(); 5049 } 5050 5051 llvm_unreachable("couldn't find in-class initializer"); 5052 } 5053 5054 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5055 SourceLocation DefaultInitLoc) { 5056 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5057 return; 5058 5059 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5060 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5061 } 5062 5063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5064 CXXRecordDecl *AnonUnion) { 5065 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5066 return; 5067 5068 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5069 } 5070 5071 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5072 /// anonymous structure or union. Anonymous unions are a C++ feature 5073 /// (C++ [class.union]) and a C11 feature; anonymous structures 5074 /// are a C11 feature and GNU C++ extension. 5075 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5076 AccessSpecifier AS, 5077 RecordDecl *Record, 5078 const PrintingPolicy &Policy) { 5079 DeclContext *Owner = Record->getDeclContext(); 5080 5081 // Diagnose whether this anonymous struct/union is an extension. 5082 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5083 Diag(Record->getLocation(), diag::ext_anonymous_union); 5084 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5085 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5086 else if (!Record->isUnion() && !getLangOpts().C11) 5087 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5088 5089 // C and C++ require different kinds of checks for anonymous 5090 // structs/unions. 5091 bool Invalid = false; 5092 if (getLangOpts().CPlusPlus) { 5093 const char *PrevSpec = nullptr; 5094 if (Record->isUnion()) { 5095 // C++ [class.union]p6: 5096 // C++17 [class.union.anon]p2: 5097 // Anonymous unions declared in a named namespace or in the 5098 // global namespace shall be declared static. 5099 unsigned DiagID; 5100 DeclContext *OwnerScope = Owner->getRedeclContext(); 5101 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5102 (OwnerScope->isTranslationUnit() || 5103 (OwnerScope->isNamespace() && 5104 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5105 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5106 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5107 5108 // Recover by adding 'static'. 5109 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5110 PrevSpec, DiagID, Policy); 5111 } 5112 // C++ [class.union]p6: 5113 // A storage class is not allowed in a declaration of an 5114 // anonymous union in a class scope. 5115 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5116 isa<RecordDecl>(Owner)) { 5117 Diag(DS.getStorageClassSpecLoc(), 5118 diag::err_anonymous_union_with_storage_spec) 5119 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5120 5121 // Recover by removing the storage specifier. 5122 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5123 SourceLocation(), 5124 PrevSpec, DiagID, Context.getPrintingPolicy()); 5125 } 5126 } 5127 5128 // Ignore const/volatile/restrict qualifiers. 5129 if (DS.getTypeQualifiers()) { 5130 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5131 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5132 << Record->isUnion() << "const" 5133 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5134 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5135 Diag(DS.getVolatileSpecLoc(), 5136 diag::ext_anonymous_struct_union_qualified) 5137 << Record->isUnion() << "volatile" 5138 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5139 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5140 Diag(DS.getRestrictSpecLoc(), 5141 diag::ext_anonymous_struct_union_qualified) 5142 << Record->isUnion() << "restrict" 5143 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5144 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5145 Diag(DS.getAtomicSpecLoc(), 5146 diag::ext_anonymous_struct_union_qualified) 5147 << Record->isUnion() << "_Atomic" 5148 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5149 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5150 Diag(DS.getUnalignedSpecLoc(), 5151 diag::ext_anonymous_struct_union_qualified) 5152 << Record->isUnion() << "__unaligned" 5153 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5154 5155 DS.ClearTypeQualifiers(); 5156 } 5157 5158 // C++ [class.union]p2: 5159 // The member-specification of an anonymous union shall only 5160 // define non-static data members. [Note: nested types and 5161 // functions cannot be declared within an anonymous union. ] 5162 for (auto *Mem : Record->decls()) { 5163 // Ignore invalid declarations; we already diagnosed them. 5164 if (Mem->isInvalidDecl()) 5165 continue; 5166 5167 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5168 // C++ [class.union]p3: 5169 // An anonymous union shall not have private or protected 5170 // members (clause 11). 5171 assert(FD->getAccess() != AS_none); 5172 if (FD->getAccess() != AS_public) { 5173 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5174 << Record->isUnion() << (FD->getAccess() == AS_protected); 5175 Invalid = true; 5176 } 5177 5178 // C++ [class.union]p1 5179 // An object of a class with a non-trivial constructor, a non-trivial 5180 // copy constructor, a non-trivial destructor, or a non-trivial copy 5181 // assignment operator cannot be a member of a union, nor can an 5182 // array of such objects. 5183 if (CheckNontrivialField(FD)) 5184 Invalid = true; 5185 } else if (Mem->isImplicit()) { 5186 // Any implicit members are fine. 5187 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5188 // This is a type that showed up in an 5189 // elaborated-type-specifier inside the anonymous struct or 5190 // union, but which actually declares a type outside of the 5191 // anonymous struct or union. It's okay. 5192 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5193 if (!MemRecord->isAnonymousStructOrUnion() && 5194 MemRecord->getDeclName()) { 5195 // Visual C++ allows type definition in anonymous struct or union. 5196 if (getLangOpts().MicrosoftExt) 5197 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5198 << Record->isUnion(); 5199 else { 5200 // This is a nested type declaration. 5201 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5202 << Record->isUnion(); 5203 Invalid = true; 5204 } 5205 } else { 5206 // This is an anonymous type definition within another anonymous type. 5207 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5208 // not part of standard C++. 5209 Diag(MemRecord->getLocation(), 5210 diag::ext_anonymous_record_with_anonymous_type) 5211 << Record->isUnion(); 5212 } 5213 } else if (isa<AccessSpecDecl>(Mem)) { 5214 // Any access specifier is fine. 5215 } else if (isa<StaticAssertDecl>(Mem)) { 5216 // In C++1z, static_assert declarations are also fine. 5217 } else { 5218 // We have something that isn't a non-static data 5219 // member. Complain about it. 5220 unsigned DK = diag::err_anonymous_record_bad_member; 5221 if (isa<TypeDecl>(Mem)) 5222 DK = diag::err_anonymous_record_with_type; 5223 else if (isa<FunctionDecl>(Mem)) 5224 DK = diag::err_anonymous_record_with_function; 5225 else if (isa<VarDecl>(Mem)) 5226 DK = diag::err_anonymous_record_with_static; 5227 5228 // Visual C++ allows type definition in anonymous struct or union. 5229 if (getLangOpts().MicrosoftExt && 5230 DK == diag::err_anonymous_record_with_type) 5231 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5232 << Record->isUnion(); 5233 else { 5234 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5235 Invalid = true; 5236 } 5237 } 5238 } 5239 5240 // C++11 [class.union]p8 (DR1460): 5241 // At most one variant member of a union may have a 5242 // brace-or-equal-initializer. 5243 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5244 Owner->isRecord()) 5245 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5246 cast<CXXRecordDecl>(Record)); 5247 } 5248 5249 if (!Record->isUnion() && !Owner->isRecord()) { 5250 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5251 << getLangOpts().CPlusPlus; 5252 Invalid = true; 5253 } 5254 5255 // C++ [dcl.dcl]p3: 5256 // [If there are no declarators], and except for the declaration of an 5257 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5258 // names into the program 5259 // C++ [class.mem]p2: 5260 // each such member-declaration shall either declare at least one member 5261 // name of the class or declare at least one unnamed bit-field 5262 // 5263 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5264 if (getLangOpts().CPlusPlus && Record->field_empty()) 5265 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5266 5267 // Mock up a declarator. 5268 Declarator Dc(DS, DeclaratorContext::Member); 5269 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5270 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5271 5272 // Create a declaration for this anonymous struct/union. 5273 NamedDecl *Anon = nullptr; 5274 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5275 Anon = FieldDecl::Create( 5276 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5277 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5278 /*BitWidth=*/nullptr, /*Mutable=*/false, 5279 /*InitStyle=*/ICIS_NoInit); 5280 Anon->setAccess(AS); 5281 ProcessDeclAttributes(S, Anon, Dc); 5282 5283 if (getLangOpts().CPlusPlus) 5284 FieldCollector->Add(cast<FieldDecl>(Anon)); 5285 } else { 5286 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5287 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5288 if (SCSpec == DeclSpec::SCS_mutable) { 5289 // mutable can only appear on non-static class members, so it's always 5290 // an error here 5291 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5292 Invalid = true; 5293 SC = SC_None; 5294 } 5295 5296 assert(DS.getAttributes().empty() && "No attribute expected"); 5297 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5298 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5299 Context.getTypeDeclType(Record), TInfo, SC); 5300 5301 // Default-initialize the implicit variable. This initialization will be 5302 // trivial in almost all cases, except if a union member has an in-class 5303 // initializer: 5304 // union { int n = 0; }; 5305 ActOnUninitializedDecl(Anon); 5306 } 5307 Anon->setImplicit(); 5308 5309 // Mark this as an anonymous struct/union type. 5310 Record->setAnonymousStructOrUnion(true); 5311 5312 // Add the anonymous struct/union object to the current 5313 // context. We'll be referencing this object when we refer to one of 5314 // its members. 5315 Owner->addDecl(Anon); 5316 5317 // Inject the members of the anonymous struct/union into the owning 5318 // context and into the identifier resolver chain for name lookup 5319 // purposes. 5320 SmallVector<NamedDecl*, 2> Chain; 5321 Chain.push_back(Anon); 5322 5323 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5324 Invalid = true; 5325 5326 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5327 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5328 MangleNumberingContext *MCtx; 5329 Decl *ManglingContextDecl; 5330 std::tie(MCtx, ManglingContextDecl) = 5331 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5332 if (MCtx) { 5333 Context.setManglingNumber( 5334 NewVD, MCtx->getManglingNumber( 5335 NewVD, getMSManglingNumber(getLangOpts(), S))); 5336 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5337 } 5338 } 5339 } 5340 5341 if (Invalid) 5342 Anon->setInvalidDecl(); 5343 5344 return Anon; 5345 } 5346 5347 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5348 /// Microsoft C anonymous structure. 5349 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5350 /// Example: 5351 /// 5352 /// struct A { int a; }; 5353 /// struct B { struct A; int b; }; 5354 /// 5355 /// void foo() { 5356 /// B var; 5357 /// var.a = 3; 5358 /// } 5359 /// 5360 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5361 RecordDecl *Record) { 5362 assert(Record && "expected a record!"); 5363 5364 // Mock up a declarator. 5365 Declarator Dc(DS, DeclaratorContext::TypeName); 5366 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5367 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5368 5369 auto *ParentDecl = cast<RecordDecl>(CurContext); 5370 QualType RecTy = Context.getTypeDeclType(Record); 5371 5372 // Create a declaration for this anonymous struct. 5373 NamedDecl *Anon = 5374 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5375 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5376 /*BitWidth=*/nullptr, /*Mutable=*/false, 5377 /*InitStyle=*/ICIS_NoInit); 5378 Anon->setImplicit(); 5379 5380 // Add the anonymous struct object to the current context. 5381 CurContext->addDecl(Anon); 5382 5383 // Inject the members of the anonymous struct into the current 5384 // context and into the identifier resolver chain for name lookup 5385 // purposes. 5386 SmallVector<NamedDecl*, 2> Chain; 5387 Chain.push_back(Anon); 5388 5389 RecordDecl *RecordDef = Record->getDefinition(); 5390 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5391 diag::err_field_incomplete_or_sizeless) || 5392 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5393 AS_none, Chain)) { 5394 Anon->setInvalidDecl(); 5395 ParentDecl->setInvalidDecl(); 5396 } 5397 5398 return Anon; 5399 } 5400 5401 /// GetNameForDeclarator - Determine the full declaration name for the 5402 /// given Declarator. 5403 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5404 return GetNameFromUnqualifiedId(D.getName()); 5405 } 5406 5407 /// Retrieves the declaration name from a parsed unqualified-id. 5408 DeclarationNameInfo 5409 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5410 DeclarationNameInfo NameInfo; 5411 NameInfo.setLoc(Name.StartLocation); 5412 5413 switch (Name.getKind()) { 5414 5415 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5416 case UnqualifiedIdKind::IK_Identifier: 5417 NameInfo.setName(Name.Identifier); 5418 return NameInfo; 5419 5420 case UnqualifiedIdKind::IK_DeductionGuideName: { 5421 // C++ [temp.deduct.guide]p3: 5422 // The simple-template-id shall name a class template specialization. 5423 // The template-name shall be the same identifier as the template-name 5424 // of the simple-template-id. 5425 // These together intend to imply that the template-name shall name a 5426 // class template. 5427 // FIXME: template<typename T> struct X {}; 5428 // template<typename T> using Y = X<T>; 5429 // Y(int) -> Y<int>; 5430 // satisfies these rules but does not name a class template. 5431 TemplateName TN = Name.TemplateName.get().get(); 5432 auto *Template = TN.getAsTemplateDecl(); 5433 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5434 Diag(Name.StartLocation, 5435 diag::err_deduction_guide_name_not_class_template) 5436 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5437 if (Template) 5438 Diag(Template->getLocation(), diag::note_template_decl_here); 5439 return DeclarationNameInfo(); 5440 } 5441 5442 NameInfo.setName( 5443 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5444 return NameInfo; 5445 } 5446 5447 case UnqualifiedIdKind::IK_OperatorFunctionId: 5448 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5449 Name.OperatorFunctionId.Operator)); 5450 NameInfo.setCXXOperatorNameRange(SourceRange( 5451 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5452 return NameInfo; 5453 5454 case UnqualifiedIdKind::IK_LiteralOperatorId: 5455 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5456 Name.Identifier)); 5457 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5458 return NameInfo; 5459 5460 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5461 TypeSourceInfo *TInfo; 5462 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5463 if (Ty.isNull()) 5464 return DeclarationNameInfo(); 5465 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5466 Context.getCanonicalType(Ty))); 5467 NameInfo.setNamedTypeInfo(TInfo); 5468 return NameInfo; 5469 } 5470 5471 case UnqualifiedIdKind::IK_ConstructorName: { 5472 TypeSourceInfo *TInfo; 5473 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5474 if (Ty.isNull()) 5475 return DeclarationNameInfo(); 5476 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5477 Context.getCanonicalType(Ty))); 5478 NameInfo.setNamedTypeInfo(TInfo); 5479 return NameInfo; 5480 } 5481 5482 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5483 // In well-formed code, we can only have a constructor 5484 // template-id that refers to the current context, so go there 5485 // to find the actual type being constructed. 5486 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5487 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5488 return DeclarationNameInfo(); 5489 5490 // Determine the type of the class being constructed. 5491 QualType CurClassType = Context.getTypeDeclType(CurClass); 5492 5493 // FIXME: Check two things: that the template-id names the same type as 5494 // CurClassType, and that the template-id does not occur when the name 5495 // was qualified. 5496 5497 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5498 Context.getCanonicalType(CurClassType))); 5499 // FIXME: should we retrieve TypeSourceInfo? 5500 NameInfo.setNamedTypeInfo(nullptr); 5501 return NameInfo; 5502 } 5503 5504 case UnqualifiedIdKind::IK_DestructorName: { 5505 TypeSourceInfo *TInfo; 5506 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5507 if (Ty.isNull()) 5508 return DeclarationNameInfo(); 5509 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5510 Context.getCanonicalType(Ty))); 5511 NameInfo.setNamedTypeInfo(TInfo); 5512 return NameInfo; 5513 } 5514 5515 case UnqualifiedIdKind::IK_TemplateId: { 5516 TemplateName TName = Name.TemplateId->Template.get(); 5517 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5518 return Context.getNameForTemplate(TName, TNameLoc); 5519 } 5520 5521 } // switch (Name.getKind()) 5522 5523 llvm_unreachable("Unknown name kind"); 5524 } 5525 5526 static QualType getCoreType(QualType Ty) { 5527 do { 5528 if (Ty->isPointerType() || Ty->isReferenceType()) 5529 Ty = Ty->getPointeeType(); 5530 else if (Ty->isArrayType()) 5531 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5532 else 5533 return Ty.withoutLocalFastQualifiers(); 5534 } while (true); 5535 } 5536 5537 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5538 /// and Definition have "nearly" matching parameters. This heuristic is 5539 /// used to improve diagnostics in the case where an out-of-line function 5540 /// definition doesn't match any declaration within the class or namespace. 5541 /// Also sets Params to the list of indices to the parameters that differ 5542 /// between the declaration and the definition. If hasSimilarParameters 5543 /// returns true and Params is empty, then all of the parameters match. 5544 static bool hasSimilarParameters(ASTContext &Context, 5545 FunctionDecl *Declaration, 5546 FunctionDecl *Definition, 5547 SmallVectorImpl<unsigned> &Params) { 5548 Params.clear(); 5549 if (Declaration->param_size() != Definition->param_size()) 5550 return false; 5551 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5552 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5553 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5554 5555 // The parameter types are identical 5556 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5557 continue; 5558 5559 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5560 QualType DefParamBaseTy = getCoreType(DefParamTy); 5561 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5562 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5563 5564 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5565 (DeclTyName && DeclTyName == DefTyName)) 5566 Params.push_back(Idx); 5567 else // The two parameters aren't even close 5568 return false; 5569 } 5570 5571 return true; 5572 } 5573 5574 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5575 /// declarator needs to be rebuilt in the current instantiation. 5576 /// Any bits of declarator which appear before the name are valid for 5577 /// consideration here. That's specifically the type in the decl spec 5578 /// and the base type in any member-pointer chunks. 5579 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5580 DeclarationName Name) { 5581 // The types we specifically need to rebuild are: 5582 // - typenames, typeofs, and decltypes 5583 // - types which will become injected class names 5584 // Of course, we also need to rebuild any type referencing such a 5585 // type. It's safest to just say "dependent", but we call out a 5586 // few cases here. 5587 5588 DeclSpec &DS = D.getMutableDeclSpec(); 5589 switch (DS.getTypeSpecType()) { 5590 case DeclSpec::TST_typename: 5591 case DeclSpec::TST_typeofType: 5592 case DeclSpec::TST_underlyingType: 5593 case DeclSpec::TST_atomic: { 5594 // Grab the type from the parser. 5595 TypeSourceInfo *TSI = nullptr; 5596 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5597 if (T.isNull() || !T->isInstantiationDependentType()) break; 5598 5599 // Make sure there's a type source info. This isn't really much 5600 // of a waste; most dependent types should have type source info 5601 // attached already. 5602 if (!TSI) 5603 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5604 5605 // Rebuild the type in the current instantiation. 5606 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5607 if (!TSI) return true; 5608 5609 // Store the new type back in the decl spec. 5610 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5611 DS.UpdateTypeRep(LocType); 5612 break; 5613 } 5614 5615 case DeclSpec::TST_decltype: 5616 case DeclSpec::TST_typeofExpr: { 5617 Expr *E = DS.getRepAsExpr(); 5618 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5619 if (Result.isInvalid()) return true; 5620 DS.UpdateExprRep(Result.get()); 5621 break; 5622 } 5623 5624 default: 5625 // Nothing to do for these decl specs. 5626 break; 5627 } 5628 5629 // It doesn't matter what order we do this in. 5630 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5631 DeclaratorChunk &Chunk = D.getTypeObject(I); 5632 5633 // The only type information in the declarator which can come 5634 // before the declaration name is the base type of a member 5635 // pointer. 5636 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5637 continue; 5638 5639 // Rebuild the scope specifier in-place. 5640 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5641 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5642 return true; 5643 } 5644 5645 return false; 5646 } 5647 5648 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5649 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5650 // of system decl. 5651 if (D->getPreviousDecl() || D->isImplicit()) 5652 return; 5653 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5654 if (Status != ReservedIdentifierStatus::NotReserved && 5655 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5656 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5657 << D << static_cast<int>(Status); 5658 } 5659 5660 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5661 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5662 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5663 5664 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5665 Dcl && Dcl->getDeclContext()->isFileContext()) 5666 Dcl->setTopLevelDeclInObjCContainer(); 5667 5668 return Dcl; 5669 } 5670 5671 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5672 /// If T is the name of a class, then each of the following shall have a 5673 /// name different from T: 5674 /// - every static data member of class T; 5675 /// - every member function of class T 5676 /// - every member of class T that is itself a type; 5677 /// \returns true if the declaration name violates these rules. 5678 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5679 DeclarationNameInfo NameInfo) { 5680 DeclarationName Name = NameInfo.getName(); 5681 5682 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5683 while (Record && Record->isAnonymousStructOrUnion()) 5684 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5685 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5686 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5687 return true; 5688 } 5689 5690 return false; 5691 } 5692 5693 /// Diagnose a declaration whose declarator-id has the given 5694 /// nested-name-specifier. 5695 /// 5696 /// \param SS The nested-name-specifier of the declarator-id. 5697 /// 5698 /// \param DC The declaration context to which the nested-name-specifier 5699 /// resolves. 5700 /// 5701 /// \param Name The name of the entity being declared. 5702 /// 5703 /// \param Loc The location of the name of the entity being declared. 5704 /// 5705 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5706 /// we're declaring an explicit / partial specialization / instantiation. 5707 /// 5708 /// \returns true if we cannot safely recover from this error, false otherwise. 5709 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5710 DeclarationName Name, 5711 SourceLocation Loc, bool IsTemplateId) { 5712 DeclContext *Cur = CurContext; 5713 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5714 Cur = Cur->getParent(); 5715 5716 // If the user provided a superfluous scope specifier that refers back to the 5717 // class in which the entity is already declared, diagnose and ignore it. 5718 // 5719 // class X { 5720 // void X::f(); 5721 // }; 5722 // 5723 // Note, it was once ill-formed to give redundant qualification in all 5724 // contexts, but that rule was removed by DR482. 5725 if (Cur->Equals(DC)) { 5726 if (Cur->isRecord()) { 5727 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5728 : diag::err_member_extra_qualification) 5729 << Name << FixItHint::CreateRemoval(SS.getRange()); 5730 SS.clear(); 5731 } else { 5732 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5733 } 5734 return false; 5735 } 5736 5737 // Check whether the qualifying scope encloses the scope of the original 5738 // declaration. For a template-id, we perform the checks in 5739 // CheckTemplateSpecializationScope. 5740 if (!Cur->Encloses(DC) && !IsTemplateId) { 5741 if (Cur->isRecord()) 5742 Diag(Loc, diag::err_member_qualification) 5743 << Name << SS.getRange(); 5744 else if (isa<TranslationUnitDecl>(DC)) 5745 Diag(Loc, diag::err_invalid_declarator_global_scope) 5746 << Name << SS.getRange(); 5747 else if (isa<FunctionDecl>(Cur)) 5748 Diag(Loc, diag::err_invalid_declarator_in_function) 5749 << Name << SS.getRange(); 5750 else if (isa<BlockDecl>(Cur)) 5751 Diag(Loc, diag::err_invalid_declarator_in_block) 5752 << Name << SS.getRange(); 5753 else 5754 Diag(Loc, diag::err_invalid_declarator_scope) 5755 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5756 5757 return true; 5758 } 5759 5760 if (Cur->isRecord()) { 5761 // Cannot qualify members within a class. 5762 Diag(Loc, diag::err_member_qualification) 5763 << Name << SS.getRange(); 5764 SS.clear(); 5765 5766 // C++ constructors and destructors with incorrect scopes can break 5767 // our AST invariants by having the wrong underlying types. If 5768 // that's the case, then drop this declaration entirely. 5769 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5770 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5771 !Context.hasSameType(Name.getCXXNameType(), 5772 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5773 return true; 5774 5775 return false; 5776 } 5777 5778 // C++11 [dcl.meaning]p1: 5779 // [...] "The nested-name-specifier of the qualified declarator-id shall 5780 // not begin with a decltype-specifer" 5781 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5782 while (SpecLoc.getPrefix()) 5783 SpecLoc = SpecLoc.getPrefix(); 5784 if (isa_and_nonnull<DecltypeType>( 5785 SpecLoc.getNestedNameSpecifier()->getAsType())) 5786 Diag(Loc, diag::err_decltype_in_declarator) 5787 << SpecLoc.getTypeLoc().getSourceRange(); 5788 5789 return false; 5790 } 5791 5792 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5793 MultiTemplateParamsArg TemplateParamLists) { 5794 // TODO: consider using NameInfo for diagnostic. 5795 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5796 DeclarationName Name = NameInfo.getName(); 5797 5798 // All of these full declarators require an identifier. If it doesn't have 5799 // one, the ParsedFreeStandingDeclSpec action should be used. 5800 if (D.isDecompositionDeclarator()) { 5801 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5802 } else if (!Name) { 5803 if (!D.isInvalidType()) // Reject this if we think it is valid. 5804 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5805 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5806 return nullptr; 5807 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5808 return nullptr; 5809 5810 // The scope passed in may not be a decl scope. Zip up the scope tree until 5811 // we find one that is. 5812 while ((S->getFlags() & Scope::DeclScope) == 0 || 5813 (S->getFlags() & Scope::TemplateParamScope) != 0) 5814 S = S->getParent(); 5815 5816 DeclContext *DC = CurContext; 5817 if (D.getCXXScopeSpec().isInvalid()) 5818 D.setInvalidType(); 5819 else if (D.getCXXScopeSpec().isSet()) { 5820 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5821 UPPC_DeclarationQualifier)) 5822 return nullptr; 5823 5824 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5825 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5826 if (!DC || isa<EnumDecl>(DC)) { 5827 // If we could not compute the declaration context, it's because the 5828 // declaration context is dependent but does not refer to a class, 5829 // class template, or class template partial specialization. Complain 5830 // and return early, to avoid the coming semantic disaster. 5831 Diag(D.getIdentifierLoc(), 5832 diag::err_template_qualified_declarator_no_match) 5833 << D.getCXXScopeSpec().getScopeRep() 5834 << D.getCXXScopeSpec().getRange(); 5835 return nullptr; 5836 } 5837 bool IsDependentContext = DC->isDependentContext(); 5838 5839 if (!IsDependentContext && 5840 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5841 return nullptr; 5842 5843 // If a class is incomplete, do not parse entities inside it. 5844 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5845 Diag(D.getIdentifierLoc(), 5846 diag::err_member_def_undefined_record) 5847 << Name << DC << D.getCXXScopeSpec().getRange(); 5848 return nullptr; 5849 } 5850 if (!D.getDeclSpec().isFriendSpecified()) { 5851 if (diagnoseQualifiedDeclaration( 5852 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5853 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5854 if (DC->isRecord()) 5855 return nullptr; 5856 5857 D.setInvalidType(); 5858 } 5859 } 5860 5861 // Check whether we need to rebuild the type of the given 5862 // declaration in the current instantiation. 5863 if (EnteringContext && IsDependentContext && 5864 TemplateParamLists.size() != 0) { 5865 ContextRAII SavedContext(*this, DC); 5866 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5867 D.setInvalidType(); 5868 } 5869 } 5870 5871 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5872 QualType R = TInfo->getType(); 5873 5874 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5875 UPPC_DeclarationType)) 5876 D.setInvalidType(); 5877 5878 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5879 forRedeclarationInCurContext()); 5880 5881 // See if this is a redefinition of a variable in the same scope. 5882 if (!D.getCXXScopeSpec().isSet()) { 5883 bool IsLinkageLookup = false; 5884 bool CreateBuiltins = false; 5885 5886 // If the declaration we're planning to build will be a function 5887 // or object with linkage, then look for another declaration with 5888 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5889 // 5890 // If the declaration we're planning to build will be declared with 5891 // external linkage in the translation unit, create any builtin with 5892 // the same name. 5893 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5894 /* Do nothing*/; 5895 else if (CurContext->isFunctionOrMethod() && 5896 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5897 R->isFunctionType())) { 5898 IsLinkageLookup = true; 5899 CreateBuiltins = 5900 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5901 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5902 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5903 CreateBuiltins = true; 5904 5905 if (IsLinkageLookup) { 5906 Previous.clear(LookupRedeclarationWithLinkage); 5907 Previous.setRedeclarationKind(ForExternalRedeclaration); 5908 } 5909 5910 LookupName(Previous, S, CreateBuiltins); 5911 } else { // Something like "int foo::x;" 5912 LookupQualifiedName(Previous, DC); 5913 5914 // C++ [dcl.meaning]p1: 5915 // When the declarator-id is qualified, the declaration shall refer to a 5916 // previously declared member of the class or namespace to which the 5917 // qualifier refers (or, in the case of a namespace, of an element of the 5918 // inline namespace set of that namespace (7.3.1)) or to a specialization 5919 // thereof; [...] 5920 // 5921 // Note that we already checked the context above, and that we do not have 5922 // enough information to make sure that Previous contains the declaration 5923 // we want to match. For example, given: 5924 // 5925 // class X { 5926 // void f(); 5927 // void f(float); 5928 // }; 5929 // 5930 // void X::f(int) { } // ill-formed 5931 // 5932 // In this case, Previous will point to the overload set 5933 // containing the two f's declared in X, but neither of them 5934 // matches. 5935 5936 // C++ [dcl.meaning]p1: 5937 // [...] the member shall not merely have been introduced by a 5938 // using-declaration in the scope of the class or namespace nominated by 5939 // the nested-name-specifier of the declarator-id. 5940 RemoveUsingDecls(Previous); 5941 } 5942 5943 if (Previous.isSingleResult() && 5944 Previous.getFoundDecl()->isTemplateParameter()) { 5945 // Maybe we will complain about the shadowed template parameter. 5946 if (!D.isInvalidType()) 5947 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5948 Previous.getFoundDecl()); 5949 5950 // Just pretend that we didn't see the previous declaration. 5951 Previous.clear(); 5952 } 5953 5954 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5955 // Forget that the previous declaration is the injected-class-name. 5956 Previous.clear(); 5957 5958 // In C++, the previous declaration we find might be a tag type 5959 // (class or enum). In this case, the new declaration will hide the 5960 // tag type. Note that this applies to functions, function templates, and 5961 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5962 if (Previous.isSingleTagDecl() && 5963 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5964 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5965 Previous.clear(); 5966 5967 // Check that there are no default arguments other than in the parameters 5968 // of a function declaration (C++ only). 5969 if (getLangOpts().CPlusPlus) 5970 CheckExtraCXXDefaultArguments(D); 5971 5972 NamedDecl *New; 5973 5974 bool AddToScope = true; 5975 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5976 if (TemplateParamLists.size()) { 5977 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5978 return nullptr; 5979 } 5980 5981 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5982 } else if (R->isFunctionType()) { 5983 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5984 TemplateParamLists, 5985 AddToScope); 5986 } else { 5987 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5988 AddToScope); 5989 } 5990 5991 if (!New) 5992 return nullptr; 5993 5994 // If this has an identifier and is not a function template specialization, 5995 // add it to the scope stack. 5996 if (New->getDeclName() && AddToScope) 5997 PushOnScopeChains(New, S); 5998 5999 if (isInOpenMPDeclareTargetContext()) 6000 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6001 6002 return New; 6003 } 6004 6005 /// Helper method to turn variable array types into constant array 6006 /// types in certain situations which would otherwise be errors (for 6007 /// GCC compatibility). 6008 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6009 ASTContext &Context, 6010 bool &SizeIsNegative, 6011 llvm::APSInt &Oversized) { 6012 // This method tries to turn a variable array into a constant 6013 // array even when the size isn't an ICE. This is necessary 6014 // for compatibility with code that depends on gcc's buggy 6015 // constant expression folding, like struct {char x[(int)(char*)2];} 6016 SizeIsNegative = false; 6017 Oversized = 0; 6018 6019 if (T->isDependentType()) 6020 return QualType(); 6021 6022 QualifierCollector Qs; 6023 const Type *Ty = Qs.strip(T); 6024 6025 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6026 QualType Pointee = PTy->getPointeeType(); 6027 QualType FixedType = 6028 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6029 Oversized); 6030 if (FixedType.isNull()) return FixedType; 6031 FixedType = Context.getPointerType(FixedType); 6032 return Qs.apply(Context, FixedType); 6033 } 6034 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6035 QualType Inner = PTy->getInnerType(); 6036 QualType FixedType = 6037 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6038 Oversized); 6039 if (FixedType.isNull()) return FixedType; 6040 FixedType = Context.getParenType(FixedType); 6041 return Qs.apply(Context, FixedType); 6042 } 6043 6044 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6045 if (!VLATy) 6046 return QualType(); 6047 6048 QualType ElemTy = VLATy->getElementType(); 6049 if (ElemTy->isVariablyModifiedType()) { 6050 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6051 SizeIsNegative, Oversized); 6052 if (ElemTy.isNull()) 6053 return QualType(); 6054 } 6055 6056 Expr::EvalResult Result; 6057 if (!VLATy->getSizeExpr() || 6058 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6059 return QualType(); 6060 6061 llvm::APSInt Res = Result.Val.getInt(); 6062 6063 // Check whether the array size is negative. 6064 if (Res.isSigned() && Res.isNegative()) { 6065 SizeIsNegative = true; 6066 return QualType(); 6067 } 6068 6069 // Check whether the array is too large to be addressed. 6070 unsigned ActiveSizeBits = 6071 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6072 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6073 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6074 : Res.getActiveBits(); 6075 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6076 Oversized = Res; 6077 return QualType(); 6078 } 6079 6080 QualType FoldedArrayType = Context.getConstantArrayType( 6081 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6082 return Qs.apply(Context, FoldedArrayType); 6083 } 6084 6085 static void 6086 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6087 SrcTL = SrcTL.getUnqualifiedLoc(); 6088 DstTL = DstTL.getUnqualifiedLoc(); 6089 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6090 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6091 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6092 DstPTL.getPointeeLoc()); 6093 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6094 return; 6095 } 6096 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6097 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6098 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6099 DstPTL.getInnerLoc()); 6100 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6101 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6102 return; 6103 } 6104 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6105 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6106 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6107 TypeLoc DstElemTL = DstATL.getElementLoc(); 6108 if (VariableArrayTypeLoc SrcElemATL = 6109 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6110 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6111 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6112 } else { 6113 DstElemTL.initializeFullCopy(SrcElemTL); 6114 } 6115 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6116 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6117 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6118 } 6119 6120 /// Helper method to turn variable array types into constant array 6121 /// types in certain situations which would otherwise be errors (for 6122 /// GCC compatibility). 6123 static TypeSourceInfo* 6124 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6125 ASTContext &Context, 6126 bool &SizeIsNegative, 6127 llvm::APSInt &Oversized) { 6128 QualType FixedTy 6129 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6130 SizeIsNegative, Oversized); 6131 if (FixedTy.isNull()) 6132 return nullptr; 6133 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6134 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6135 FixedTInfo->getTypeLoc()); 6136 return FixedTInfo; 6137 } 6138 6139 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6140 /// true if we were successful. 6141 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6142 QualType &T, SourceLocation Loc, 6143 unsigned FailedFoldDiagID) { 6144 bool SizeIsNegative; 6145 llvm::APSInt Oversized; 6146 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6147 TInfo, Context, SizeIsNegative, Oversized); 6148 if (FixedTInfo) { 6149 Diag(Loc, diag::ext_vla_folded_to_constant); 6150 TInfo = FixedTInfo; 6151 T = FixedTInfo->getType(); 6152 return true; 6153 } 6154 6155 if (SizeIsNegative) 6156 Diag(Loc, diag::err_typecheck_negative_array_size); 6157 else if (Oversized.getBoolValue()) 6158 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6159 else if (FailedFoldDiagID) 6160 Diag(Loc, FailedFoldDiagID); 6161 return false; 6162 } 6163 6164 /// Register the given locally-scoped extern "C" declaration so 6165 /// that it can be found later for redeclarations. We include any extern "C" 6166 /// declaration that is not visible in the translation unit here, not just 6167 /// function-scope declarations. 6168 void 6169 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6170 if (!getLangOpts().CPlusPlus && 6171 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6172 // Don't need to track declarations in the TU in C. 6173 return; 6174 6175 // Note that we have a locally-scoped external with this name. 6176 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6177 } 6178 6179 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6180 // FIXME: We can have multiple results via __attribute__((overloadable)). 6181 auto Result = Context.getExternCContextDecl()->lookup(Name); 6182 return Result.empty() ? nullptr : *Result.begin(); 6183 } 6184 6185 /// Diagnose function specifiers on a declaration of an identifier that 6186 /// does not identify a function. 6187 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6188 // FIXME: We should probably indicate the identifier in question to avoid 6189 // confusion for constructs like "virtual int a(), b;" 6190 if (DS.isVirtualSpecified()) 6191 Diag(DS.getVirtualSpecLoc(), 6192 diag::err_virtual_non_function); 6193 6194 if (DS.hasExplicitSpecifier()) 6195 Diag(DS.getExplicitSpecLoc(), 6196 diag::err_explicit_non_function); 6197 6198 if (DS.isNoreturnSpecified()) 6199 Diag(DS.getNoreturnSpecLoc(), 6200 diag::err_noreturn_non_function); 6201 } 6202 6203 NamedDecl* 6204 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6205 TypeSourceInfo *TInfo, LookupResult &Previous) { 6206 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6207 if (D.getCXXScopeSpec().isSet()) { 6208 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6209 << D.getCXXScopeSpec().getRange(); 6210 D.setInvalidType(); 6211 // Pretend we didn't see the scope specifier. 6212 DC = CurContext; 6213 Previous.clear(); 6214 } 6215 6216 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6217 6218 if (D.getDeclSpec().isInlineSpecified()) 6219 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6220 << getLangOpts().CPlusPlus17; 6221 if (D.getDeclSpec().hasConstexprSpecifier()) 6222 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6223 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6224 6225 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6226 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6227 Diag(D.getName().StartLocation, 6228 diag::err_deduction_guide_invalid_specifier) 6229 << "typedef"; 6230 else 6231 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6232 << D.getName().getSourceRange(); 6233 return nullptr; 6234 } 6235 6236 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6237 if (!NewTD) return nullptr; 6238 6239 // Handle attributes prior to checking for duplicates in MergeVarDecl 6240 ProcessDeclAttributes(S, NewTD, D); 6241 6242 CheckTypedefForVariablyModifiedType(S, NewTD); 6243 6244 bool Redeclaration = D.isRedeclaration(); 6245 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6246 D.setRedeclaration(Redeclaration); 6247 return ND; 6248 } 6249 6250 void 6251 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6252 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6253 // then it shall have block scope. 6254 // Note that variably modified types must be fixed before merging the decl so 6255 // that redeclarations will match. 6256 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6257 QualType T = TInfo->getType(); 6258 if (T->isVariablyModifiedType()) { 6259 setFunctionHasBranchProtectedScope(); 6260 6261 if (S->getFnParent() == nullptr) { 6262 bool SizeIsNegative; 6263 llvm::APSInt Oversized; 6264 TypeSourceInfo *FixedTInfo = 6265 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6266 SizeIsNegative, 6267 Oversized); 6268 if (FixedTInfo) { 6269 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6270 NewTD->setTypeSourceInfo(FixedTInfo); 6271 } else { 6272 if (SizeIsNegative) 6273 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6274 else if (T->isVariableArrayType()) 6275 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6276 else if (Oversized.getBoolValue()) 6277 Diag(NewTD->getLocation(), diag::err_array_too_large) 6278 << toString(Oversized, 10); 6279 else 6280 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6281 NewTD->setInvalidDecl(); 6282 } 6283 } 6284 } 6285 } 6286 6287 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6288 /// declares a typedef-name, either using the 'typedef' type specifier or via 6289 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6290 NamedDecl* 6291 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6292 LookupResult &Previous, bool &Redeclaration) { 6293 6294 // Find the shadowed declaration before filtering for scope. 6295 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6296 6297 // Merge the decl with the existing one if appropriate. If the decl is 6298 // in an outer scope, it isn't the same thing. 6299 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6300 /*AllowInlineNamespace*/false); 6301 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6302 if (!Previous.empty()) { 6303 Redeclaration = true; 6304 MergeTypedefNameDecl(S, NewTD, Previous); 6305 } else { 6306 inferGslPointerAttribute(NewTD); 6307 } 6308 6309 if (ShadowedDecl && !Redeclaration) 6310 CheckShadow(NewTD, ShadowedDecl, Previous); 6311 6312 // If this is the C FILE type, notify the AST context. 6313 if (IdentifierInfo *II = NewTD->getIdentifier()) 6314 if (!NewTD->isInvalidDecl() && 6315 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6316 if (II->isStr("FILE")) 6317 Context.setFILEDecl(NewTD); 6318 else if (II->isStr("jmp_buf")) 6319 Context.setjmp_bufDecl(NewTD); 6320 else if (II->isStr("sigjmp_buf")) 6321 Context.setsigjmp_bufDecl(NewTD); 6322 else if (II->isStr("ucontext_t")) 6323 Context.setucontext_tDecl(NewTD); 6324 } 6325 6326 return NewTD; 6327 } 6328 6329 /// Determines whether the given declaration is an out-of-scope 6330 /// previous declaration. 6331 /// 6332 /// This routine should be invoked when name lookup has found a 6333 /// previous declaration (PrevDecl) that is not in the scope where a 6334 /// new declaration by the same name is being introduced. If the new 6335 /// declaration occurs in a local scope, previous declarations with 6336 /// linkage may still be considered previous declarations (C99 6337 /// 6.2.2p4-5, C++ [basic.link]p6). 6338 /// 6339 /// \param PrevDecl the previous declaration found by name 6340 /// lookup 6341 /// 6342 /// \param DC the context in which the new declaration is being 6343 /// declared. 6344 /// 6345 /// \returns true if PrevDecl is an out-of-scope previous declaration 6346 /// for a new delcaration with the same name. 6347 static bool 6348 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6349 ASTContext &Context) { 6350 if (!PrevDecl) 6351 return false; 6352 6353 if (!PrevDecl->hasLinkage()) 6354 return false; 6355 6356 if (Context.getLangOpts().CPlusPlus) { 6357 // C++ [basic.link]p6: 6358 // If there is a visible declaration of an entity with linkage 6359 // having the same name and type, ignoring entities declared 6360 // outside the innermost enclosing namespace scope, the block 6361 // scope declaration declares that same entity and receives the 6362 // linkage of the previous declaration. 6363 DeclContext *OuterContext = DC->getRedeclContext(); 6364 if (!OuterContext->isFunctionOrMethod()) 6365 // This rule only applies to block-scope declarations. 6366 return false; 6367 6368 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6369 if (PrevOuterContext->isRecord()) 6370 // We found a member function: ignore it. 6371 return false; 6372 6373 // Find the innermost enclosing namespace for the new and 6374 // previous declarations. 6375 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6376 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6377 6378 // The previous declaration is in a different namespace, so it 6379 // isn't the same function. 6380 if (!OuterContext->Equals(PrevOuterContext)) 6381 return false; 6382 } 6383 6384 return true; 6385 } 6386 6387 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6388 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6389 if (!SS.isSet()) return; 6390 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6391 } 6392 6393 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6394 QualType type = decl->getType(); 6395 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6396 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6397 // Various kinds of declaration aren't allowed to be __autoreleasing. 6398 unsigned kind = -1U; 6399 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6400 if (var->hasAttr<BlocksAttr>()) 6401 kind = 0; // __block 6402 else if (!var->hasLocalStorage()) 6403 kind = 1; // global 6404 } else if (isa<ObjCIvarDecl>(decl)) { 6405 kind = 3; // ivar 6406 } else if (isa<FieldDecl>(decl)) { 6407 kind = 2; // field 6408 } 6409 6410 if (kind != -1U) { 6411 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6412 << kind; 6413 } 6414 } else if (lifetime == Qualifiers::OCL_None) { 6415 // Try to infer lifetime. 6416 if (!type->isObjCLifetimeType()) 6417 return false; 6418 6419 lifetime = type->getObjCARCImplicitLifetime(); 6420 type = Context.getLifetimeQualifiedType(type, lifetime); 6421 decl->setType(type); 6422 } 6423 6424 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6425 // Thread-local variables cannot have lifetime. 6426 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6427 var->getTLSKind()) { 6428 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6429 << var->getType(); 6430 return true; 6431 } 6432 } 6433 6434 return false; 6435 } 6436 6437 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6438 if (Decl->getType().hasAddressSpace()) 6439 return; 6440 if (Decl->getType()->isDependentType()) 6441 return; 6442 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6443 QualType Type = Var->getType(); 6444 if (Type->isSamplerT() || Type->isVoidType()) 6445 return; 6446 LangAS ImplAS = LangAS::opencl_private; 6447 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6448 // __opencl_c_program_scope_global_variables feature, the address space 6449 // for a variable at program scope or a static or extern variable inside 6450 // a function are inferred to be __global. 6451 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6452 Var->hasGlobalStorage()) 6453 ImplAS = LangAS::opencl_global; 6454 // If the original type from a decayed type is an array type and that array 6455 // type has no address space yet, deduce it now. 6456 if (auto DT = dyn_cast<DecayedType>(Type)) { 6457 auto OrigTy = DT->getOriginalType(); 6458 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6459 // Add the address space to the original array type and then propagate 6460 // that to the element type through `getAsArrayType`. 6461 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6462 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6463 // Re-generate the decayed type. 6464 Type = Context.getDecayedType(OrigTy); 6465 } 6466 } 6467 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6468 // Apply any qualifiers (including address space) from the array type to 6469 // the element type. This implements C99 6.7.3p8: "If the specification of 6470 // an array type includes any type qualifiers, the element type is so 6471 // qualified, not the array type." 6472 if (Type->isArrayType()) 6473 Type = QualType(Context.getAsArrayType(Type), 0); 6474 Decl->setType(Type); 6475 } 6476 } 6477 6478 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6479 // Ensure that an auto decl is deduced otherwise the checks below might cache 6480 // the wrong linkage. 6481 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6482 6483 // 'weak' only applies to declarations with external linkage. 6484 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6485 if (!ND.isExternallyVisible()) { 6486 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6487 ND.dropAttr<WeakAttr>(); 6488 } 6489 } 6490 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6491 if (ND.isExternallyVisible()) { 6492 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6493 ND.dropAttr<WeakRefAttr>(); 6494 ND.dropAttr<AliasAttr>(); 6495 } 6496 } 6497 6498 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6499 if (VD->hasInit()) { 6500 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6501 assert(VD->isThisDeclarationADefinition() && 6502 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6503 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6504 VD->dropAttr<AliasAttr>(); 6505 } 6506 } 6507 } 6508 6509 // 'selectany' only applies to externally visible variable declarations. 6510 // It does not apply to functions. 6511 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6512 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6513 S.Diag(Attr->getLocation(), 6514 diag::err_attribute_selectany_non_extern_data); 6515 ND.dropAttr<SelectAnyAttr>(); 6516 } 6517 } 6518 6519 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6520 auto *VD = dyn_cast<VarDecl>(&ND); 6521 bool IsAnonymousNS = false; 6522 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6523 if (VD) { 6524 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6525 while (NS && !IsAnonymousNS) { 6526 IsAnonymousNS = NS->isAnonymousNamespace(); 6527 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6528 } 6529 } 6530 // dll attributes require external linkage. Static locals may have external 6531 // linkage but still cannot be explicitly imported or exported. 6532 // In Microsoft mode, a variable defined in anonymous namespace must have 6533 // external linkage in order to be exported. 6534 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6535 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6536 (!AnonNSInMicrosoftMode && 6537 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6538 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6539 << &ND << Attr; 6540 ND.setInvalidDecl(); 6541 } 6542 } 6543 6544 // Check the attributes on the function type, if any. 6545 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6546 // Don't declare this variable in the second operand of the for-statement; 6547 // GCC miscompiles that by ending its lifetime before evaluating the 6548 // third operand. See gcc.gnu.org/PR86769. 6549 AttributedTypeLoc ATL; 6550 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6551 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6552 TL = ATL.getModifiedLoc()) { 6553 // The [[lifetimebound]] attribute can be applied to the implicit object 6554 // parameter of a non-static member function (other than a ctor or dtor) 6555 // by applying it to the function type. 6556 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6557 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6558 if (!MD || MD->isStatic()) { 6559 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6560 << !MD << A->getRange(); 6561 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6562 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6563 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6564 } 6565 } 6566 } 6567 } 6568 } 6569 6570 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6571 NamedDecl *NewDecl, 6572 bool IsSpecialization, 6573 bool IsDefinition) { 6574 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6575 return; 6576 6577 bool IsTemplate = false; 6578 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6579 OldDecl = OldTD->getTemplatedDecl(); 6580 IsTemplate = true; 6581 if (!IsSpecialization) 6582 IsDefinition = false; 6583 } 6584 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6585 NewDecl = NewTD->getTemplatedDecl(); 6586 IsTemplate = true; 6587 } 6588 6589 if (!OldDecl || !NewDecl) 6590 return; 6591 6592 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6593 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6594 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6595 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6596 6597 // dllimport and dllexport are inheritable attributes so we have to exclude 6598 // inherited attribute instances. 6599 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6600 (NewExportAttr && !NewExportAttr->isInherited()); 6601 6602 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6603 // the only exception being explicit specializations. 6604 // Implicitly generated declarations are also excluded for now because there 6605 // is no other way to switch these to use dllimport or dllexport. 6606 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6607 6608 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6609 // Allow with a warning for free functions and global variables. 6610 bool JustWarn = false; 6611 if (!OldDecl->isCXXClassMember()) { 6612 auto *VD = dyn_cast<VarDecl>(OldDecl); 6613 if (VD && !VD->getDescribedVarTemplate()) 6614 JustWarn = true; 6615 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6616 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6617 JustWarn = true; 6618 } 6619 6620 // We cannot change a declaration that's been used because IR has already 6621 // been emitted. Dllimported functions will still work though (modulo 6622 // address equality) as they can use the thunk. 6623 if (OldDecl->isUsed()) 6624 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6625 JustWarn = false; 6626 6627 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6628 : diag::err_attribute_dll_redeclaration; 6629 S.Diag(NewDecl->getLocation(), DiagID) 6630 << NewDecl 6631 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6632 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6633 if (!JustWarn) { 6634 NewDecl->setInvalidDecl(); 6635 return; 6636 } 6637 } 6638 6639 // A redeclaration is not allowed to drop a dllimport attribute, the only 6640 // exceptions being inline function definitions (except for function 6641 // templates), local extern declarations, qualified friend declarations or 6642 // special MSVC extension: in the last case, the declaration is treated as if 6643 // it were marked dllexport. 6644 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6645 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6646 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6647 // Ignore static data because out-of-line definitions are diagnosed 6648 // separately. 6649 IsStaticDataMember = VD->isStaticDataMember(); 6650 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6651 VarDecl::DeclarationOnly; 6652 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6653 IsInline = FD->isInlined(); 6654 IsQualifiedFriend = FD->getQualifier() && 6655 FD->getFriendObjectKind() == Decl::FOK_Declared; 6656 } 6657 6658 if (OldImportAttr && !HasNewAttr && 6659 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6660 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6661 if (IsMicrosoftABI && IsDefinition) { 6662 S.Diag(NewDecl->getLocation(), 6663 diag::warn_redeclaration_without_import_attribute) 6664 << NewDecl; 6665 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6666 NewDecl->dropAttr<DLLImportAttr>(); 6667 NewDecl->addAttr( 6668 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6669 } else { 6670 S.Diag(NewDecl->getLocation(), 6671 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6672 << NewDecl << OldImportAttr; 6673 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6674 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6675 OldDecl->dropAttr<DLLImportAttr>(); 6676 NewDecl->dropAttr<DLLImportAttr>(); 6677 } 6678 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6679 // In MinGW, seeing a function declared inline drops the dllimport 6680 // attribute. 6681 OldDecl->dropAttr<DLLImportAttr>(); 6682 NewDecl->dropAttr<DLLImportAttr>(); 6683 S.Diag(NewDecl->getLocation(), 6684 diag::warn_dllimport_dropped_from_inline_function) 6685 << NewDecl << OldImportAttr; 6686 } 6687 6688 // A specialization of a class template member function is processed here 6689 // since it's a redeclaration. If the parent class is dllexport, the 6690 // specialization inherits that attribute. This doesn't happen automatically 6691 // since the parent class isn't instantiated until later. 6692 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6693 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6694 !NewImportAttr && !NewExportAttr) { 6695 if (const DLLExportAttr *ParentExportAttr = 6696 MD->getParent()->getAttr<DLLExportAttr>()) { 6697 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6698 NewAttr->setInherited(true); 6699 NewDecl->addAttr(NewAttr); 6700 } 6701 } 6702 } 6703 } 6704 6705 /// Given that we are within the definition of the given function, 6706 /// will that definition behave like C99's 'inline', where the 6707 /// definition is discarded except for optimization purposes? 6708 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6709 // Try to avoid calling GetGVALinkageForFunction. 6710 6711 // All cases of this require the 'inline' keyword. 6712 if (!FD->isInlined()) return false; 6713 6714 // This is only possible in C++ with the gnu_inline attribute. 6715 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6716 return false; 6717 6718 // Okay, go ahead and call the relatively-more-expensive function. 6719 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6720 } 6721 6722 /// Determine whether a variable is extern "C" prior to attaching 6723 /// an initializer. We can't just call isExternC() here, because that 6724 /// will also compute and cache whether the declaration is externally 6725 /// visible, which might change when we attach the initializer. 6726 /// 6727 /// This can only be used if the declaration is known to not be a 6728 /// redeclaration of an internal linkage declaration. 6729 /// 6730 /// For instance: 6731 /// 6732 /// auto x = []{}; 6733 /// 6734 /// Attaching the initializer here makes this declaration not externally 6735 /// visible, because its type has internal linkage. 6736 /// 6737 /// FIXME: This is a hack. 6738 template<typename T> 6739 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6740 if (S.getLangOpts().CPlusPlus) { 6741 // In C++, the overloadable attribute negates the effects of extern "C". 6742 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6743 return false; 6744 6745 // So do CUDA's host/device attributes. 6746 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6747 D->template hasAttr<CUDAHostAttr>())) 6748 return false; 6749 } 6750 return D->isExternC(); 6751 } 6752 6753 static bool shouldConsiderLinkage(const VarDecl *VD) { 6754 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6755 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6756 isa<OMPDeclareMapperDecl>(DC)) 6757 return VD->hasExternalStorage(); 6758 if (DC->isFileContext()) 6759 return true; 6760 if (DC->isRecord()) 6761 return false; 6762 if (isa<RequiresExprBodyDecl>(DC)) 6763 return false; 6764 llvm_unreachable("Unexpected context"); 6765 } 6766 6767 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6768 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6769 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6770 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6771 return true; 6772 if (DC->isRecord()) 6773 return false; 6774 llvm_unreachable("Unexpected context"); 6775 } 6776 6777 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6778 ParsedAttr::Kind Kind) { 6779 // Check decl attributes on the DeclSpec. 6780 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6781 return true; 6782 6783 // Walk the declarator structure, checking decl attributes that were in a type 6784 // position to the decl itself. 6785 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6786 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6787 return true; 6788 } 6789 6790 // Finally, check attributes on the decl itself. 6791 return PD.getAttributes().hasAttribute(Kind); 6792 } 6793 6794 /// Adjust the \c DeclContext for a function or variable that might be a 6795 /// function-local external declaration. 6796 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6797 if (!DC->isFunctionOrMethod()) 6798 return false; 6799 6800 // If this is a local extern function or variable declared within a function 6801 // template, don't add it into the enclosing namespace scope until it is 6802 // instantiated; it might have a dependent type right now. 6803 if (DC->isDependentContext()) 6804 return true; 6805 6806 // C++11 [basic.link]p7: 6807 // When a block scope declaration of an entity with linkage is not found to 6808 // refer to some other declaration, then that entity is a member of the 6809 // innermost enclosing namespace. 6810 // 6811 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6812 // semantically-enclosing namespace, not a lexically-enclosing one. 6813 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6814 DC = DC->getParent(); 6815 return true; 6816 } 6817 6818 /// Returns true if given declaration has external C language linkage. 6819 static bool isDeclExternC(const Decl *D) { 6820 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6821 return FD->isExternC(); 6822 if (const auto *VD = dyn_cast<VarDecl>(D)) 6823 return VD->isExternC(); 6824 6825 llvm_unreachable("Unknown type of decl!"); 6826 } 6827 6828 /// Returns true if there hasn't been any invalid type diagnosed. 6829 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6830 DeclContext *DC = NewVD->getDeclContext(); 6831 QualType R = NewVD->getType(); 6832 6833 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6834 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6835 // argument. 6836 if (R->isImageType() || R->isPipeType()) { 6837 Se.Diag(NewVD->getLocation(), 6838 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6839 << R; 6840 NewVD->setInvalidDecl(); 6841 return false; 6842 } 6843 6844 // OpenCL v1.2 s6.9.r: 6845 // The event type cannot be used to declare a program scope variable. 6846 // OpenCL v2.0 s6.9.q: 6847 // The clk_event_t and reserve_id_t types cannot be declared in program 6848 // scope. 6849 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6850 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6851 Se.Diag(NewVD->getLocation(), 6852 diag::err_invalid_type_for_program_scope_var) 6853 << R; 6854 NewVD->setInvalidDecl(); 6855 return false; 6856 } 6857 } 6858 6859 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6860 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6861 Se.getLangOpts())) { 6862 QualType NR = R.getCanonicalType(); 6863 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6864 NR->isReferenceType()) { 6865 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6866 NR->isFunctionReferenceType()) { 6867 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6868 << NR->isReferenceType(); 6869 NewVD->setInvalidDecl(); 6870 return false; 6871 } 6872 NR = NR->getPointeeType(); 6873 } 6874 } 6875 6876 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6877 Se.getLangOpts())) { 6878 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6879 // half array type (unless the cl_khr_fp16 extension is enabled). 6880 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6881 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6882 NewVD->setInvalidDecl(); 6883 return false; 6884 } 6885 } 6886 6887 // OpenCL v1.2 s6.9.r: 6888 // The event type cannot be used with the __local, __constant and __global 6889 // address space qualifiers. 6890 if (R->isEventT()) { 6891 if (R.getAddressSpace() != LangAS::opencl_private) { 6892 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6893 NewVD->setInvalidDecl(); 6894 return false; 6895 } 6896 } 6897 6898 if (R->isSamplerT()) { 6899 // OpenCL v1.2 s6.9.b p4: 6900 // The sampler type cannot be used with the __local and __global address 6901 // space qualifiers. 6902 if (R.getAddressSpace() == LangAS::opencl_local || 6903 R.getAddressSpace() == LangAS::opencl_global) { 6904 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6905 NewVD->setInvalidDecl(); 6906 } 6907 6908 // OpenCL v1.2 s6.12.14.1: 6909 // A global sampler must be declared with either the constant address 6910 // space qualifier or with the const qualifier. 6911 if (DC->isTranslationUnit() && 6912 !(R.getAddressSpace() == LangAS::opencl_constant || 6913 R.isConstQualified())) { 6914 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6915 NewVD->setInvalidDecl(); 6916 } 6917 if (NewVD->isInvalidDecl()) 6918 return false; 6919 } 6920 6921 return true; 6922 } 6923 6924 template <typename AttrTy> 6925 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6926 const TypedefNameDecl *TND = TT->getDecl(); 6927 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6928 AttrTy *Clone = Attribute->clone(S.Context); 6929 Clone->setInherited(true); 6930 D->addAttr(Clone); 6931 } 6932 } 6933 6934 NamedDecl *Sema::ActOnVariableDeclarator( 6935 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6936 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6937 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6938 QualType R = TInfo->getType(); 6939 DeclarationName Name = GetNameForDeclarator(D).getName(); 6940 6941 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6942 6943 if (D.isDecompositionDeclarator()) { 6944 // Take the name of the first declarator as our name for diagnostic 6945 // purposes. 6946 auto &Decomp = D.getDecompositionDeclarator(); 6947 if (!Decomp.bindings().empty()) { 6948 II = Decomp.bindings()[0].Name; 6949 Name = II; 6950 } 6951 } else if (!II) { 6952 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6953 return nullptr; 6954 } 6955 6956 6957 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6958 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6959 6960 // dllimport globals without explicit storage class are treated as extern. We 6961 // have to change the storage class this early to get the right DeclContext. 6962 if (SC == SC_None && !DC->isRecord() && 6963 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6964 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6965 SC = SC_Extern; 6966 6967 DeclContext *OriginalDC = DC; 6968 bool IsLocalExternDecl = SC == SC_Extern && 6969 adjustContextForLocalExternDecl(DC); 6970 6971 if (SCSpec == DeclSpec::SCS_mutable) { 6972 // mutable can only appear on non-static class members, so it's always 6973 // an error here 6974 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6975 D.setInvalidType(); 6976 SC = SC_None; 6977 } 6978 6979 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6980 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6981 D.getDeclSpec().getStorageClassSpecLoc())) { 6982 // In C++11, the 'register' storage class specifier is deprecated. 6983 // Suppress the warning in system macros, it's used in macros in some 6984 // popular C system headers, such as in glibc's htonl() macro. 6985 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6986 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6987 : diag::warn_deprecated_register) 6988 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6989 } 6990 6991 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6992 6993 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6994 // C99 6.9p2: The storage-class specifiers auto and register shall not 6995 // appear in the declaration specifiers in an external declaration. 6996 // Global Register+Asm is a GNU extension we support. 6997 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6998 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6999 D.setInvalidType(); 7000 } 7001 } 7002 7003 // If this variable has a VLA type and an initializer, try to 7004 // fold to a constant-sized type. This is otherwise invalid. 7005 if (D.hasInitializer() && R->isVariableArrayType()) 7006 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7007 /*DiagID=*/0); 7008 7009 bool IsMemberSpecialization = false; 7010 bool IsVariableTemplateSpecialization = false; 7011 bool IsPartialSpecialization = false; 7012 bool IsVariableTemplate = false; 7013 VarDecl *NewVD = nullptr; 7014 VarTemplateDecl *NewTemplate = nullptr; 7015 TemplateParameterList *TemplateParams = nullptr; 7016 if (!getLangOpts().CPlusPlus) { 7017 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7018 II, R, TInfo, SC); 7019 7020 if (R->getContainedDeducedType()) 7021 ParsingInitForAutoVars.insert(NewVD); 7022 7023 if (D.isInvalidType()) 7024 NewVD->setInvalidDecl(); 7025 7026 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7027 NewVD->hasLocalStorage()) 7028 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7029 NTCUC_AutoVar, NTCUK_Destruct); 7030 } else { 7031 bool Invalid = false; 7032 7033 if (DC->isRecord() && !CurContext->isRecord()) { 7034 // This is an out-of-line definition of a static data member. 7035 switch (SC) { 7036 case SC_None: 7037 break; 7038 case SC_Static: 7039 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7040 diag::err_static_out_of_line) 7041 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7042 break; 7043 case SC_Auto: 7044 case SC_Register: 7045 case SC_Extern: 7046 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7047 // to names of variables declared in a block or to function parameters. 7048 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7049 // of class members 7050 7051 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7052 diag::err_storage_class_for_static_member) 7053 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7054 break; 7055 case SC_PrivateExtern: 7056 llvm_unreachable("C storage class in c++!"); 7057 } 7058 } 7059 7060 if (SC == SC_Static && CurContext->isRecord()) { 7061 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7062 // Walk up the enclosing DeclContexts to check for any that are 7063 // incompatible with static data members. 7064 const DeclContext *FunctionOrMethod = nullptr; 7065 const CXXRecordDecl *AnonStruct = nullptr; 7066 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7067 if (Ctxt->isFunctionOrMethod()) { 7068 FunctionOrMethod = Ctxt; 7069 break; 7070 } 7071 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7072 if (ParentDecl && !ParentDecl->getDeclName()) { 7073 AnonStruct = ParentDecl; 7074 break; 7075 } 7076 } 7077 if (FunctionOrMethod) { 7078 // C++ [class.static.data]p5: A local class shall not have static data 7079 // members. 7080 Diag(D.getIdentifierLoc(), 7081 diag::err_static_data_member_not_allowed_in_local_class) 7082 << Name << RD->getDeclName() << RD->getTagKind(); 7083 } else if (AnonStruct) { 7084 // C++ [class.static.data]p4: Unnamed classes and classes contained 7085 // directly or indirectly within unnamed classes shall not contain 7086 // static data members. 7087 Diag(D.getIdentifierLoc(), 7088 diag::err_static_data_member_not_allowed_in_anon_struct) 7089 << Name << AnonStruct->getTagKind(); 7090 Invalid = true; 7091 } else if (RD->isUnion()) { 7092 // C++98 [class.union]p1: If a union contains a static data member, 7093 // the program is ill-formed. C++11 drops this restriction. 7094 Diag(D.getIdentifierLoc(), 7095 getLangOpts().CPlusPlus11 7096 ? diag::warn_cxx98_compat_static_data_member_in_union 7097 : diag::ext_static_data_member_in_union) << Name; 7098 } 7099 } 7100 } 7101 7102 // Match up the template parameter lists with the scope specifier, then 7103 // determine whether we have a template or a template specialization. 7104 bool InvalidScope = false; 7105 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7106 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7107 D.getCXXScopeSpec(), 7108 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7109 ? D.getName().TemplateId 7110 : nullptr, 7111 TemplateParamLists, 7112 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7113 Invalid |= InvalidScope; 7114 7115 if (TemplateParams) { 7116 if (!TemplateParams->size() && 7117 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7118 // There is an extraneous 'template<>' for this variable. Complain 7119 // about it, but allow the declaration of the variable. 7120 Diag(TemplateParams->getTemplateLoc(), 7121 diag::err_template_variable_noparams) 7122 << II 7123 << SourceRange(TemplateParams->getTemplateLoc(), 7124 TemplateParams->getRAngleLoc()); 7125 TemplateParams = nullptr; 7126 } else { 7127 // Check that we can declare a template here. 7128 if (CheckTemplateDeclScope(S, TemplateParams)) 7129 return nullptr; 7130 7131 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7132 // This is an explicit specialization or a partial specialization. 7133 IsVariableTemplateSpecialization = true; 7134 IsPartialSpecialization = TemplateParams->size() > 0; 7135 } else { // if (TemplateParams->size() > 0) 7136 // This is a template declaration. 7137 IsVariableTemplate = true; 7138 7139 // Only C++1y supports variable templates (N3651). 7140 Diag(D.getIdentifierLoc(), 7141 getLangOpts().CPlusPlus14 7142 ? diag::warn_cxx11_compat_variable_template 7143 : diag::ext_variable_template); 7144 } 7145 } 7146 } else { 7147 // Check that we can declare a member specialization here. 7148 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7149 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7150 return nullptr; 7151 assert((Invalid || 7152 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7153 "should have a 'template<>' for this decl"); 7154 } 7155 7156 if (IsVariableTemplateSpecialization) { 7157 SourceLocation TemplateKWLoc = 7158 TemplateParamLists.size() > 0 7159 ? TemplateParamLists[0]->getTemplateLoc() 7160 : SourceLocation(); 7161 DeclResult Res = ActOnVarTemplateSpecialization( 7162 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7163 IsPartialSpecialization); 7164 if (Res.isInvalid()) 7165 return nullptr; 7166 NewVD = cast<VarDecl>(Res.get()); 7167 AddToScope = false; 7168 } else if (D.isDecompositionDeclarator()) { 7169 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7170 D.getIdentifierLoc(), R, TInfo, SC, 7171 Bindings); 7172 } else 7173 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7174 D.getIdentifierLoc(), II, R, TInfo, SC); 7175 7176 // If this is supposed to be a variable template, create it as such. 7177 if (IsVariableTemplate) { 7178 NewTemplate = 7179 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7180 TemplateParams, NewVD); 7181 NewVD->setDescribedVarTemplate(NewTemplate); 7182 } 7183 7184 // If this decl has an auto type in need of deduction, make a note of the 7185 // Decl so we can diagnose uses of it in its own initializer. 7186 if (R->getContainedDeducedType()) 7187 ParsingInitForAutoVars.insert(NewVD); 7188 7189 if (D.isInvalidType() || Invalid) { 7190 NewVD->setInvalidDecl(); 7191 if (NewTemplate) 7192 NewTemplate->setInvalidDecl(); 7193 } 7194 7195 SetNestedNameSpecifier(*this, NewVD, D); 7196 7197 // If we have any template parameter lists that don't directly belong to 7198 // the variable (matching the scope specifier), store them. 7199 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7200 if (TemplateParamLists.size() > VDTemplateParamLists) 7201 NewVD->setTemplateParameterListsInfo( 7202 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7203 } 7204 7205 if (D.getDeclSpec().isInlineSpecified()) { 7206 if (!getLangOpts().CPlusPlus) { 7207 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7208 << 0; 7209 } else if (CurContext->isFunctionOrMethod()) { 7210 // 'inline' is not allowed on block scope variable declaration. 7211 Diag(D.getDeclSpec().getInlineSpecLoc(), 7212 diag::err_inline_declaration_block_scope) << Name 7213 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7214 } else { 7215 Diag(D.getDeclSpec().getInlineSpecLoc(), 7216 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7217 : diag::ext_inline_variable); 7218 NewVD->setInlineSpecified(); 7219 } 7220 } 7221 7222 // Set the lexical context. If the declarator has a C++ scope specifier, the 7223 // lexical context will be different from the semantic context. 7224 NewVD->setLexicalDeclContext(CurContext); 7225 if (NewTemplate) 7226 NewTemplate->setLexicalDeclContext(CurContext); 7227 7228 if (IsLocalExternDecl) { 7229 if (D.isDecompositionDeclarator()) 7230 for (auto *B : Bindings) 7231 B->setLocalExternDecl(); 7232 else 7233 NewVD->setLocalExternDecl(); 7234 } 7235 7236 bool EmitTLSUnsupportedError = false; 7237 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7238 // C++11 [dcl.stc]p4: 7239 // When thread_local is applied to a variable of block scope the 7240 // storage-class-specifier static is implied if it does not appear 7241 // explicitly. 7242 // Core issue: 'static' is not implied if the variable is declared 7243 // 'extern'. 7244 if (NewVD->hasLocalStorage() && 7245 (SCSpec != DeclSpec::SCS_unspecified || 7246 TSCS != DeclSpec::TSCS_thread_local || 7247 !DC->isFunctionOrMethod())) 7248 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7249 diag::err_thread_non_global) 7250 << DeclSpec::getSpecifierName(TSCS); 7251 else if (!Context.getTargetInfo().isTLSSupported()) { 7252 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7253 getLangOpts().SYCLIsDevice) { 7254 // Postpone error emission until we've collected attributes required to 7255 // figure out whether it's a host or device variable and whether the 7256 // error should be ignored. 7257 EmitTLSUnsupportedError = true; 7258 // We still need to mark the variable as TLS so it shows up in AST with 7259 // proper storage class for other tools to use even if we're not going 7260 // to emit any code for it. 7261 NewVD->setTSCSpec(TSCS); 7262 } else 7263 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7264 diag::err_thread_unsupported); 7265 } else 7266 NewVD->setTSCSpec(TSCS); 7267 } 7268 7269 switch (D.getDeclSpec().getConstexprSpecifier()) { 7270 case ConstexprSpecKind::Unspecified: 7271 break; 7272 7273 case ConstexprSpecKind::Consteval: 7274 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7275 diag::err_constexpr_wrong_decl_kind) 7276 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7277 LLVM_FALLTHROUGH; 7278 7279 case ConstexprSpecKind::Constexpr: 7280 NewVD->setConstexpr(true); 7281 // C++1z [dcl.spec.constexpr]p1: 7282 // A static data member declared with the constexpr specifier is 7283 // implicitly an inline variable. 7284 if (NewVD->isStaticDataMember() && 7285 (getLangOpts().CPlusPlus17 || 7286 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7287 NewVD->setImplicitlyInline(); 7288 break; 7289 7290 case ConstexprSpecKind::Constinit: 7291 if (!NewVD->hasGlobalStorage()) 7292 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7293 diag::err_constinit_local_variable); 7294 else 7295 NewVD->addAttr(ConstInitAttr::Create( 7296 Context, D.getDeclSpec().getConstexprSpecLoc(), 7297 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7298 break; 7299 } 7300 7301 // C99 6.7.4p3 7302 // An inline definition of a function with external linkage shall 7303 // not contain a definition of a modifiable object with static or 7304 // thread storage duration... 7305 // We only apply this when the function is required to be defined 7306 // elsewhere, i.e. when the function is not 'extern inline'. Note 7307 // that a local variable with thread storage duration still has to 7308 // be marked 'static'. Also note that it's possible to get these 7309 // semantics in C++ using __attribute__((gnu_inline)). 7310 if (SC == SC_Static && S->getFnParent() != nullptr && 7311 !NewVD->getType().isConstQualified()) { 7312 FunctionDecl *CurFD = getCurFunctionDecl(); 7313 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7314 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7315 diag::warn_static_local_in_extern_inline); 7316 MaybeSuggestAddingStaticToDecl(CurFD); 7317 } 7318 } 7319 7320 if (D.getDeclSpec().isModulePrivateSpecified()) { 7321 if (IsVariableTemplateSpecialization) 7322 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7323 << (IsPartialSpecialization ? 1 : 0) 7324 << FixItHint::CreateRemoval( 7325 D.getDeclSpec().getModulePrivateSpecLoc()); 7326 else if (IsMemberSpecialization) 7327 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7328 << 2 7329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7330 else if (NewVD->hasLocalStorage()) 7331 Diag(NewVD->getLocation(), diag::err_module_private_local) 7332 << 0 << NewVD 7333 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7334 << FixItHint::CreateRemoval( 7335 D.getDeclSpec().getModulePrivateSpecLoc()); 7336 else { 7337 NewVD->setModulePrivate(); 7338 if (NewTemplate) 7339 NewTemplate->setModulePrivate(); 7340 for (auto *B : Bindings) 7341 B->setModulePrivate(); 7342 } 7343 } 7344 7345 if (getLangOpts().OpenCL) { 7346 deduceOpenCLAddressSpace(NewVD); 7347 7348 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7349 if (TSC != TSCS_unspecified) { 7350 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7351 diag::err_opencl_unknown_type_specifier) 7352 << getLangOpts().getOpenCLVersionString() 7353 << DeclSpec::getSpecifierName(TSC) << 1; 7354 NewVD->setInvalidDecl(); 7355 } 7356 } 7357 7358 // Handle attributes prior to checking for duplicates in MergeVarDecl 7359 ProcessDeclAttributes(S, NewVD, D); 7360 7361 // FIXME: This is probably the wrong location to be doing this and we should 7362 // probably be doing this for more attributes (especially for function 7363 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7364 // the code to copy attributes would be generated by TableGen. 7365 if (R->isFunctionPointerType()) 7366 if (const auto *TT = R->getAs<TypedefType>()) 7367 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7368 7369 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7370 getLangOpts().SYCLIsDevice) { 7371 if (EmitTLSUnsupportedError && 7372 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7373 (getLangOpts().OpenMPIsDevice && 7374 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7375 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7376 diag::err_thread_unsupported); 7377 7378 if (EmitTLSUnsupportedError && 7379 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7380 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7381 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7382 // storage [duration]." 7383 if (SC == SC_None && S->getFnParent() != nullptr && 7384 (NewVD->hasAttr<CUDASharedAttr>() || 7385 NewVD->hasAttr<CUDAConstantAttr>())) { 7386 NewVD->setStorageClass(SC_Static); 7387 } 7388 } 7389 7390 // Ensure that dllimport globals without explicit storage class are treated as 7391 // extern. The storage class is set above using parsed attributes. Now we can 7392 // check the VarDecl itself. 7393 assert(!NewVD->hasAttr<DLLImportAttr>() || 7394 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7395 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7396 7397 // In auto-retain/release, infer strong retension for variables of 7398 // retainable type. 7399 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7400 NewVD->setInvalidDecl(); 7401 7402 // Handle GNU asm-label extension (encoded as an attribute). 7403 if (Expr *E = (Expr*)D.getAsmLabel()) { 7404 // The parser guarantees this is a string. 7405 StringLiteral *SE = cast<StringLiteral>(E); 7406 StringRef Label = SE->getString(); 7407 if (S->getFnParent() != nullptr) { 7408 switch (SC) { 7409 case SC_None: 7410 case SC_Auto: 7411 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7412 break; 7413 case SC_Register: 7414 // Local Named register 7415 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7416 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7417 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7418 break; 7419 case SC_Static: 7420 case SC_Extern: 7421 case SC_PrivateExtern: 7422 break; 7423 } 7424 } else if (SC == SC_Register) { 7425 // Global Named register 7426 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7427 const auto &TI = Context.getTargetInfo(); 7428 bool HasSizeMismatch; 7429 7430 if (!TI.isValidGCCRegisterName(Label)) 7431 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7432 else if (!TI.validateGlobalRegisterVariable(Label, 7433 Context.getTypeSize(R), 7434 HasSizeMismatch)) 7435 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7436 else if (HasSizeMismatch) 7437 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7438 } 7439 7440 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7441 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7442 NewVD->setInvalidDecl(true); 7443 } 7444 } 7445 7446 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7447 /*IsLiteralLabel=*/true, 7448 SE->getStrTokenLoc(0))); 7449 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7450 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7451 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7452 if (I != ExtnameUndeclaredIdentifiers.end()) { 7453 if (isDeclExternC(NewVD)) { 7454 NewVD->addAttr(I->second); 7455 ExtnameUndeclaredIdentifiers.erase(I); 7456 } else 7457 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7458 << /*Variable*/1 << NewVD; 7459 } 7460 } 7461 7462 // Find the shadowed declaration before filtering for scope. 7463 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7464 ? getShadowedDeclaration(NewVD, Previous) 7465 : nullptr; 7466 7467 // Don't consider existing declarations that are in a different 7468 // scope and are out-of-semantic-context declarations (if the new 7469 // declaration has linkage). 7470 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7471 D.getCXXScopeSpec().isNotEmpty() || 7472 IsMemberSpecialization || 7473 IsVariableTemplateSpecialization); 7474 7475 // Check whether the previous declaration is in the same block scope. This 7476 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7477 if (getLangOpts().CPlusPlus && 7478 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7479 NewVD->setPreviousDeclInSameBlockScope( 7480 Previous.isSingleResult() && !Previous.isShadowed() && 7481 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7482 7483 if (!getLangOpts().CPlusPlus) { 7484 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7485 } else { 7486 // If this is an explicit specialization of a static data member, check it. 7487 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7488 CheckMemberSpecialization(NewVD, Previous)) 7489 NewVD->setInvalidDecl(); 7490 7491 // Merge the decl with the existing one if appropriate. 7492 if (!Previous.empty()) { 7493 if (Previous.isSingleResult() && 7494 isa<FieldDecl>(Previous.getFoundDecl()) && 7495 D.getCXXScopeSpec().isSet()) { 7496 // The user tried to define a non-static data member 7497 // out-of-line (C++ [dcl.meaning]p1). 7498 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7499 << D.getCXXScopeSpec().getRange(); 7500 Previous.clear(); 7501 NewVD->setInvalidDecl(); 7502 } 7503 } else if (D.getCXXScopeSpec().isSet()) { 7504 // No previous declaration in the qualifying scope. 7505 Diag(D.getIdentifierLoc(), diag::err_no_member) 7506 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7507 << D.getCXXScopeSpec().getRange(); 7508 NewVD->setInvalidDecl(); 7509 } 7510 7511 if (!IsVariableTemplateSpecialization) 7512 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7513 7514 if (NewTemplate) { 7515 VarTemplateDecl *PrevVarTemplate = 7516 NewVD->getPreviousDecl() 7517 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7518 : nullptr; 7519 7520 // Check the template parameter list of this declaration, possibly 7521 // merging in the template parameter list from the previous variable 7522 // template declaration. 7523 if (CheckTemplateParameterList( 7524 TemplateParams, 7525 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7526 : nullptr, 7527 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7528 DC->isDependentContext()) 7529 ? TPC_ClassTemplateMember 7530 : TPC_VarTemplate)) 7531 NewVD->setInvalidDecl(); 7532 7533 // If we are providing an explicit specialization of a static variable 7534 // template, make a note of that. 7535 if (PrevVarTemplate && 7536 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7537 PrevVarTemplate->setMemberSpecialization(); 7538 } 7539 } 7540 7541 // Diagnose shadowed variables iff this isn't a redeclaration. 7542 if (ShadowedDecl && !D.isRedeclaration()) 7543 CheckShadow(NewVD, ShadowedDecl, Previous); 7544 7545 ProcessPragmaWeak(S, NewVD); 7546 7547 // If this is the first declaration of an extern C variable, update 7548 // the map of such variables. 7549 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7550 isIncompleteDeclExternC(*this, NewVD)) 7551 RegisterLocallyScopedExternCDecl(NewVD, S); 7552 7553 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7554 MangleNumberingContext *MCtx; 7555 Decl *ManglingContextDecl; 7556 std::tie(MCtx, ManglingContextDecl) = 7557 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7558 if (MCtx) { 7559 Context.setManglingNumber( 7560 NewVD, MCtx->getManglingNumber( 7561 NewVD, getMSManglingNumber(getLangOpts(), S))); 7562 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7563 } 7564 } 7565 7566 // Special handling of variable named 'main'. 7567 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7568 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7569 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7570 7571 // C++ [basic.start.main]p3 7572 // A program that declares a variable main at global scope is ill-formed. 7573 if (getLangOpts().CPlusPlus) 7574 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7575 7576 // In C, and external-linkage variable named main results in undefined 7577 // behavior. 7578 else if (NewVD->hasExternalFormalLinkage()) 7579 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7580 } 7581 7582 if (D.isRedeclaration() && !Previous.empty()) { 7583 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7584 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7585 D.isFunctionDefinition()); 7586 } 7587 7588 if (NewTemplate) { 7589 if (NewVD->isInvalidDecl()) 7590 NewTemplate->setInvalidDecl(); 7591 ActOnDocumentableDecl(NewTemplate); 7592 return NewTemplate; 7593 } 7594 7595 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7596 CompleteMemberSpecialization(NewVD, Previous); 7597 7598 return NewVD; 7599 } 7600 7601 /// Enum describing the %select options in diag::warn_decl_shadow. 7602 enum ShadowedDeclKind { 7603 SDK_Local, 7604 SDK_Global, 7605 SDK_StaticMember, 7606 SDK_Field, 7607 SDK_Typedef, 7608 SDK_Using, 7609 SDK_StructuredBinding 7610 }; 7611 7612 /// Determine what kind of declaration we're shadowing. 7613 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7614 const DeclContext *OldDC) { 7615 if (isa<TypeAliasDecl>(ShadowedDecl)) 7616 return SDK_Using; 7617 else if (isa<TypedefDecl>(ShadowedDecl)) 7618 return SDK_Typedef; 7619 else if (isa<BindingDecl>(ShadowedDecl)) 7620 return SDK_StructuredBinding; 7621 else if (isa<RecordDecl>(OldDC)) 7622 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7623 7624 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7625 } 7626 7627 /// Return the location of the capture if the given lambda captures the given 7628 /// variable \p VD, or an invalid source location otherwise. 7629 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7630 const VarDecl *VD) { 7631 for (const Capture &Capture : LSI->Captures) { 7632 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7633 return Capture.getLocation(); 7634 } 7635 return SourceLocation(); 7636 } 7637 7638 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7639 const LookupResult &R) { 7640 // Only diagnose if we're shadowing an unambiguous field or variable. 7641 if (R.getResultKind() != LookupResult::Found) 7642 return false; 7643 7644 // Return false if warning is ignored. 7645 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7646 } 7647 7648 /// Return the declaration shadowed by the given variable \p D, or null 7649 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7650 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7651 const LookupResult &R) { 7652 if (!shouldWarnIfShadowedDecl(Diags, R)) 7653 return nullptr; 7654 7655 // Don't diagnose declarations at file scope. 7656 if (D->hasGlobalStorage()) 7657 return nullptr; 7658 7659 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7660 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7661 : nullptr; 7662 } 7663 7664 /// Return the declaration shadowed by the given typedef \p D, or null 7665 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7666 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7667 const LookupResult &R) { 7668 // Don't warn if typedef declaration is part of a class 7669 if (D->getDeclContext()->isRecord()) 7670 return nullptr; 7671 7672 if (!shouldWarnIfShadowedDecl(Diags, R)) 7673 return nullptr; 7674 7675 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7676 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7677 } 7678 7679 /// Return the declaration shadowed by the given variable \p D, or null 7680 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7681 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7682 const LookupResult &R) { 7683 if (!shouldWarnIfShadowedDecl(Diags, R)) 7684 return nullptr; 7685 7686 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7687 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7688 : nullptr; 7689 } 7690 7691 /// Diagnose variable or built-in function shadowing. Implements 7692 /// -Wshadow. 7693 /// 7694 /// This method is called whenever a VarDecl is added to a "useful" 7695 /// scope. 7696 /// 7697 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7698 /// \param R the lookup of the name 7699 /// 7700 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7701 const LookupResult &R) { 7702 DeclContext *NewDC = D->getDeclContext(); 7703 7704 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7705 // Fields are not shadowed by variables in C++ static methods. 7706 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7707 if (MD->isStatic()) 7708 return; 7709 7710 // Fields shadowed by constructor parameters are a special case. Usually 7711 // the constructor initializes the field with the parameter. 7712 if (isa<CXXConstructorDecl>(NewDC)) 7713 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7714 // Remember that this was shadowed so we can either warn about its 7715 // modification or its existence depending on warning settings. 7716 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7717 return; 7718 } 7719 } 7720 7721 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7722 if (shadowedVar->isExternC()) { 7723 // For shadowing external vars, make sure that we point to the global 7724 // declaration, not a locally scoped extern declaration. 7725 for (auto I : shadowedVar->redecls()) 7726 if (I->isFileVarDecl()) { 7727 ShadowedDecl = I; 7728 break; 7729 } 7730 } 7731 7732 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7733 7734 unsigned WarningDiag = diag::warn_decl_shadow; 7735 SourceLocation CaptureLoc; 7736 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7737 isa<CXXMethodDecl>(NewDC)) { 7738 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7739 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7740 if (RD->getLambdaCaptureDefault() == LCD_None) { 7741 // Try to avoid warnings for lambdas with an explicit capture list. 7742 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7743 // Warn only when the lambda captures the shadowed decl explicitly. 7744 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7745 if (CaptureLoc.isInvalid()) 7746 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7747 } else { 7748 // Remember that this was shadowed so we can avoid the warning if the 7749 // shadowed decl isn't captured and the warning settings allow it. 7750 cast<LambdaScopeInfo>(getCurFunction()) 7751 ->ShadowingDecls.push_back( 7752 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7753 return; 7754 } 7755 } 7756 7757 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7758 // A variable can't shadow a local variable in an enclosing scope, if 7759 // they are separated by a non-capturing declaration context. 7760 for (DeclContext *ParentDC = NewDC; 7761 ParentDC && !ParentDC->Equals(OldDC); 7762 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7763 // Only block literals, captured statements, and lambda expressions 7764 // can capture; other scopes don't. 7765 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7766 !isLambdaCallOperator(ParentDC)) { 7767 return; 7768 } 7769 } 7770 } 7771 } 7772 } 7773 7774 // Only warn about certain kinds of shadowing for class members. 7775 if (NewDC && NewDC->isRecord()) { 7776 // In particular, don't warn about shadowing non-class members. 7777 if (!OldDC->isRecord()) 7778 return; 7779 7780 // TODO: should we warn about static data members shadowing 7781 // static data members from base classes? 7782 7783 // TODO: don't diagnose for inaccessible shadowed members. 7784 // This is hard to do perfectly because we might friend the 7785 // shadowing context, but that's just a false negative. 7786 } 7787 7788 7789 DeclarationName Name = R.getLookupName(); 7790 7791 // Emit warning and note. 7792 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7793 return; 7794 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7795 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7796 if (!CaptureLoc.isInvalid()) 7797 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7798 << Name << /*explicitly*/ 1; 7799 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7800 } 7801 7802 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7803 /// when these variables are captured by the lambda. 7804 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7805 for (const auto &Shadow : LSI->ShadowingDecls) { 7806 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7807 // Try to avoid the warning when the shadowed decl isn't captured. 7808 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7809 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7810 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7811 ? diag::warn_decl_shadow_uncaptured_local 7812 : diag::warn_decl_shadow) 7813 << Shadow.VD->getDeclName() 7814 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7815 if (!CaptureLoc.isInvalid()) 7816 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7817 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7818 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7819 } 7820 } 7821 7822 /// Check -Wshadow without the advantage of a previous lookup. 7823 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7824 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7825 return; 7826 7827 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7828 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7829 LookupName(R, S); 7830 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7831 CheckShadow(D, ShadowedDecl, R); 7832 } 7833 7834 /// Check if 'E', which is an expression that is about to be modified, refers 7835 /// to a constructor parameter that shadows a field. 7836 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7837 // Quickly ignore expressions that can't be shadowing ctor parameters. 7838 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7839 return; 7840 E = E->IgnoreParenImpCasts(); 7841 auto *DRE = dyn_cast<DeclRefExpr>(E); 7842 if (!DRE) 7843 return; 7844 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7845 auto I = ShadowingDecls.find(D); 7846 if (I == ShadowingDecls.end()) 7847 return; 7848 const NamedDecl *ShadowedDecl = I->second; 7849 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7850 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7851 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7852 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7853 7854 // Avoid issuing multiple warnings about the same decl. 7855 ShadowingDecls.erase(I); 7856 } 7857 7858 /// Check for conflict between this global or extern "C" declaration and 7859 /// previous global or extern "C" declarations. This is only used in C++. 7860 template<typename T> 7861 static bool checkGlobalOrExternCConflict( 7862 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7863 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7864 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7865 7866 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7867 // The common case: this global doesn't conflict with any extern "C" 7868 // declaration. 7869 return false; 7870 } 7871 7872 if (Prev) { 7873 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7874 // Both the old and new declarations have C language linkage. This is a 7875 // redeclaration. 7876 Previous.clear(); 7877 Previous.addDecl(Prev); 7878 return true; 7879 } 7880 7881 // This is a global, non-extern "C" declaration, and there is a previous 7882 // non-global extern "C" declaration. Diagnose if this is a variable 7883 // declaration. 7884 if (!isa<VarDecl>(ND)) 7885 return false; 7886 } else { 7887 // The declaration is extern "C". Check for any declaration in the 7888 // translation unit which might conflict. 7889 if (IsGlobal) { 7890 // We have already performed the lookup into the translation unit. 7891 IsGlobal = false; 7892 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7893 I != E; ++I) { 7894 if (isa<VarDecl>(*I)) { 7895 Prev = *I; 7896 break; 7897 } 7898 } 7899 } else { 7900 DeclContext::lookup_result R = 7901 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7902 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7903 I != E; ++I) { 7904 if (isa<VarDecl>(*I)) { 7905 Prev = *I; 7906 break; 7907 } 7908 // FIXME: If we have any other entity with this name in global scope, 7909 // the declaration is ill-formed, but that is a defect: it breaks the 7910 // 'stat' hack, for instance. Only variables can have mangled name 7911 // clashes with extern "C" declarations, so only they deserve a 7912 // diagnostic. 7913 } 7914 } 7915 7916 if (!Prev) 7917 return false; 7918 } 7919 7920 // Use the first declaration's location to ensure we point at something which 7921 // is lexically inside an extern "C" linkage-spec. 7922 assert(Prev && "should have found a previous declaration to diagnose"); 7923 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7924 Prev = FD->getFirstDecl(); 7925 else 7926 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7927 7928 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7929 << IsGlobal << ND; 7930 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7931 << IsGlobal; 7932 return false; 7933 } 7934 7935 /// Apply special rules for handling extern "C" declarations. Returns \c true 7936 /// if we have found that this is a redeclaration of some prior entity. 7937 /// 7938 /// Per C++ [dcl.link]p6: 7939 /// Two declarations [for a function or variable] with C language linkage 7940 /// with the same name that appear in different scopes refer to the same 7941 /// [entity]. An entity with C language linkage shall not be declared with 7942 /// the same name as an entity in global scope. 7943 template<typename T> 7944 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7945 LookupResult &Previous) { 7946 if (!S.getLangOpts().CPlusPlus) { 7947 // In C, when declaring a global variable, look for a corresponding 'extern' 7948 // variable declared in function scope. We don't need this in C++, because 7949 // we find local extern decls in the surrounding file-scope DeclContext. 7950 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7951 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7952 Previous.clear(); 7953 Previous.addDecl(Prev); 7954 return true; 7955 } 7956 } 7957 return false; 7958 } 7959 7960 // A declaration in the translation unit can conflict with an extern "C" 7961 // declaration. 7962 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7963 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7964 7965 // An extern "C" declaration can conflict with a declaration in the 7966 // translation unit or can be a redeclaration of an extern "C" declaration 7967 // in another scope. 7968 if (isIncompleteDeclExternC(S,ND)) 7969 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7970 7971 // Neither global nor extern "C": nothing to do. 7972 return false; 7973 } 7974 7975 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7976 // If the decl is already known invalid, don't check it. 7977 if (NewVD->isInvalidDecl()) 7978 return; 7979 7980 QualType T = NewVD->getType(); 7981 7982 // Defer checking an 'auto' type until its initializer is attached. 7983 if (T->isUndeducedType()) 7984 return; 7985 7986 if (NewVD->hasAttrs()) 7987 CheckAlignasUnderalignment(NewVD); 7988 7989 if (T->isObjCObjectType()) { 7990 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7991 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7992 T = Context.getObjCObjectPointerType(T); 7993 NewVD->setType(T); 7994 } 7995 7996 // Emit an error if an address space was applied to decl with local storage. 7997 // This includes arrays of objects with address space qualifiers, but not 7998 // automatic variables that point to other address spaces. 7999 // ISO/IEC TR 18037 S5.1.2 8000 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8001 T.getAddressSpace() != LangAS::Default) { 8002 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 8007 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8008 // scope. 8009 if (getLangOpts().OpenCLVersion == 120 && 8010 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8011 getLangOpts()) && 8012 NewVD->isStaticLocal()) { 8013 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8014 NewVD->setInvalidDecl(); 8015 return; 8016 } 8017 8018 if (getLangOpts().OpenCL) { 8019 if (!diagnoseOpenCLTypes(*this, NewVD)) 8020 return; 8021 8022 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8023 if (NewVD->hasAttr<BlocksAttr>()) { 8024 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8025 return; 8026 } 8027 8028 if (T->isBlockPointerType()) { 8029 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8030 // can't use 'extern' storage class. 8031 if (!T.isConstQualified()) { 8032 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8033 << 0 /*const*/; 8034 NewVD->setInvalidDecl(); 8035 return; 8036 } 8037 if (NewVD->hasExternalStorage()) { 8038 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8039 NewVD->setInvalidDecl(); 8040 return; 8041 } 8042 } 8043 8044 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8045 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8046 NewVD->hasExternalStorage()) { 8047 if (!T->isSamplerT() && !T->isDependentType() && 8048 !(T.getAddressSpace() == LangAS::opencl_constant || 8049 (T.getAddressSpace() == LangAS::opencl_global && 8050 getOpenCLOptions().areProgramScopeVariablesSupported( 8051 getLangOpts())))) { 8052 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8053 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8054 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8055 << Scope << "global or constant"; 8056 else 8057 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8058 << Scope << "constant"; 8059 NewVD->setInvalidDecl(); 8060 return; 8061 } 8062 } else { 8063 if (T.getAddressSpace() == LangAS::opencl_global) { 8064 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8065 << 1 /*is any function*/ << "global"; 8066 NewVD->setInvalidDecl(); 8067 return; 8068 } 8069 if (T.getAddressSpace() == LangAS::opencl_constant || 8070 T.getAddressSpace() == LangAS::opencl_local) { 8071 FunctionDecl *FD = getCurFunctionDecl(); 8072 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8073 // in functions. 8074 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8075 if (T.getAddressSpace() == LangAS::opencl_constant) 8076 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8077 << 0 /*non-kernel only*/ << "constant"; 8078 else 8079 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8080 << 0 /*non-kernel only*/ << "local"; 8081 NewVD->setInvalidDecl(); 8082 return; 8083 } 8084 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8085 // in the outermost scope of a kernel function. 8086 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8087 if (!getCurScope()->isFunctionScope()) { 8088 if (T.getAddressSpace() == LangAS::opencl_constant) 8089 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8090 << "constant"; 8091 else 8092 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8093 << "local"; 8094 NewVD->setInvalidDecl(); 8095 return; 8096 } 8097 } 8098 } else if (T.getAddressSpace() != LangAS::opencl_private && 8099 // If we are parsing a template we didn't deduce an addr 8100 // space yet. 8101 T.getAddressSpace() != LangAS::Default) { 8102 // Do not allow other address spaces on automatic variable. 8103 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8104 NewVD->setInvalidDecl(); 8105 return; 8106 } 8107 } 8108 } 8109 8110 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8111 && !NewVD->hasAttr<BlocksAttr>()) { 8112 if (getLangOpts().getGC() != LangOptions::NonGC) 8113 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8114 else { 8115 assert(!getLangOpts().ObjCAutoRefCount); 8116 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8117 } 8118 } 8119 8120 bool isVM = T->isVariablyModifiedType(); 8121 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8122 NewVD->hasAttr<BlocksAttr>()) 8123 setFunctionHasBranchProtectedScope(); 8124 8125 if ((isVM && NewVD->hasLinkage()) || 8126 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8127 bool SizeIsNegative; 8128 llvm::APSInt Oversized; 8129 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8130 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8131 QualType FixedT; 8132 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8133 FixedT = FixedTInfo->getType(); 8134 else if (FixedTInfo) { 8135 // Type and type-as-written are canonically different. We need to fix up 8136 // both types separately. 8137 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8138 Oversized); 8139 } 8140 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8141 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8142 // FIXME: This won't give the correct result for 8143 // int a[10][n]; 8144 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8145 8146 if (NewVD->isFileVarDecl()) 8147 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8148 << SizeRange; 8149 else if (NewVD->isStaticLocal()) 8150 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8151 << SizeRange; 8152 else 8153 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8154 << SizeRange; 8155 NewVD->setInvalidDecl(); 8156 return; 8157 } 8158 8159 if (!FixedTInfo) { 8160 if (NewVD->isFileVarDecl()) 8161 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8162 else 8163 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8164 NewVD->setInvalidDecl(); 8165 return; 8166 } 8167 8168 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8169 NewVD->setType(FixedT); 8170 NewVD->setTypeSourceInfo(FixedTInfo); 8171 } 8172 8173 if (T->isVoidType()) { 8174 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8175 // of objects and functions. 8176 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8177 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8178 << T; 8179 NewVD->setInvalidDecl(); 8180 return; 8181 } 8182 } 8183 8184 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8185 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8186 NewVD->setInvalidDecl(); 8187 return; 8188 } 8189 8190 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8191 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8192 NewVD->setInvalidDecl(); 8193 return; 8194 } 8195 8196 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8197 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8198 NewVD->setInvalidDecl(); 8199 return; 8200 } 8201 8202 if (NewVD->isConstexpr() && !T->isDependentType() && 8203 RequireLiteralType(NewVD->getLocation(), T, 8204 diag::err_constexpr_var_non_literal)) { 8205 NewVD->setInvalidDecl(); 8206 return; 8207 } 8208 8209 // PPC MMA non-pointer types are not allowed as non-local variable types. 8210 if (Context.getTargetInfo().getTriple().isPPC64() && 8211 !NewVD->isLocalVarDecl() && 8212 CheckPPCMMAType(T, NewVD->getLocation())) { 8213 NewVD->setInvalidDecl(); 8214 return; 8215 } 8216 } 8217 8218 /// Perform semantic checking on a newly-created variable 8219 /// declaration. 8220 /// 8221 /// This routine performs all of the type-checking required for a 8222 /// variable declaration once it has been built. It is used both to 8223 /// check variables after they have been parsed and their declarators 8224 /// have been translated into a declaration, and to check variables 8225 /// that have been instantiated from a template. 8226 /// 8227 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8228 /// 8229 /// Returns true if the variable declaration is a redeclaration. 8230 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8231 CheckVariableDeclarationType(NewVD); 8232 8233 // If the decl is already known invalid, don't check it. 8234 if (NewVD->isInvalidDecl()) 8235 return false; 8236 8237 // If we did not find anything by this name, look for a non-visible 8238 // extern "C" declaration with the same name. 8239 if (Previous.empty() && 8240 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8241 Previous.setShadowed(); 8242 8243 if (!Previous.empty()) { 8244 MergeVarDecl(NewVD, Previous); 8245 return true; 8246 } 8247 return false; 8248 } 8249 8250 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8251 /// and if so, check that it's a valid override and remember it. 8252 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8253 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8254 8255 // Look for methods in base classes that this method might override. 8256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8257 /*DetectVirtual=*/false); 8258 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8259 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8260 DeclarationName Name = MD->getDeclName(); 8261 8262 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8263 // We really want to find the base class destructor here. 8264 QualType T = Context.getTypeDeclType(BaseRecord); 8265 CanQualType CT = Context.getCanonicalType(T); 8266 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8267 } 8268 8269 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8270 CXXMethodDecl *BaseMD = 8271 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8272 if (!BaseMD || !BaseMD->isVirtual() || 8273 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8274 /*ConsiderCudaAttrs=*/true, 8275 // C++2a [class.virtual]p2 does not consider requires 8276 // clauses when overriding. 8277 /*ConsiderRequiresClauses=*/false)) 8278 continue; 8279 8280 if (Overridden.insert(BaseMD).second) { 8281 MD->addOverriddenMethod(BaseMD); 8282 CheckOverridingFunctionReturnType(MD, BaseMD); 8283 CheckOverridingFunctionAttributes(MD, BaseMD); 8284 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8285 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8286 } 8287 8288 // A method can only override one function from each base class. We 8289 // don't track indirectly overridden methods from bases of bases. 8290 return true; 8291 } 8292 8293 return false; 8294 }; 8295 8296 DC->lookupInBases(VisitBase, Paths); 8297 return !Overridden.empty(); 8298 } 8299 8300 namespace { 8301 // Struct for holding all of the extra arguments needed by 8302 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8303 struct ActOnFDArgs { 8304 Scope *S; 8305 Declarator &D; 8306 MultiTemplateParamsArg TemplateParamLists; 8307 bool AddToScope; 8308 }; 8309 } // end anonymous namespace 8310 8311 namespace { 8312 8313 // Callback to only accept typo corrections that have a non-zero edit distance. 8314 // Also only accept corrections that have the same parent decl. 8315 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8316 public: 8317 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8318 CXXRecordDecl *Parent) 8319 : Context(Context), OriginalFD(TypoFD), 8320 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8321 8322 bool ValidateCandidate(const TypoCorrection &candidate) override { 8323 if (candidate.getEditDistance() == 0) 8324 return false; 8325 8326 SmallVector<unsigned, 1> MismatchedParams; 8327 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8328 CDeclEnd = candidate.end(); 8329 CDecl != CDeclEnd; ++CDecl) { 8330 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8331 8332 if (FD && !FD->hasBody() && 8333 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8334 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8335 CXXRecordDecl *Parent = MD->getParent(); 8336 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8337 return true; 8338 } else if (!ExpectedParent) { 8339 return true; 8340 } 8341 } 8342 } 8343 8344 return false; 8345 } 8346 8347 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8348 return std::make_unique<DifferentNameValidatorCCC>(*this); 8349 } 8350 8351 private: 8352 ASTContext &Context; 8353 FunctionDecl *OriginalFD; 8354 CXXRecordDecl *ExpectedParent; 8355 }; 8356 8357 } // end anonymous namespace 8358 8359 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8360 TypoCorrectedFunctionDefinitions.insert(F); 8361 } 8362 8363 /// Generate diagnostics for an invalid function redeclaration. 8364 /// 8365 /// This routine handles generating the diagnostic messages for an invalid 8366 /// function redeclaration, including finding possible similar declarations 8367 /// or performing typo correction if there are no previous declarations with 8368 /// the same name. 8369 /// 8370 /// Returns a NamedDecl iff typo correction was performed and substituting in 8371 /// the new declaration name does not cause new errors. 8372 static NamedDecl *DiagnoseInvalidRedeclaration( 8373 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8374 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8375 DeclarationName Name = NewFD->getDeclName(); 8376 DeclContext *NewDC = NewFD->getDeclContext(); 8377 SmallVector<unsigned, 1> MismatchedParams; 8378 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8379 TypoCorrection Correction; 8380 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8381 unsigned DiagMsg = 8382 IsLocalFriend ? diag::err_no_matching_local_friend : 8383 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8384 diag::err_member_decl_does_not_match; 8385 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8386 IsLocalFriend ? Sema::LookupLocalFriendName 8387 : Sema::LookupOrdinaryName, 8388 Sema::ForVisibleRedeclaration); 8389 8390 NewFD->setInvalidDecl(); 8391 if (IsLocalFriend) 8392 SemaRef.LookupName(Prev, S); 8393 else 8394 SemaRef.LookupQualifiedName(Prev, NewDC); 8395 assert(!Prev.isAmbiguous() && 8396 "Cannot have an ambiguity in previous-declaration lookup"); 8397 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8398 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8399 MD ? MD->getParent() : nullptr); 8400 if (!Prev.empty()) { 8401 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8402 Func != FuncEnd; ++Func) { 8403 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8404 if (FD && 8405 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8406 // Add 1 to the index so that 0 can mean the mismatch didn't 8407 // involve a parameter 8408 unsigned ParamNum = 8409 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8410 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8411 } 8412 } 8413 // If the qualified name lookup yielded nothing, try typo correction 8414 } else if ((Correction = SemaRef.CorrectTypo( 8415 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8416 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8417 IsLocalFriend ? nullptr : NewDC))) { 8418 // Set up everything for the call to ActOnFunctionDeclarator 8419 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8420 ExtraArgs.D.getIdentifierLoc()); 8421 Previous.clear(); 8422 Previous.setLookupName(Correction.getCorrection()); 8423 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8424 CDeclEnd = Correction.end(); 8425 CDecl != CDeclEnd; ++CDecl) { 8426 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8427 if (FD && !FD->hasBody() && 8428 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8429 Previous.addDecl(FD); 8430 } 8431 } 8432 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8433 8434 NamedDecl *Result; 8435 // Retry building the function declaration with the new previous 8436 // declarations, and with errors suppressed. 8437 { 8438 // Trap errors. 8439 Sema::SFINAETrap Trap(SemaRef); 8440 8441 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8442 // pieces need to verify the typo-corrected C++ declaration and hopefully 8443 // eliminate the need for the parameter pack ExtraArgs. 8444 Result = SemaRef.ActOnFunctionDeclarator( 8445 ExtraArgs.S, ExtraArgs.D, 8446 Correction.getCorrectionDecl()->getDeclContext(), 8447 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8448 ExtraArgs.AddToScope); 8449 8450 if (Trap.hasErrorOccurred()) 8451 Result = nullptr; 8452 } 8453 8454 if (Result) { 8455 // Determine which correction we picked. 8456 Decl *Canonical = Result->getCanonicalDecl(); 8457 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8458 I != E; ++I) 8459 if ((*I)->getCanonicalDecl() == Canonical) 8460 Correction.setCorrectionDecl(*I); 8461 8462 // Let Sema know about the correction. 8463 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8464 SemaRef.diagnoseTypo( 8465 Correction, 8466 SemaRef.PDiag(IsLocalFriend 8467 ? diag::err_no_matching_local_friend_suggest 8468 : diag::err_member_decl_does_not_match_suggest) 8469 << Name << NewDC << IsDefinition); 8470 return Result; 8471 } 8472 8473 // Pretend the typo correction never occurred 8474 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8475 ExtraArgs.D.getIdentifierLoc()); 8476 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8477 Previous.clear(); 8478 Previous.setLookupName(Name); 8479 } 8480 8481 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8482 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8483 8484 bool NewFDisConst = false; 8485 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8486 NewFDisConst = NewMD->isConst(); 8487 8488 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8489 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8490 NearMatch != NearMatchEnd; ++NearMatch) { 8491 FunctionDecl *FD = NearMatch->first; 8492 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8493 bool FDisConst = MD && MD->isConst(); 8494 bool IsMember = MD || !IsLocalFriend; 8495 8496 // FIXME: These notes are poorly worded for the local friend case. 8497 if (unsigned Idx = NearMatch->second) { 8498 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8499 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8500 if (Loc.isInvalid()) Loc = FD->getLocation(); 8501 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8502 : diag::note_local_decl_close_param_match) 8503 << Idx << FDParam->getType() 8504 << NewFD->getParamDecl(Idx - 1)->getType(); 8505 } else if (FDisConst != NewFDisConst) { 8506 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8507 << NewFDisConst << FD->getSourceRange().getEnd(); 8508 } else 8509 SemaRef.Diag(FD->getLocation(), 8510 IsMember ? diag::note_member_def_close_match 8511 : diag::note_local_decl_close_match); 8512 } 8513 return nullptr; 8514 } 8515 8516 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8517 switch (D.getDeclSpec().getStorageClassSpec()) { 8518 default: llvm_unreachable("Unknown storage class!"); 8519 case DeclSpec::SCS_auto: 8520 case DeclSpec::SCS_register: 8521 case DeclSpec::SCS_mutable: 8522 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8523 diag::err_typecheck_sclass_func); 8524 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8525 D.setInvalidType(); 8526 break; 8527 case DeclSpec::SCS_unspecified: break; 8528 case DeclSpec::SCS_extern: 8529 if (D.getDeclSpec().isExternInLinkageSpec()) 8530 return SC_None; 8531 return SC_Extern; 8532 case DeclSpec::SCS_static: { 8533 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8534 // C99 6.7.1p5: 8535 // The declaration of an identifier for a function that has 8536 // block scope shall have no explicit storage-class specifier 8537 // other than extern 8538 // See also (C++ [dcl.stc]p4). 8539 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8540 diag::err_static_block_func); 8541 break; 8542 } else 8543 return SC_Static; 8544 } 8545 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8546 } 8547 8548 // No explicit storage class has already been returned 8549 return SC_None; 8550 } 8551 8552 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8553 DeclContext *DC, QualType &R, 8554 TypeSourceInfo *TInfo, 8555 StorageClass SC, 8556 bool &IsVirtualOkay) { 8557 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8558 DeclarationName Name = NameInfo.getName(); 8559 8560 FunctionDecl *NewFD = nullptr; 8561 bool isInline = D.getDeclSpec().isInlineSpecified(); 8562 8563 if (!SemaRef.getLangOpts().CPlusPlus) { 8564 // Determine whether the function was written with a 8565 // prototype. This true when: 8566 // - there is a prototype in the declarator, or 8567 // - the type R of the function is some kind of typedef or other non- 8568 // attributed reference to a type name (which eventually refers to a 8569 // function type). 8570 bool HasPrototype = 8571 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8572 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8573 8574 NewFD = FunctionDecl::Create( 8575 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8576 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8577 ConstexprSpecKind::Unspecified, 8578 /*TrailingRequiresClause=*/nullptr); 8579 if (D.isInvalidType()) 8580 NewFD->setInvalidDecl(); 8581 8582 return NewFD; 8583 } 8584 8585 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8586 8587 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8588 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8589 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8590 diag::err_constexpr_wrong_decl_kind) 8591 << static_cast<int>(ConstexprKind); 8592 ConstexprKind = ConstexprSpecKind::Unspecified; 8593 D.getMutableDeclSpec().ClearConstexprSpec(); 8594 } 8595 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8596 8597 // Check that the return type is not an abstract class type. 8598 // For record types, this is done by the AbstractClassUsageDiagnoser once 8599 // the class has been completely parsed. 8600 if (!DC->isRecord() && 8601 SemaRef.RequireNonAbstractType( 8602 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8603 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8604 D.setInvalidType(); 8605 8606 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8607 // This is a C++ constructor declaration. 8608 assert(DC->isRecord() && 8609 "Constructors can only be declared in a member context"); 8610 8611 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8612 return CXXConstructorDecl::Create( 8613 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8614 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8615 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8616 InheritedConstructor(), TrailingRequiresClause); 8617 8618 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8619 // This is a C++ destructor declaration. 8620 if (DC->isRecord()) { 8621 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8622 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8623 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8624 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8625 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8626 /*isImplicitlyDeclared=*/false, ConstexprKind, 8627 TrailingRequiresClause); 8628 8629 // If the destructor needs an implicit exception specification, set it 8630 // now. FIXME: It'd be nice to be able to create the right type to start 8631 // with, but the type needs to reference the destructor declaration. 8632 if (SemaRef.getLangOpts().CPlusPlus11) 8633 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8634 8635 IsVirtualOkay = true; 8636 return NewDD; 8637 8638 } else { 8639 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8640 D.setInvalidType(); 8641 8642 // Create a FunctionDecl to satisfy the function definition parsing 8643 // code path. 8644 return FunctionDecl::Create( 8645 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8646 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8647 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8648 } 8649 8650 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8651 if (!DC->isRecord()) { 8652 SemaRef.Diag(D.getIdentifierLoc(), 8653 diag::err_conv_function_not_member); 8654 return nullptr; 8655 } 8656 8657 SemaRef.CheckConversionDeclarator(D, R, SC); 8658 if (D.isInvalidType()) 8659 return nullptr; 8660 8661 IsVirtualOkay = true; 8662 return CXXConversionDecl::Create( 8663 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8664 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8665 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8666 TrailingRequiresClause); 8667 8668 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8669 if (TrailingRequiresClause) 8670 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8671 diag::err_trailing_requires_clause_on_deduction_guide) 8672 << TrailingRequiresClause->getSourceRange(); 8673 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8674 8675 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8676 ExplicitSpecifier, NameInfo, R, TInfo, 8677 D.getEndLoc()); 8678 } else if (DC->isRecord()) { 8679 // If the name of the function is the same as the name of the record, 8680 // then this must be an invalid constructor that has a return type. 8681 // (The parser checks for a return type and makes the declarator a 8682 // constructor if it has no return type). 8683 if (Name.getAsIdentifierInfo() && 8684 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8685 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8686 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8687 << SourceRange(D.getIdentifierLoc()); 8688 return nullptr; 8689 } 8690 8691 // This is a C++ method declaration. 8692 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8693 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8694 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8695 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8696 IsVirtualOkay = !Ret->isStatic(); 8697 return Ret; 8698 } else { 8699 bool isFriend = 8700 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8701 if (!isFriend && SemaRef.CurContext->isRecord()) 8702 return nullptr; 8703 8704 // Determine whether the function was written with a 8705 // prototype. This true when: 8706 // - we're in C++ (where every function has a prototype), 8707 return FunctionDecl::Create( 8708 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8709 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8710 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8711 } 8712 } 8713 8714 enum OpenCLParamType { 8715 ValidKernelParam, 8716 PtrPtrKernelParam, 8717 PtrKernelParam, 8718 InvalidAddrSpacePtrKernelParam, 8719 InvalidKernelParam, 8720 RecordKernelParam 8721 }; 8722 8723 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8724 // Size dependent types are just typedefs to normal integer types 8725 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8726 // integers other than by their names. 8727 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8728 8729 // Remove typedefs one by one until we reach a typedef 8730 // for a size dependent type. 8731 QualType DesugaredTy = Ty; 8732 do { 8733 ArrayRef<StringRef> Names(SizeTypeNames); 8734 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8735 if (Names.end() != Match) 8736 return true; 8737 8738 Ty = DesugaredTy; 8739 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8740 } while (DesugaredTy != Ty); 8741 8742 return false; 8743 } 8744 8745 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8746 if (PT->isDependentType()) 8747 return InvalidKernelParam; 8748 8749 if (PT->isPointerType() || PT->isReferenceType()) { 8750 QualType PointeeType = PT->getPointeeType(); 8751 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8752 PointeeType.getAddressSpace() == LangAS::opencl_private || 8753 PointeeType.getAddressSpace() == LangAS::Default) 8754 return InvalidAddrSpacePtrKernelParam; 8755 8756 if (PointeeType->isPointerType()) { 8757 // This is a pointer to pointer parameter. 8758 // Recursively check inner type. 8759 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8760 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8761 ParamKind == InvalidKernelParam) 8762 return ParamKind; 8763 8764 return PtrPtrKernelParam; 8765 } 8766 8767 // C++ for OpenCL v1.0 s2.4: 8768 // Moreover the types used in parameters of the kernel functions must be: 8769 // Standard layout types for pointer parameters. The same applies to 8770 // reference if an implementation supports them in kernel parameters. 8771 if (S.getLangOpts().OpenCLCPlusPlus && 8772 !S.getOpenCLOptions().isAvailableOption( 8773 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8774 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8775 !PointeeType->isStandardLayoutType()) 8776 return InvalidKernelParam; 8777 8778 return PtrKernelParam; 8779 } 8780 8781 // OpenCL v1.2 s6.9.k: 8782 // Arguments to kernel functions in a program cannot be declared with the 8783 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8784 // uintptr_t or a struct and/or union that contain fields declared to be one 8785 // of these built-in scalar types. 8786 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8787 return InvalidKernelParam; 8788 8789 if (PT->isImageType()) 8790 return PtrKernelParam; 8791 8792 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8793 return InvalidKernelParam; 8794 8795 // OpenCL extension spec v1.2 s9.5: 8796 // This extension adds support for half scalar and vector types as built-in 8797 // types that can be used for arithmetic operations, conversions etc. 8798 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8799 PT->isHalfType()) 8800 return InvalidKernelParam; 8801 8802 // Look into an array argument to check if it has a forbidden type. 8803 if (PT->isArrayType()) { 8804 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8805 // Call ourself to check an underlying type of an array. Since the 8806 // getPointeeOrArrayElementType returns an innermost type which is not an 8807 // array, this recursive call only happens once. 8808 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8809 } 8810 8811 // C++ for OpenCL v1.0 s2.4: 8812 // Moreover the types used in parameters of the kernel functions must be: 8813 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8814 // types) for parameters passed by value; 8815 if (S.getLangOpts().OpenCLCPlusPlus && 8816 !S.getOpenCLOptions().isAvailableOption( 8817 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8818 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8819 return InvalidKernelParam; 8820 8821 if (PT->isRecordType()) 8822 return RecordKernelParam; 8823 8824 return ValidKernelParam; 8825 } 8826 8827 static void checkIsValidOpenCLKernelParameter( 8828 Sema &S, 8829 Declarator &D, 8830 ParmVarDecl *Param, 8831 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8832 QualType PT = Param->getType(); 8833 8834 // Cache the valid types we encounter to avoid rechecking structs that are 8835 // used again 8836 if (ValidTypes.count(PT.getTypePtr())) 8837 return; 8838 8839 switch (getOpenCLKernelParameterType(S, PT)) { 8840 case PtrPtrKernelParam: 8841 // OpenCL v3.0 s6.11.a: 8842 // A kernel function argument cannot be declared as a pointer to a pointer 8843 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8844 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8845 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8846 D.setInvalidType(); 8847 return; 8848 } 8849 8850 ValidTypes.insert(PT.getTypePtr()); 8851 return; 8852 8853 case InvalidAddrSpacePtrKernelParam: 8854 // OpenCL v1.0 s6.5: 8855 // __kernel function arguments declared to be a pointer of a type can point 8856 // to one of the following address spaces only : __global, __local or 8857 // __constant. 8858 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8859 D.setInvalidType(); 8860 return; 8861 8862 // OpenCL v1.2 s6.9.k: 8863 // Arguments to kernel functions in a program cannot be declared with the 8864 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8865 // uintptr_t or a struct and/or union that contain fields declared to be 8866 // one of these built-in scalar types. 8867 8868 case InvalidKernelParam: 8869 // OpenCL v1.2 s6.8 n: 8870 // A kernel function argument cannot be declared 8871 // of event_t type. 8872 // Do not diagnose half type since it is diagnosed as invalid argument 8873 // type for any function elsewhere. 8874 if (!PT->isHalfType()) { 8875 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8876 8877 // Explain what typedefs are involved. 8878 const TypedefType *Typedef = nullptr; 8879 while ((Typedef = PT->getAs<TypedefType>())) { 8880 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8881 // SourceLocation may be invalid for a built-in type. 8882 if (Loc.isValid()) 8883 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8884 PT = Typedef->desugar(); 8885 } 8886 } 8887 8888 D.setInvalidType(); 8889 return; 8890 8891 case PtrKernelParam: 8892 case ValidKernelParam: 8893 ValidTypes.insert(PT.getTypePtr()); 8894 return; 8895 8896 case RecordKernelParam: 8897 break; 8898 } 8899 8900 // Track nested structs we will inspect 8901 SmallVector<const Decl *, 4> VisitStack; 8902 8903 // Track where we are in the nested structs. Items will migrate from 8904 // VisitStack to HistoryStack as we do the DFS for bad field. 8905 SmallVector<const FieldDecl *, 4> HistoryStack; 8906 HistoryStack.push_back(nullptr); 8907 8908 // At this point we already handled everything except of a RecordType or 8909 // an ArrayType of a RecordType. 8910 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8911 const RecordType *RecTy = 8912 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8913 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8914 8915 VisitStack.push_back(RecTy->getDecl()); 8916 assert(VisitStack.back() && "First decl null?"); 8917 8918 do { 8919 const Decl *Next = VisitStack.pop_back_val(); 8920 if (!Next) { 8921 assert(!HistoryStack.empty()); 8922 // Found a marker, we have gone up a level 8923 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8924 ValidTypes.insert(Hist->getType().getTypePtr()); 8925 8926 continue; 8927 } 8928 8929 // Adds everything except the original parameter declaration (which is not a 8930 // field itself) to the history stack. 8931 const RecordDecl *RD; 8932 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8933 HistoryStack.push_back(Field); 8934 8935 QualType FieldTy = Field->getType(); 8936 // Other field types (known to be valid or invalid) are handled while we 8937 // walk around RecordDecl::fields(). 8938 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8939 "Unexpected type."); 8940 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8941 8942 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8943 } else { 8944 RD = cast<RecordDecl>(Next); 8945 } 8946 8947 // Add a null marker so we know when we've gone back up a level 8948 VisitStack.push_back(nullptr); 8949 8950 for (const auto *FD : RD->fields()) { 8951 QualType QT = FD->getType(); 8952 8953 if (ValidTypes.count(QT.getTypePtr())) 8954 continue; 8955 8956 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8957 if (ParamType == ValidKernelParam) 8958 continue; 8959 8960 if (ParamType == RecordKernelParam) { 8961 VisitStack.push_back(FD); 8962 continue; 8963 } 8964 8965 // OpenCL v1.2 s6.9.p: 8966 // Arguments to kernel functions that are declared to be a struct or union 8967 // do not allow OpenCL objects to be passed as elements of the struct or 8968 // union. 8969 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8970 ParamType == InvalidAddrSpacePtrKernelParam) { 8971 S.Diag(Param->getLocation(), 8972 diag::err_record_with_pointers_kernel_param) 8973 << PT->isUnionType() 8974 << PT; 8975 } else { 8976 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8977 } 8978 8979 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8980 << OrigRecDecl->getDeclName(); 8981 8982 // We have an error, now let's go back up through history and show where 8983 // the offending field came from 8984 for (ArrayRef<const FieldDecl *>::const_iterator 8985 I = HistoryStack.begin() + 1, 8986 E = HistoryStack.end(); 8987 I != E; ++I) { 8988 const FieldDecl *OuterField = *I; 8989 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8990 << OuterField->getType(); 8991 } 8992 8993 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8994 << QT->isPointerType() 8995 << QT; 8996 D.setInvalidType(); 8997 return; 8998 } 8999 } while (!VisitStack.empty()); 9000 } 9001 9002 /// Find the DeclContext in which a tag is implicitly declared if we see an 9003 /// elaborated type specifier in the specified context, and lookup finds 9004 /// nothing. 9005 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9006 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9007 DC = DC->getParent(); 9008 return DC; 9009 } 9010 9011 /// Find the Scope in which a tag is implicitly declared if we see an 9012 /// elaborated type specifier in the specified context, and lookup finds 9013 /// nothing. 9014 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9015 while (S->isClassScope() || 9016 (LangOpts.CPlusPlus && 9017 S->isFunctionPrototypeScope()) || 9018 ((S->getFlags() & Scope::DeclScope) == 0) || 9019 (S->getEntity() && S->getEntity()->isTransparentContext())) 9020 S = S->getParent(); 9021 return S; 9022 } 9023 9024 NamedDecl* 9025 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9026 TypeSourceInfo *TInfo, LookupResult &Previous, 9027 MultiTemplateParamsArg TemplateParamListsRef, 9028 bool &AddToScope) { 9029 QualType R = TInfo->getType(); 9030 9031 assert(R->isFunctionType()); 9032 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9033 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9034 9035 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9036 for (TemplateParameterList *TPL : TemplateParamListsRef) 9037 TemplateParamLists.push_back(TPL); 9038 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9039 if (!TemplateParamLists.empty() && 9040 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9041 TemplateParamLists.back() = Invented; 9042 else 9043 TemplateParamLists.push_back(Invented); 9044 } 9045 9046 // TODO: consider using NameInfo for diagnostic. 9047 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9048 DeclarationName Name = NameInfo.getName(); 9049 StorageClass SC = getFunctionStorageClass(*this, D); 9050 9051 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9052 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9053 diag::err_invalid_thread) 9054 << DeclSpec::getSpecifierName(TSCS); 9055 9056 if (D.isFirstDeclarationOfMember()) 9057 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9058 D.getIdentifierLoc()); 9059 9060 bool isFriend = false; 9061 FunctionTemplateDecl *FunctionTemplate = nullptr; 9062 bool isMemberSpecialization = false; 9063 bool isFunctionTemplateSpecialization = false; 9064 9065 bool isDependentClassScopeExplicitSpecialization = false; 9066 bool HasExplicitTemplateArgs = false; 9067 TemplateArgumentListInfo TemplateArgs; 9068 9069 bool isVirtualOkay = false; 9070 9071 DeclContext *OriginalDC = DC; 9072 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9073 9074 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9075 isVirtualOkay); 9076 if (!NewFD) return nullptr; 9077 9078 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9079 NewFD->setTopLevelDeclInObjCContainer(); 9080 9081 // Set the lexical context. If this is a function-scope declaration, or has a 9082 // C++ scope specifier, or is the object of a friend declaration, the lexical 9083 // context will be different from the semantic context. 9084 NewFD->setLexicalDeclContext(CurContext); 9085 9086 if (IsLocalExternDecl) 9087 NewFD->setLocalExternDecl(); 9088 9089 if (getLangOpts().CPlusPlus) { 9090 bool isInline = D.getDeclSpec().isInlineSpecified(); 9091 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9092 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9093 isFriend = D.getDeclSpec().isFriendSpecified(); 9094 if (isFriend && !isInline && D.isFunctionDefinition()) { 9095 // C++ [class.friend]p5 9096 // A function can be defined in a friend declaration of a 9097 // class . . . . Such a function is implicitly inline. 9098 NewFD->setImplicitlyInline(); 9099 } 9100 9101 // If this is a method defined in an __interface, and is not a constructor 9102 // or an overloaded operator, then set the pure flag (isVirtual will already 9103 // return true). 9104 if (const CXXRecordDecl *Parent = 9105 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9106 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9107 NewFD->setPure(true); 9108 9109 // C++ [class.union]p2 9110 // A union can have member functions, but not virtual functions. 9111 if (isVirtual && Parent->isUnion()) { 9112 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9113 NewFD->setInvalidDecl(); 9114 } 9115 } 9116 9117 SetNestedNameSpecifier(*this, NewFD, D); 9118 isMemberSpecialization = false; 9119 isFunctionTemplateSpecialization = false; 9120 if (D.isInvalidType()) 9121 NewFD->setInvalidDecl(); 9122 9123 // Match up the template parameter lists with the scope specifier, then 9124 // determine whether we have a template or a template specialization. 9125 bool Invalid = false; 9126 TemplateParameterList *TemplateParams = 9127 MatchTemplateParametersToScopeSpecifier( 9128 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9129 D.getCXXScopeSpec(), 9130 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9131 ? D.getName().TemplateId 9132 : nullptr, 9133 TemplateParamLists, isFriend, isMemberSpecialization, 9134 Invalid); 9135 if (TemplateParams) { 9136 // Check that we can declare a template here. 9137 if (CheckTemplateDeclScope(S, TemplateParams)) 9138 NewFD->setInvalidDecl(); 9139 9140 if (TemplateParams->size() > 0) { 9141 // This is a function template 9142 9143 // A destructor cannot be a template. 9144 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9145 Diag(NewFD->getLocation(), diag::err_destructor_template); 9146 NewFD->setInvalidDecl(); 9147 } 9148 9149 // If we're adding a template to a dependent context, we may need to 9150 // rebuilding some of the types used within the template parameter list, 9151 // now that we know what the current instantiation is. 9152 if (DC->isDependentContext()) { 9153 ContextRAII SavedContext(*this, DC); 9154 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9155 Invalid = true; 9156 } 9157 9158 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9159 NewFD->getLocation(), 9160 Name, TemplateParams, 9161 NewFD); 9162 FunctionTemplate->setLexicalDeclContext(CurContext); 9163 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9164 9165 // For source fidelity, store the other template param lists. 9166 if (TemplateParamLists.size() > 1) { 9167 NewFD->setTemplateParameterListsInfo(Context, 9168 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9169 .drop_back(1)); 9170 } 9171 } else { 9172 // This is a function template specialization. 9173 isFunctionTemplateSpecialization = true; 9174 // For source fidelity, store all the template param lists. 9175 if (TemplateParamLists.size() > 0) 9176 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9177 9178 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9179 if (isFriend) { 9180 // We want to remove the "template<>", found here. 9181 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9182 9183 // If we remove the template<> and the name is not a 9184 // template-id, we're actually silently creating a problem: 9185 // the friend declaration will refer to an untemplated decl, 9186 // and clearly the user wants a template specialization. So 9187 // we need to insert '<>' after the name. 9188 SourceLocation InsertLoc; 9189 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9190 InsertLoc = D.getName().getSourceRange().getEnd(); 9191 InsertLoc = getLocForEndOfToken(InsertLoc); 9192 } 9193 9194 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9195 << Name << RemoveRange 9196 << FixItHint::CreateRemoval(RemoveRange) 9197 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9198 } 9199 } 9200 } else { 9201 // Check that we can declare a template here. 9202 if (!TemplateParamLists.empty() && isMemberSpecialization && 9203 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9204 NewFD->setInvalidDecl(); 9205 9206 // All template param lists were matched against the scope specifier: 9207 // this is NOT (an explicit specialization of) a template. 9208 if (TemplateParamLists.size() > 0) 9209 // For source fidelity, store all the template param lists. 9210 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9211 } 9212 9213 if (Invalid) { 9214 NewFD->setInvalidDecl(); 9215 if (FunctionTemplate) 9216 FunctionTemplate->setInvalidDecl(); 9217 } 9218 9219 // C++ [dcl.fct.spec]p5: 9220 // The virtual specifier shall only be used in declarations of 9221 // nonstatic class member functions that appear within a 9222 // member-specification of a class declaration; see 10.3. 9223 // 9224 if (isVirtual && !NewFD->isInvalidDecl()) { 9225 if (!isVirtualOkay) { 9226 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9227 diag::err_virtual_non_function); 9228 } else if (!CurContext->isRecord()) { 9229 // 'virtual' was specified outside of the class. 9230 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9231 diag::err_virtual_out_of_class) 9232 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9233 } else if (NewFD->getDescribedFunctionTemplate()) { 9234 // C++ [temp.mem]p3: 9235 // A member function template shall not be virtual. 9236 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9237 diag::err_virtual_member_function_template) 9238 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9239 } else { 9240 // Okay: Add virtual to the method. 9241 NewFD->setVirtualAsWritten(true); 9242 } 9243 9244 if (getLangOpts().CPlusPlus14 && 9245 NewFD->getReturnType()->isUndeducedType()) 9246 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9247 } 9248 9249 if (getLangOpts().CPlusPlus14 && 9250 (NewFD->isDependentContext() || 9251 (isFriend && CurContext->isDependentContext())) && 9252 NewFD->getReturnType()->isUndeducedType()) { 9253 // If the function template is referenced directly (for instance, as a 9254 // member of the current instantiation), pretend it has a dependent type. 9255 // This is not really justified by the standard, but is the only sane 9256 // thing to do. 9257 // FIXME: For a friend function, we have not marked the function as being 9258 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9259 const FunctionProtoType *FPT = 9260 NewFD->getType()->castAs<FunctionProtoType>(); 9261 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9262 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9263 FPT->getExtProtoInfo())); 9264 } 9265 9266 // C++ [dcl.fct.spec]p3: 9267 // The inline specifier shall not appear on a block scope function 9268 // declaration. 9269 if (isInline && !NewFD->isInvalidDecl()) { 9270 if (CurContext->isFunctionOrMethod()) { 9271 // 'inline' is not allowed on block scope function declaration. 9272 Diag(D.getDeclSpec().getInlineSpecLoc(), 9273 diag::err_inline_declaration_block_scope) << Name 9274 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9275 } 9276 } 9277 9278 // C++ [dcl.fct.spec]p6: 9279 // The explicit specifier shall be used only in the declaration of a 9280 // constructor or conversion function within its class definition; 9281 // see 12.3.1 and 12.3.2. 9282 if (hasExplicit && !NewFD->isInvalidDecl() && 9283 !isa<CXXDeductionGuideDecl>(NewFD)) { 9284 if (!CurContext->isRecord()) { 9285 // 'explicit' was specified outside of the class. 9286 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9287 diag::err_explicit_out_of_class) 9288 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9289 } else if (!isa<CXXConstructorDecl>(NewFD) && 9290 !isa<CXXConversionDecl>(NewFD)) { 9291 // 'explicit' was specified on a function that wasn't a constructor 9292 // or conversion function. 9293 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9294 diag::err_explicit_non_ctor_or_conv_function) 9295 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9296 } 9297 } 9298 9299 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9300 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9301 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9302 // are implicitly inline. 9303 NewFD->setImplicitlyInline(); 9304 9305 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9306 // be either constructors or to return a literal type. Therefore, 9307 // destructors cannot be declared constexpr. 9308 if (isa<CXXDestructorDecl>(NewFD) && 9309 (!getLangOpts().CPlusPlus20 || 9310 ConstexprKind == ConstexprSpecKind::Consteval)) { 9311 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9312 << static_cast<int>(ConstexprKind); 9313 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9314 ? ConstexprSpecKind::Unspecified 9315 : ConstexprSpecKind::Constexpr); 9316 } 9317 // C++20 [dcl.constexpr]p2: An allocation function, or a 9318 // deallocation function shall not be declared with the consteval 9319 // specifier. 9320 if (ConstexprKind == ConstexprSpecKind::Consteval && 9321 (NewFD->getOverloadedOperator() == OO_New || 9322 NewFD->getOverloadedOperator() == OO_Array_New || 9323 NewFD->getOverloadedOperator() == OO_Delete || 9324 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9325 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9326 diag::err_invalid_consteval_decl_kind) 9327 << NewFD; 9328 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9329 } 9330 } 9331 9332 // If __module_private__ was specified, mark the function accordingly. 9333 if (D.getDeclSpec().isModulePrivateSpecified()) { 9334 if (isFunctionTemplateSpecialization) { 9335 SourceLocation ModulePrivateLoc 9336 = D.getDeclSpec().getModulePrivateSpecLoc(); 9337 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9338 << 0 9339 << FixItHint::CreateRemoval(ModulePrivateLoc); 9340 } else { 9341 NewFD->setModulePrivate(); 9342 if (FunctionTemplate) 9343 FunctionTemplate->setModulePrivate(); 9344 } 9345 } 9346 9347 if (isFriend) { 9348 if (FunctionTemplate) { 9349 FunctionTemplate->setObjectOfFriendDecl(); 9350 FunctionTemplate->setAccess(AS_public); 9351 } 9352 NewFD->setObjectOfFriendDecl(); 9353 NewFD->setAccess(AS_public); 9354 } 9355 9356 // If a function is defined as defaulted or deleted, mark it as such now. 9357 // We'll do the relevant checks on defaulted / deleted functions later. 9358 switch (D.getFunctionDefinitionKind()) { 9359 case FunctionDefinitionKind::Declaration: 9360 case FunctionDefinitionKind::Definition: 9361 break; 9362 9363 case FunctionDefinitionKind::Defaulted: 9364 NewFD->setDefaulted(); 9365 break; 9366 9367 case FunctionDefinitionKind::Deleted: 9368 NewFD->setDeletedAsWritten(); 9369 break; 9370 } 9371 9372 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9373 D.isFunctionDefinition()) { 9374 // C++ [class.mfct]p2: 9375 // A member function may be defined (8.4) in its class definition, in 9376 // which case it is an inline member function (7.1.2) 9377 NewFD->setImplicitlyInline(); 9378 } 9379 9380 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9381 !CurContext->isRecord()) { 9382 // C++ [class.static]p1: 9383 // A data or function member of a class may be declared static 9384 // in a class definition, in which case it is a static member of 9385 // the class. 9386 9387 // Complain about the 'static' specifier if it's on an out-of-line 9388 // member function definition. 9389 9390 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9391 // member function template declaration and class member template 9392 // declaration (MSVC versions before 2015), warn about this. 9393 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9394 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9395 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9396 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9397 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9398 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9399 } 9400 9401 // C++11 [except.spec]p15: 9402 // A deallocation function with no exception-specification is treated 9403 // as if it were specified with noexcept(true). 9404 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9405 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9406 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9407 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9408 NewFD->setType(Context.getFunctionType( 9409 FPT->getReturnType(), FPT->getParamTypes(), 9410 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9411 } 9412 9413 // Filter out previous declarations that don't match the scope. 9414 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9415 D.getCXXScopeSpec().isNotEmpty() || 9416 isMemberSpecialization || 9417 isFunctionTemplateSpecialization); 9418 9419 // Handle GNU asm-label extension (encoded as an attribute). 9420 if (Expr *E = (Expr*) D.getAsmLabel()) { 9421 // The parser guarantees this is a string. 9422 StringLiteral *SE = cast<StringLiteral>(E); 9423 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9424 /*IsLiteralLabel=*/true, 9425 SE->getStrTokenLoc(0))); 9426 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9427 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9428 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9429 if (I != ExtnameUndeclaredIdentifiers.end()) { 9430 if (isDeclExternC(NewFD)) { 9431 NewFD->addAttr(I->second); 9432 ExtnameUndeclaredIdentifiers.erase(I); 9433 } else 9434 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9435 << /*Variable*/0 << NewFD; 9436 } 9437 } 9438 9439 // Copy the parameter declarations from the declarator D to the function 9440 // declaration NewFD, if they are available. First scavenge them into Params. 9441 SmallVector<ParmVarDecl*, 16> Params; 9442 unsigned FTIIdx; 9443 if (D.isFunctionDeclarator(FTIIdx)) { 9444 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9445 9446 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9447 // function that takes no arguments, not a function that takes a 9448 // single void argument. 9449 // We let through "const void" here because Sema::GetTypeForDeclarator 9450 // already checks for that case. 9451 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9452 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9453 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9454 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9455 Param->setDeclContext(NewFD); 9456 Params.push_back(Param); 9457 9458 if (Param->isInvalidDecl()) 9459 NewFD->setInvalidDecl(); 9460 } 9461 } 9462 9463 if (!getLangOpts().CPlusPlus) { 9464 // In C, find all the tag declarations from the prototype and move them 9465 // into the function DeclContext. Remove them from the surrounding tag 9466 // injection context of the function, which is typically but not always 9467 // the TU. 9468 DeclContext *PrototypeTagContext = 9469 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9470 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9471 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9472 9473 // We don't want to reparent enumerators. Look at their parent enum 9474 // instead. 9475 if (!TD) { 9476 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9477 TD = cast<EnumDecl>(ECD->getDeclContext()); 9478 } 9479 if (!TD) 9480 continue; 9481 DeclContext *TagDC = TD->getLexicalDeclContext(); 9482 if (!TagDC->containsDecl(TD)) 9483 continue; 9484 TagDC->removeDecl(TD); 9485 TD->setDeclContext(NewFD); 9486 NewFD->addDecl(TD); 9487 9488 // Preserve the lexical DeclContext if it is not the surrounding tag 9489 // injection context of the FD. In this example, the semantic context of 9490 // E will be f and the lexical context will be S, while both the 9491 // semantic and lexical contexts of S will be f: 9492 // void f(struct S { enum E { a } f; } s); 9493 if (TagDC != PrototypeTagContext) 9494 TD->setLexicalDeclContext(TagDC); 9495 } 9496 } 9497 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9498 // When we're declaring a function with a typedef, typeof, etc as in the 9499 // following example, we'll need to synthesize (unnamed) 9500 // parameters for use in the declaration. 9501 // 9502 // @code 9503 // typedef void fn(int); 9504 // fn f; 9505 // @endcode 9506 9507 // Synthesize a parameter for each argument type. 9508 for (const auto &AI : FT->param_types()) { 9509 ParmVarDecl *Param = 9510 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9511 Param->setScopeInfo(0, Params.size()); 9512 Params.push_back(Param); 9513 } 9514 } else { 9515 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9516 "Should not need args for typedef of non-prototype fn"); 9517 } 9518 9519 // Finally, we know we have the right number of parameters, install them. 9520 NewFD->setParams(Params); 9521 9522 if (D.getDeclSpec().isNoreturnSpecified()) 9523 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9524 D.getDeclSpec().getNoreturnSpecLoc(), 9525 AttributeCommonInfo::AS_Keyword)); 9526 9527 // Functions returning a variably modified type violate C99 6.7.5.2p2 9528 // because all functions have linkage. 9529 if (!NewFD->isInvalidDecl() && 9530 NewFD->getReturnType()->isVariablyModifiedType()) { 9531 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9532 NewFD->setInvalidDecl(); 9533 } 9534 9535 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9536 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9537 !NewFD->hasAttr<SectionAttr>()) 9538 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9539 Context, PragmaClangTextSection.SectionName, 9540 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9541 9542 // Apply an implicit SectionAttr if #pragma code_seg is active. 9543 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9544 !NewFD->hasAttr<SectionAttr>()) { 9545 NewFD->addAttr(SectionAttr::CreateImplicit( 9546 Context, CodeSegStack.CurrentValue->getString(), 9547 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9548 SectionAttr::Declspec_allocate)); 9549 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9550 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9551 ASTContext::PSF_Read, 9552 NewFD)) 9553 NewFD->dropAttr<SectionAttr>(); 9554 } 9555 9556 // Apply an implicit CodeSegAttr from class declspec or 9557 // apply an implicit SectionAttr from #pragma code_seg if active. 9558 if (!NewFD->hasAttr<CodeSegAttr>()) { 9559 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9560 D.isFunctionDefinition())) { 9561 NewFD->addAttr(SAttr); 9562 } 9563 } 9564 9565 // Handle attributes. 9566 ProcessDeclAttributes(S, NewFD, D); 9567 9568 if (getLangOpts().OpenCL) { 9569 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9570 // type declaration will generate a compilation error. 9571 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9572 if (AddressSpace != LangAS::Default) { 9573 Diag(NewFD->getLocation(), 9574 diag::err_opencl_return_value_with_address_space); 9575 NewFD->setInvalidDecl(); 9576 } 9577 } 9578 9579 if (!getLangOpts().CPlusPlus) { 9580 // Perform semantic checking on the function declaration. 9581 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9582 CheckMain(NewFD, D.getDeclSpec()); 9583 9584 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9585 CheckMSVCRTEntryPoint(NewFD); 9586 9587 if (!NewFD->isInvalidDecl()) 9588 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9589 isMemberSpecialization)); 9590 else if (!Previous.empty()) 9591 // Recover gracefully from an invalid redeclaration. 9592 D.setRedeclaration(true); 9593 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9594 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9595 "previous declaration set still overloaded"); 9596 9597 // Diagnose no-prototype function declarations with calling conventions that 9598 // don't support variadic calls. Only do this in C and do it after merging 9599 // possibly prototyped redeclarations. 9600 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9601 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9602 CallingConv CC = FT->getExtInfo().getCC(); 9603 if (!supportsVariadicCall(CC)) { 9604 // Windows system headers sometimes accidentally use stdcall without 9605 // (void) parameters, so we relax this to a warning. 9606 int DiagID = 9607 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9608 Diag(NewFD->getLocation(), DiagID) 9609 << FunctionType::getNameForCallConv(CC); 9610 } 9611 } 9612 9613 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9614 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9615 checkNonTrivialCUnion(NewFD->getReturnType(), 9616 NewFD->getReturnTypeSourceRange().getBegin(), 9617 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9618 } else { 9619 // C++11 [replacement.functions]p3: 9620 // The program's definitions shall not be specified as inline. 9621 // 9622 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9623 // 9624 // Suppress the diagnostic if the function is __attribute__((used)), since 9625 // that forces an external definition to be emitted. 9626 if (D.getDeclSpec().isInlineSpecified() && 9627 NewFD->isReplaceableGlobalAllocationFunction() && 9628 !NewFD->hasAttr<UsedAttr>()) 9629 Diag(D.getDeclSpec().getInlineSpecLoc(), 9630 diag::ext_operator_new_delete_declared_inline) 9631 << NewFD->getDeclName(); 9632 9633 // If the declarator is a template-id, translate the parser's template 9634 // argument list into our AST format. 9635 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9636 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9637 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9638 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9639 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9640 TemplateId->NumArgs); 9641 translateTemplateArguments(TemplateArgsPtr, 9642 TemplateArgs); 9643 9644 HasExplicitTemplateArgs = true; 9645 9646 if (NewFD->isInvalidDecl()) { 9647 HasExplicitTemplateArgs = false; 9648 } else if (FunctionTemplate) { 9649 // Function template with explicit template arguments. 9650 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9651 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9652 9653 HasExplicitTemplateArgs = false; 9654 } else { 9655 assert((isFunctionTemplateSpecialization || 9656 D.getDeclSpec().isFriendSpecified()) && 9657 "should have a 'template<>' for this decl"); 9658 // "friend void foo<>(int);" is an implicit specialization decl. 9659 isFunctionTemplateSpecialization = true; 9660 } 9661 } else if (isFriend && isFunctionTemplateSpecialization) { 9662 // This combination is only possible in a recovery case; the user 9663 // wrote something like: 9664 // template <> friend void foo(int); 9665 // which we're recovering from as if the user had written: 9666 // friend void foo<>(int); 9667 // Go ahead and fake up a template id. 9668 HasExplicitTemplateArgs = true; 9669 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9670 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9671 } 9672 9673 // We do not add HD attributes to specializations here because 9674 // they may have different constexpr-ness compared to their 9675 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9676 // may end up with different effective targets. Instead, a 9677 // specialization inherits its target attributes from its template 9678 // in the CheckFunctionTemplateSpecialization() call below. 9679 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9680 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9681 9682 // If it's a friend (and only if it's a friend), it's possible 9683 // that either the specialized function type or the specialized 9684 // template is dependent, and therefore matching will fail. In 9685 // this case, don't check the specialization yet. 9686 if (isFunctionTemplateSpecialization && isFriend && 9687 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9688 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9689 TemplateArgs.arguments()))) { 9690 assert(HasExplicitTemplateArgs && 9691 "friend function specialization without template args"); 9692 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9693 Previous)) 9694 NewFD->setInvalidDecl(); 9695 } else if (isFunctionTemplateSpecialization) { 9696 if (CurContext->isDependentContext() && CurContext->isRecord() 9697 && !isFriend) { 9698 isDependentClassScopeExplicitSpecialization = true; 9699 } else if (!NewFD->isInvalidDecl() && 9700 CheckFunctionTemplateSpecialization( 9701 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9702 Previous)) 9703 NewFD->setInvalidDecl(); 9704 9705 // C++ [dcl.stc]p1: 9706 // A storage-class-specifier shall not be specified in an explicit 9707 // specialization (14.7.3) 9708 FunctionTemplateSpecializationInfo *Info = 9709 NewFD->getTemplateSpecializationInfo(); 9710 if (Info && SC != SC_None) { 9711 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9712 Diag(NewFD->getLocation(), 9713 diag::err_explicit_specialization_inconsistent_storage_class) 9714 << SC 9715 << FixItHint::CreateRemoval( 9716 D.getDeclSpec().getStorageClassSpecLoc()); 9717 9718 else 9719 Diag(NewFD->getLocation(), 9720 diag::ext_explicit_specialization_storage_class) 9721 << FixItHint::CreateRemoval( 9722 D.getDeclSpec().getStorageClassSpecLoc()); 9723 } 9724 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9725 if (CheckMemberSpecialization(NewFD, Previous)) 9726 NewFD->setInvalidDecl(); 9727 } 9728 9729 // Perform semantic checking on the function declaration. 9730 if (!isDependentClassScopeExplicitSpecialization) { 9731 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9732 CheckMain(NewFD, D.getDeclSpec()); 9733 9734 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9735 CheckMSVCRTEntryPoint(NewFD); 9736 9737 if (!NewFD->isInvalidDecl()) 9738 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9739 isMemberSpecialization)); 9740 else if (!Previous.empty()) 9741 // Recover gracefully from an invalid redeclaration. 9742 D.setRedeclaration(true); 9743 } 9744 9745 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9746 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9747 "previous declaration set still overloaded"); 9748 9749 NamedDecl *PrincipalDecl = (FunctionTemplate 9750 ? cast<NamedDecl>(FunctionTemplate) 9751 : NewFD); 9752 9753 if (isFriend && NewFD->getPreviousDecl()) { 9754 AccessSpecifier Access = AS_public; 9755 if (!NewFD->isInvalidDecl()) 9756 Access = NewFD->getPreviousDecl()->getAccess(); 9757 9758 NewFD->setAccess(Access); 9759 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9760 } 9761 9762 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9763 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9764 PrincipalDecl->setNonMemberOperator(); 9765 9766 // If we have a function template, check the template parameter 9767 // list. This will check and merge default template arguments. 9768 if (FunctionTemplate) { 9769 FunctionTemplateDecl *PrevTemplate = 9770 FunctionTemplate->getPreviousDecl(); 9771 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9772 PrevTemplate ? PrevTemplate->getTemplateParameters() 9773 : nullptr, 9774 D.getDeclSpec().isFriendSpecified() 9775 ? (D.isFunctionDefinition() 9776 ? TPC_FriendFunctionTemplateDefinition 9777 : TPC_FriendFunctionTemplate) 9778 : (D.getCXXScopeSpec().isSet() && 9779 DC && DC->isRecord() && 9780 DC->isDependentContext()) 9781 ? TPC_ClassTemplateMember 9782 : TPC_FunctionTemplate); 9783 } 9784 9785 if (NewFD->isInvalidDecl()) { 9786 // Ignore all the rest of this. 9787 } else if (!D.isRedeclaration()) { 9788 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9789 AddToScope }; 9790 // Fake up an access specifier if it's supposed to be a class member. 9791 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9792 NewFD->setAccess(AS_public); 9793 9794 // Qualified decls generally require a previous declaration. 9795 if (D.getCXXScopeSpec().isSet()) { 9796 // ...with the major exception of templated-scope or 9797 // dependent-scope friend declarations. 9798 9799 // TODO: we currently also suppress this check in dependent 9800 // contexts because (1) the parameter depth will be off when 9801 // matching friend templates and (2) we might actually be 9802 // selecting a friend based on a dependent factor. But there 9803 // are situations where these conditions don't apply and we 9804 // can actually do this check immediately. 9805 // 9806 // Unless the scope is dependent, it's always an error if qualified 9807 // redeclaration lookup found nothing at all. Diagnose that now; 9808 // nothing will diagnose that error later. 9809 if (isFriend && 9810 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9811 (!Previous.empty() && CurContext->isDependentContext()))) { 9812 // ignore these 9813 } else if (NewFD->isCPUDispatchMultiVersion() || 9814 NewFD->isCPUSpecificMultiVersion()) { 9815 // ignore this, we allow the redeclaration behavior here to create new 9816 // versions of the function. 9817 } else { 9818 // The user tried to provide an out-of-line definition for a 9819 // function that is a member of a class or namespace, but there 9820 // was no such member function declared (C++ [class.mfct]p2, 9821 // C++ [namespace.memdef]p2). For example: 9822 // 9823 // class X { 9824 // void f() const; 9825 // }; 9826 // 9827 // void X::f() { } // ill-formed 9828 // 9829 // Complain about this problem, and attempt to suggest close 9830 // matches (e.g., those that differ only in cv-qualifiers and 9831 // whether the parameter types are references). 9832 9833 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9834 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9835 AddToScope = ExtraArgs.AddToScope; 9836 return Result; 9837 } 9838 } 9839 9840 // Unqualified local friend declarations are required to resolve 9841 // to something. 9842 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9843 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9844 *this, Previous, NewFD, ExtraArgs, true, S)) { 9845 AddToScope = ExtraArgs.AddToScope; 9846 return Result; 9847 } 9848 } 9849 } else if (!D.isFunctionDefinition() && 9850 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9851 !isFriend && !isFunctionTemplateSpecialization && 9852 !isMemberSpecialization) { 9853 // An out-of-line member function declaration must also be a 9854 // definition (C++ [class.mfct]p2). 9855 // Note that this is not the case for explicit specializations of 9856 // function templates or member functions of class templates, per 9857 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9858 // extension for compatibility with old SWIG code which likes to 9859 // generate them. 9860 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9861 << D.getCXXScopeSpec().getRange(); 9862 } 9863 } 9864 9865 // If this is the first declaration of a library builtin function, add 9866 // attributes as appropriate. 9867 if (!D.isRedeclaration() && 9868 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9869 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9870 if (unsigned BuiltinID = II->getBuiltinID()) { 9871 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9872 // Validate the type matches unless this builtin is specified as 9873 // matching regardless of its declared type. 9874 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9875 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9876 } else { 9877 ASTContext::GetBuiltinTypeError Error; 9878 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9879 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9880 9881 if (!Error && !BuiltinType.isNull() && 9882 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9883 NewFD->getType(), BuiltinType)) 9884 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9885 } 9886 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9887 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9888 // FIXME: We should consider this a builtin only in the std namespace. 9889 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9890 } 9891 } 9892 } 9893 } 9894 9895 ProcessPragmaWeak(S, NewFD); 9896 checkAttributesAfterMerging(*this, *NewFD); 9897 9898 AddKnownFunctionAttributes(NewFD); 9899 9900 if (NewFD->hasAttr<OverloadableAttr>() && 9901 !NewFD->getType()->getAs<FunctionProtoType>()) { 9902 Diag(NewFD->getLocation(), 9903 diag::err_attribute_overloadable_no_prototype) 9904 << NewFD; 9905 9906 // Turn this into a variadic function with no parameters. 9907 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9908 FunctionProtoType::ExtProtoInfo EPI( 9909 Context.getDefaultCallingConvention(true, false)); 9910 EPI.Variadic = true; 9911 EPI.ExtInfo = FT->getExtInfo(); 9912 9913 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9914 NewFD->setType(R); 9915 } 9916 9917 // If there's a #pragma GCC visibility in scope, and this isn't a class 9918 // member, set the visibility of this function. 9919 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9920 AddPushedVisibilityAttribute(NewFD); 9921 9922 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9923 // marking the function. 9924 AddCFAuditedAttribute(NewFD); 9925 9926 // If this is a function definition, check if we have to apply optnone due to 9927 // a pragma. 9928 if(D.isFunctionDefinition()) 9929 AddRangeBasedOptnone(NewFD); 9930 9931 // If this is the first declaration of an extern C variable, update 9932 // the map of such variables. 9933 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9934 isIncompleteDeclExternC(*this, NewFD)) 9935 RegisterLocallyScopedExternCDecl(NewFD, S); 9936 9937 // Set this FunctionDecl's range up to the right paren. 9938 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9939 9940 if (D.isRedeclaration() && !Previous.empty()) { 9941 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9942 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9943 isMemberSpecialization || 9944 isFunctionTemplateSpecialization, 9945 D.isFunctionDefinition()); 9946 } 9947 9948 if (getLangOpts().CUDA) { 9949 IdentifierInfo *II = NewFD->getIdentifier(); 9950 if (II && II->isStr(getCudaConfigureFuncName()) && 9951 !NewFD->isInvalidDecl() && 9952 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9953 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9954 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9955 << getCudaConfigureFuncName(); 9956 Context.setcudaConfigureCallDecl(NewFD); 9957 } 9958 9959 // Variadic functions, other than a *declaration* of printf, are not allowed 9960 // in device-side CUDA code, unless someone passed 9961 // -fcuda-allow-variadic-functions. 9962 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9963 (NewFD->hasAttr<CUDADeviceAttr>() || 9964 NewFD->hasAttr<CUDAGlobalAttr>()) && 9965 !(II && II->isStr("printf") && NewFD->isExternC() && 9966 !D.isFunctionDefinition())) { 9967 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9968 } 9969 } 9970 9971 MarkUnusedFileScopedDecl(NewFD); 9972 9973 9974 9975 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9976 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9977 if (SC == SC_Static) { 9978 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9979 D.setInvalidType(); 9980 } 9981 9982 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9983 if (!NewFD->getReturnType()->isVoidType()) { 9984 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9985 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9986 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9987 : FixItHint()); 9988 D.setInvalidType(); 9989 } 9990 9991 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9992 for (auto Param : NewFD->parameters()) 9993 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9994 9995 if (getLangOpts().OpenCLCPlusPlus) { 9996 if (DC->isRecord()) { 9997 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9998 D.setInvalidType(); 9999 } 10000 if (FunctionTemplate) { 10001 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10002 D.setInvalidType(); 10003 } 10004 } 10005 } 10006 10007 if (getLangOpts().CPlusPlus) { 10008 if (FunctionTemplate) { 10009 if (NewFD->isInvalidDecl()) 10010 FunctionTemplate->setInvalidDecl(); 10011 return FunctionTemplate; 10012 } 10013 10014 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10015 CompleteMemberSpecialization(NewFD, Previous); 10016 } 10017 10018 for (const ParmVarDecl *Param : NewFD->parameters()) { 10019 QualType PT = Param->getType(); 10020 10021 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10022 // types. 10023 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10024 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10025 QualType ElemTy = PipeTy->getElementType(); 10026 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10027 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10028 D.setInvalidType(); 10029 } 10030 } 10031 } 10032 } 10033 10034 // Here we have an function template explicit specialization at class scope. 10035 // The actual specialization will be postponed to template instatiation 10036 // time via the ClassScopeFunctionSpecializationDecl node. 10037 if (isDependentClassScopeExplicitSpecialization) { 10038 ClassScopeFunctionSpecializationDecl *NewSpec = 10039 ClassScopeFunctionSpecializationDecl::Create( 10040 Context, CurContext, NewFD->getLocation(), 10041 cast<CXXMethodDecl>(NewFD), 10042 HasExplicitTemplateArgs, TemplateArgs); 10043 CurContext->addDecl(NewSpec); 10044 AddToScope = false; 10045 } 10046 10047 // Diagnose availability attributes. Availability cannot be used on functions 10048 // that are run during load/unload. 10049 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10050 if (NewFD->hasAttr<ConstructorAttr>()) { 10051 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10052 << 1; 10053 NewFD->dropAttr<AvailabilityAttr>(); 10054 } 10055 if (NewFD->hasAttr<DestructorAttr>()) { 10056 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10057 << 2; 10058 NewFD->dropAttr<AvailabilityAttr>(); 10059 } 10060 } 10061 10062 // Diagnose no_builtin attribute on function declaration that are not a 10063 // definition. 10064 // FIXME: We should really be doing this in 10065 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10066 // the FunctionDecl and at this point of the code 10067 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10068 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10069 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10070 switch (D.getFunctionDefinitionKind()) { 10071 case FunctionDefinitionKind::Defaulted: 10072 case FunctionDefinitionKind::Deleted: 10073 Diag(NBA->getLocation(), 10074 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10075 << NBA->getSpelling(); 10076 break; 10077 case FunctionDefinitionKind::Declaration: 10078 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10079 << NBA->getSpelling(); 10080 break; 10081 case FunctionDefinitionKind::Definition: 10082 break; 10083 } 10084 10085 return NewFD; 10086 } 10087 10088 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10089 /// when __declspec(code_seg) "is applied to a class, all member functions of 10090 /// the class and nested classes -- this includes compiler-generated special 10091 /// member functions -- are put in the specified segment." 10092 /// The actual behavior is a little more complicated. The Microsoft compiler 10093 /// won't check outer classes if there is an active value from #pragma code_seg. 10094 /// The CodeSeg is always applied from the direct parent but only from outer 10095 /// classes when the #pragma code_seg stack is empty. See: 10096 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10097 /// available since MS has removed the page. 10098 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10099 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10100 if (!Method) 10101 return nullptr; 10102 const CXXRecordDecl *Parent = Method->getParent(); 10103 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10104 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10105 NewAttr->setImplicit(true); 10106 return NewAttr; 10107 } 10108 10109 // The Microsoft compiler won't check outer classes for the CodeSeg 10110 // when the #pragma code_seg stack is active. 10111 if (S.CodeSegStack.CurrentValue) 10112 return nullptr; 10113 10114 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10115 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10116 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10117 NewAttr->setImplicit(true); 10118 return NewAttr; 10119 } 10120 } 10121 return nullptr; 10122 } 10123 10124 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10125 /// containing class. Otherwise it will return implicit SectionAttr if the 10126 /// function is a definition and there is an active value on CodeSegStack 10127 /// (from the current #pragma code-seg value). 10128 /// 10129 /// \param FD Function being declared. 10130 /// \param IsDefinition Whether it is a definition or just a declarartion. 10131 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10132 /// nullptr if no attribute should be added. 10133 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10134 bool IsDefinition) { 10135 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10136 return A; 10137 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10138 CodeSegStack.CurrentValue) 10139 return SectionAttr::CreateImplicit( 10140 getASTContext(), CodeSegStack.CurrentValue->getString(), 10141 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10142 SectionAttr::Declspec_allocate); 10143 return nullptr; 10144 } 10145 10146 /// Determines if we can perform a correct type check for \p D as a 10147 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10148 /// best-effort check. 10149 /// 10150 /// \param NewD The new declaration. 10151 /// \param OldD The old declaration. 10152 /// \param NewT The portion of the type of the new declaration to check. 10153 /// \param OldT The portion of the type of the old declaration to check. 10154 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10155 QualType NewT, QualType OldT) { 10156 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10157 return true; 10158 10159 // For dependently-typed local extern declarations and friends, we can't 10160 // perform a correct type check in general until instantiation: 10161 // 10162 // int f(); 10163 // template<typename T> void g() { T f(); } 10164 // 10165 // (valid if g() is only instantiated with T = int). 10166 if (NewT->isDependentType() && 10167 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10168 return false; 10169 10170 // Similarly, if the previous declaration was a dependent local extern 10171 // declaration, we don't really know its type yet. 10172 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10173 return false; 10174 10175 return true; 10176 } 10177 10178 /// Checks if the new declaration declared in dependent context must be 10179 /// put in the same redeclaration chain as the specified declaration. 10180 /// 10181 /// \param D Declaration that is checked. 10182 /// \param PrevDecl Previous declaration found with proper lookup method for the 10183 /// same declaration name. 10184 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10185 /// belongs to. 10186 /// 10187 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10188 if (!D->getLexicalDeclContext()->isDependentContext()) 10189 return true; 10190 10191 // Don't chain dependent friend function definitions until instantiation, to 10192 // permit cases like 10193 // 10194 // void func(); 10195 // template<typename T> class C1 { friend void func() {} }; 10196 // template<typename T> class C2 { friend void func() {} }; 10197 // 10198 // ... which is valid if only one of C1 and C2 is ever instantiated. 10199 // 10200 // FIXME: This need only apply to function definitions. For now, we proxy 10201 // this by checking for a file-scope function. We do not want this to apply 10202 // to friend declarations nominating member functions, because that gets in 10203 // the way of access checks. 10204 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10205 return false; 10206 10207 auto *VD = dyn_cast<ValueDecl>(D); 10208 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10209 return !VD || !PrevVD || 10210 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10211 PrevVD->getType()); 10212 } 10213 10214 /// Check the target attribute of the function for MultiVersion 10215 /// validity. 10216 /// 10217 /// Returns true if there was an error, false otherwise. 10218 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10219 const auto *TA = FD->getAttr<TargetAttr>(); 10220 assert(TA && "MultiVersion Candidate requires a target attribute"); 10221 ParsedTargetAttr ParseInfo = TA->parse(); 10222 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10223 enum ErrType { Feature = 0, Architecture = 1 }; 10224 10225 if (!ParseInfo.Architecture.empty() && 10226 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10227 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10228 << Architecture << ParseInfo.Architecture; 10229 return true; 10230 } 10231 10232 for (const auto &Feat : ParseInfo.Features) { 10233 auto BareFeat = StringRef{Feat}.substr(1); 10234 if (Feat[0] == '-') { 10235 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10236 << Feature << ("no-" + BareFeat).str(); 10237 return true; 10238 } 10239 10240 if (!TargetInfo.validateCpuSupports(BareFeat) || 10241 !TargetInfo.isValidFeatureName(BareFeat)) { 10242 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10243 << Feature << BareFeat; 10244 return true; 10245 } 10246 } 10247 return false; 10248 } 10249 10250 // Provide a white-list of attributes that are allowed to be combined with 10251 // multiversion functions. 10252 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10253 MultiVersionKind MVType) { 10254 // Note: this list/diagnosis must match the list in 10255 // checkMultiversionAttributesAllSame. 10256 switch (Kind) { 10257 default: 10258 return false; 10259 case attr::Used: 10260 return MVType == MultiVersionKind::Target; 10261 case attr::NonNull: 10262 case attr::NoThrow: 10263 return true; 10264 } 10265 } 10266 10267 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10268 const FunctionDecl *FD, 10269 const FunctionDecl *CausedFD, 10270 MultiVersionKind MVType) { 10271 bool IsCPUSpecificCPUDispatchMVType = 10272 MVType == MultiVersionKind::CPUDispatch || 10273 MVType == MultiVersionKind::CPUSpecific; 10274 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10275 Sema &S, const Attr *A) { 10276 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10277 << IsCPUSpecificCPUDispatchMVType << A; 10278 if (CausedFD) 10279 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10280 return true; 10281 }; 10282 10283 for (const Attr *A : FD->attrs()) { 10284 switch (A->getKind()) { 10285 case attr::CPUDispatch: 10286 case attr::CPUSpecific: 10287 if (MVType != MultiVersionKind::CPUDispatch && 10288 MVType != MultiVersionKind::CPUSpecific) 10289 return Diagnose(S, A); 10290 break; 10291 case attr::Target: 10292 if (MVType != MultiVersionKind::Target) 10293 return Diagnose(S, A); 10294 break; 10295 default: 10296 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10297 return Diagnose(S, A); 10298 break; 10299 } 10300 } 10301 return false; 10302 } 10303 10304 bool Sema::areMultiversionVariantFunctionsCompatible( 10305 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10306 const PartialDiagnostic &NoProtoDiagID, 10307 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10308 const PartialDiagnosticAt &NoSupportDiagIDAt, 10309 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10310 bool ConstexprSupported, bool CLinkageMayDiffer) { 10311 enum DoesntSupport { 10312 FuncTemplates = 0, 10313 VirtFuncs = 1, 10314 DeducedReturn = 2, 10315 Constructors = 3, 10316 Destructors = 4, 10317 DeletedFuncs = 5, 10318 DefaultedFuncs = 6, 10319 ConstexprFuncs = 7, 10320 ConstevalFuncs = 8, 10321 }; 10322 enum Different { 10323 CallingConv = 0, 10324 ReturnType = 1, 10325 ConstexprSpec = 2, 10326 InlineSpec = 3, 10327 Linkage = 4, 10328 LanguageLinkage = 5, 10329 }; 10330 10331 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10332 !OldFD->getType()->getAs<FunctionProtoType>()) { 10333 Diag(OldFD->getLocation(), NoProtoDiagID); 10334 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10335 return true; 10336 } 10337 10338 if (NoProtoDiagID.getDiagID() != 0 && 10339 !NewFD->getType()->getAs<FunctionProtoType>()) 10340 return Diag(NewFD->getLocation(), NoProtoDiagID); 10341 10342 if (!TemplatesSupported && 10343 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10345 << FuncTemplates; 10346 10347 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10348 if (NewCXXFD->isVirtual()) 10349 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10350 << VirtFuncs; 10351 10352 if (isa<CXXConstructorDecl>(NewCXXFD)) 10353 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10354 << Constructors; 10355 10356 if (isa<CXXDestructorDecl>(NewCXXFD)) 10357 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10358 << Destructors; 10359 } 10360 10361 if (NewFD->isDeleted()) 10362 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10363 << DeletedFuncs; 10364 10365 if (NewFD->isDefaulted()) 10366 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10367 << DefaultedFuncs; 10368 10369 if (!ConstexprSupported && NewFD->isConstexpr()) 10370 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10371 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10372 10373 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10374 const auto *NewType = cast<FunctionType>(NewQType); 10375 QualType NewReturnType = NewType->getReturnType(); 10376 10377 if (NewReturnType->isUndeducedType()) 10378 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10379 << DeducedReturn; 10380 10381 // Ensure the return type is identical. 10382 if (OldFD) { 10383 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10384 const auto *OldType = cast<FunctionType>(OldQType); 10385 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10386 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10387 10388 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10389 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10390 10391 QualType OldReturnType = OldType->getReturnType(); 10392 10393 if (OldReturnType != NewReturnType) 10394 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10395 10396 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10397 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10398 10399 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10400 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10401 10402 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10403 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10404 10405 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10406 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10407 10408 if (CheckEquivalentExceptionSpec( 10409 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10410 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10411 return true; 10412 } 10413 return false; 10414 } 10415 10416 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10417 const FunctionDecl *NewFD, 10418 bool CausesMV, 10419 MultiVersionKind MVType) { 10420 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10421 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10422 if (OldFD) 10423 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10424 return true; 10425 } 10426 10427 bool IsCPUSpecificCPUDispatchMVType = 10428 MVType == MultiVersionKind::CPUDispatch || 10429 MVType == MultiVersionKind::CPUSpecific; 10430 10431 if (CausesMV && OldFD && 10432 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10433 return true; 10434 10435 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10436 return true; 10437 10438 // Only allow transition to MultiVersion if it hasn't been used. 10439 if (OldFD && CausesMV && OldFD->isUsed(false)) 10440 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10441 10442 return S.areMultiversionVariantFunctionsCompatible( 10443 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10444 PartialDiagnosticAt(NewFD->getLocation(), 10445 S.PDiag(diag::note_multiversioning_caused_here)), 10446 PartialDiagnosticAt(NewFD->getLocation(), 10447 S.PDiag(diag::err_multiversion_doesnt_support) 10448 << IsCPUSpecificCPUDispatchMVType), 10449 PartialDiagnosticAt(NewFD->getLocation(), 10450 S.PDiag(diag::err_multiversion_diff)), 10451 /*TemplatesSupported=*/false, 10452 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10453 /*CLinkageMayDiffer=*/false); 10454 } 10455 10456 /// Check the validity of a multiversion function declaration that is the 10457 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10458 /// 10459 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10460 /// 10461 /// Returns true if there was an error, false otherwise. 10462 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10463 MultiVersionKind MVType, 10464 const TargetAttr *TA) { 10465 assert(MVType != MultiVersionKind::None && 10466 "Function lacks multiversion attribute"); 10467 10468 // Target only causes MV if it is default, otherwise this is a normal 10469 // function. 10470 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10471 return false; 10472 10473 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10474 FD->setInvalidDecl(); 10475 return true; 10476 } 10477 10478 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10479 FD->setInvalidDecl(); 10480 return true; 10481 } 10482 10483 FD->setIsMultiVersion(); 10484 return false; 10485 } 10486 10487 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10488 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10489 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10490 return true; 10491 } 10492 10493 return false; 10494 } 10495 10496 static bool CheckTargetCausesMultiVersioning( 10497 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10498 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10499 LookupResult &Previous) { 10500 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10501 ParsedTargetAttr NewParsed = NewTA->parse(); 10502 // Sort order doesn't matter, it just needs to be consistent. 10503 llvm::sort(NewParsed.Features); 10504 10505 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10506 // to change, this is a simple redeclaration. 10507 if (!NewTA->isDefaultVersion() && 10508 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10509 return false; 10510 10511 // Otherwise, this decl causes MultiVersioning. 10512 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10513 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10514 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10515 NewFD->setInvalidDecl(); 10516 return true; 10517 } 10518 10519 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10520 MultiVersionKind::Target)) { 10521 NewFD->setInvalidDecl(); 10522 return true; 10523 } 10524 10525 if (CheckMultiVersionValue(S, NewFD)) { 10526 NewFD->setInvalidDecl(); 10527 return true; 10528 } 10529 10530 // If this is 'default', permit the forward declaration. 10531 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10532 Redeclaration = true; 10533 OldDecl = OldFD; 10534 OldFD->setIsMultiVersion(); 10535 NewFD->setIsMultiVersion(); 10536 return false; 10537 } 10538 10539 if (CheckMultiVersionValue(S, OldFD)) { 10540 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10541 NewFD->setInvalidDecl(); 10542 return true; 10543 } 10544 10545 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10546 10547 if (OldParsed == NewParsed) { 10548 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10549 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10550 NewFD->setInvalidDecl(); 10551 return true; 10552 } 10553 10554 for (const auto *FD : OldFD->redecls()) { 10555 const auto *CurTA = FD->getAttr<TargetAttr>(); 10556 // We allow forward declarations before ANY multiversioning attributes, but 10557 // nothing after the fact. 10558 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10559 (!CurTA || CurTA->isInherited())) { 10560 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10561 << 0; 10562 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10563 NewFD->setInvalidDecl(); 10564 return true; 10565 } 10566 } 10567 10568 OldFD->setIsMultiVersion(); 10569 NewFD->setIsMultiVersion(); 10570 Redeclaration = false; 10571 MergeTypeWithPrevious = false; 10572 OldDecl = nullptr; 10573 Previous.clear(); 10574 return false; 10575 } 10576 10577 /// Check the validity of a new function declaration being added to an existing 10578 /// multiversioned declaration collection. 10579 static bool CheckMultiVersionAdditionalDecl( 10580 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10581 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10582 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10583 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10584 LookupResult &Previous) { 10585 10586 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10587 // Disallow mixing of multiversioning types. 10588 if ((OldMVType == MultiVersionKind::Target && 10589 NewMVType != MultiVersionKind::Target) || 10590 (NewMVType == MultiVersionKind::Target && 10591 OldMVType != MultiVersionKind::Target)) { 10592 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10593 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10594 NewFD->setInvalidDecl(); 10595 return true; 10596 } 10597 10598 ParsedTargetAttr NewParsed; 10599 if (NewTA) { 10600 NewParsed = NewTA->parse(); 10601 llvm::sort(NewParsed.Features); 10602 } 10603 10604 bool UseMemberUsingDeclRules = 10605 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10606 10607 // Next, check ALL non-overloads to see if this is a redeclaration of a 10608 // previous member of the MultiVersion set. 10609 for (NamedDecl *ND : Previous) { 10610 FunctionDecl *CurFD = ND->getAsFunction(); 10611 if (!CurFD) 10612 continue; 10613 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10614 continue; 10615 10616 if (NewMVType == MultiVersionKind::Target) { 10617 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10618 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10619 NewFD->setIsMultiVersion(); 10620 Redeclaration = true; 10621 OldDecl = ND; 10622 return false; 10623 } 10624 10625 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10626 if (CurParsed == NewParsed) { 10627 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10628 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10629 NewFD->setInvalidDecl(); 10630 return true; 10631 } 10632 } else { 10633 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10634 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10635 // Handle CPUDispatch/CPUSpecific versions. 10636 // Only 1 CPUDispatch function is allowed, this will make it go through 10637 // the redeclaration errors. 10638 if (NewMVType == MultiVersionKind::CPUDispatch && 10639 CurFD->hasAttr<CPUDispatchAttr>()) { 10640 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10641 std::equal( 10642 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10643 NewCPUDisp->cpus_begin(), 10644 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10645 return Cur->getName() == New->getName(); 10646 })) { 10647 NewFD->setIsMultiVersion(); 10648 Redeclaration = true; 10649 OldDecl = ND; 10650 return false; 10651 } 10652 10653 // If the declarations don't match, this is an error condition. 10654 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10655 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10656 NewFD->setInvalidDecl(); 10657 return true; 10658 } 10659 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10660 10661 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10662 std::equal( 10663 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10664 NewCPUSpec->cpus_begin(), 10665 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10666 return Cur->getName() == New->getName(); 10667 })) { 10668 NewFD->setIsMultiVersion(); 10669 Redeclaration = true; 10670 OldDecl = ND; 10671 return false; 10672 } 10673 10674 // Only 1 version of CPUSpecific is allowed for each CPU. 10675 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10676 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10677 if (CurII == NewII) { 10678 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10679 << NewII; 10680 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10681 NewFD->setInvalidDecl(); 10682 return true; 10683 } 10684 } 10685 } 10686 } 10687 // If the two decls aren't the same MVType, there is no possible error 10688 // condition. 10689 } 10690 } 10691 10692 // Else, this is simply a non-redecl case. Checking the 'value' is only 10693 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10694 // handled in the attribute adding step. 10695 if (NewMVType == MultiVersionKind::Target && 10696 CheckMultiVersionValue(S, NewFD)) { 10697 NewFD->setInvalidDecl(); 10698 return true; 10699 } 10700 10701 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10702 !OldFD->isMultiVersion(), NewMVType)) { 10703 NewFD->setInvalidDecl(); 10704 return true; 10705 } 10706 10707 // Permit forward declarations in the case where these two are compatible. 10708 if (!OldFD->isMultiVersion()) { 10709 OldFD->setIsMultiVersion(); 10710 NewFD->setIsMultiVersion(); 10711 Redeclaration = true; 10712 OldDecl = OldFD; 10713 return false; 10714 } 10715 10716 NewFD->setIsMultiVersion(); 10717 Redeclaration = false; 10718 MergeTypeWithPrevious = false; 10719 OldDecl = nullptr; 10720 Previous.clear(); 10721 return false; 10722 } 10723 10724 10725 /// Check the validity of a mulitversion function declaration. 10726 /// Also sets the multiversion'ness' of the function itself. 10727 /// 10728 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10729 /// 10730 /// Returns true if there was an error, false otherwise. 10731 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10732 bool &Redeclaration, NamedDecl *&OldDecl, 10733 bool &MergeTypeWithPrevious, 10734 LookupResult &Previous) { 10735 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10736 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10737 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10738 10739 // Mixing Multiversioning types is prohibited. 10740 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10741 (NewCPUDisp && NewCPUSpec)) { 10742 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10743 NewFD->setInvalidDecl(); 10744 return true; 10745 } 10746 10747 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10748 10749 // Main isn't allowed to become a multiversion function, however it IS 10750 // permitted to have 'main' be marked with the 'target' optimization hint. 10751 if (NewFD->isMain()) { 10752 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10753 MVType == MultiVersionKind::CPUDispatch || 10754 MVType == MultiVersionKind::CPUSpecific) { 10755 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10756 NewFD->setInvalidDecl(); 10757 return true; 10758 } 10759 return false; 10760 } 10761 10762 if (!OldDecl || !OldDecl->getAsFunction() || 10763 OldDecl->getDeclContext()->getRedeclContext() != 10764 NewFD->getDeclContext()->getRedeclContext()) { 10765 // If there's no previous declaration, AND this isn't attempting to cause 10766 // multiversioning, this isn't an error condition. 10767 if (MVType == MultiVersionKind::None) 10768 return false; 10769 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10770 } 10771 10772 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10773 10774 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10775 return false; 10776 10777 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10778 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10779 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10780 NewFD->setInvalidDecl(); 10781 return true; 10782 } 10783 10784 // Handle the target potentially causes multiversioning case. 10785 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10786 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10787 Redeclaration, OldDecl, 10788 MergeTypeWithPrevious, Previous); 10789 10790 // At this point, we have a multiversion function decl (in OldFD) AND an 10791 // appropriate attribute in the current function decl. Resolve that these are 10792 // still compatible with previous declarations. 10793 return CheckMultiVersionAdditionalDecl( 10794 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10795 OldDecl, MergeTypeWithPrevious, Previous); 10796 } 10797 10798 /// Perform semantic checking of a new function declaration. 10799 /// 10800 /// Performs semantic analysis of the new function declaration 10801 /// NewFD. This routine performs all semantic checking that does not 10802 /// require the actual declarator involved in the declaration, and is 10803 /// used both for the declaration of functions as they are parsed 10804 /// (called via ActOnDeclarator) and for the declaration of functions 10805 /// that have been instantiated via C++ template instantiation (called 10806 /// via InstantiateDecl). 10807 /// 10808 /// \param IsMemberSpecialization whether this new function declaration is 10809 /// a member specialization (that replaces any definition provided by the 10810 /// previous declaration). 10811 /// 10812 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10813 /// 10814 /// \returns true if the function declaration is a redeclaration. 10815 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10816 LookupResult &Previous, 10817 bool IsMemberSpecialization) { 10818 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10819 "Variably modified return types are not handled here"); 10820 10821 // Determine whether the type of this function should be merged with 10822 // a previous visible declaration. This never happens for functions in C++, 10823 // and always happens in C if the previous declaration was visible. 10824 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10825 !Previous.isShadowed(); 10826 10827 bool Redeclaration = false; 10828 NamedDecl *OldDecl = nullptr; 10829 bool MayNeedOverloadableChecks = false; 10830 10831 // Merge or overload the declaration with an existing declaration of 10832 // the same name, if appropriate. 10833 if (!Previous.empty()) { 10834 // Determine whether NewFD is an overload of PrevDecl or 10835 // a declaration that requires merging. If it's an overload, 10836 // there's no more work to do here; we'll just add the new 10837 // function to the scope. 10838 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10839 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10840 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10841 Redeclaration = true; 10842 OldDecl = Candidate; 10843 } 10844 } else { 10845 MayNeedOverloadableChecks = true; 10846 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10847 /*NewIsUsingDecl*/ false)) { 10848 case Ovl_Match: 10849 Redeclaration = true; 10850 break; 10851 10852 case Ovl_NonFunction: 10853 Redeclaration = true; 10854 break; 10855 10856 case Ovl_Overload: 10857 Redeclaration = false; 10858 break; 10859 } 10860 } 10861 } 10862 10863 // Check for a previous extern "C" declaration with this name. 10864 if (!Redeclaration && 10865 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10866 if (!Previous.empty()) { 10867 // This is an extern "C" declaration with the same name as a previous 10868 // declaration, and thus redeclares that entity... 10869 Redeclaration = true; 10870 OldDecl = Previous.getFoundDecl(); 10871 MergeTypeWithPrevious = false; 10872 10873 // ... except in the presence of __attribute__((overloadable)). 10874 if (OldDecl->hasAttr<OverloadableAttr>() || 10875 NewFD->hasAttr<OverloadableAttr>()) { 10876 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10877 MayNeedOverloadableChecks = true; 10878 Redeclaration = false; 10879 OldDecl = nullptr; 10880 } 10881 } 10882 } 10883 } 10884 10885 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10886 MergeTypeWithPrevious, Previous)) 10887 return Redeclaration; 10888 10889 // PPC MMA non-pointer types are not allowed as function return types. 10890 if (Context.getTargetInfo().getTriple().isPPC64() && 10891 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10892 NewFD->setInvalidDecl(); 10893 } 10894 10895 // C++11 [dcl.constexpr]p8: 10896 // A constexpr specifier for a non-static member function that is not 10897 // a constructor declares that member function to be const. 10898 // 10899 // This needs to be delayed until we know whether this is an out-of-line 10900 // definition of a static member function. 10901 // 10902 // This rule is not present in C++1y, so we produce a backwards 10903 // compatibility warning whenever it happens in C++11. 10904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10905 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10906 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10907 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10908 CXXMethodDecl *OldMD = nullptr; 10909 if (OldDecl) 10910 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10911 if (!OldMD || !OldMD->isStatic()) { 10912 const FunctionProtoType *FPT = 10913 MD->getType()->castAs<FunctionProtoType>(); 10914 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10915 EPI.TypeQuals.addConst(); 10916 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10917 FPT->getParamTypes(), EPI)); 10918 10919 // Warn that we did this, if we're not performing template instantiation. 10920 // In that case, we'll have warned already when the template was defined. 10921 if (!inTemplateInstantiation()) { 10922 SourceLocation AddConstLoc; 10923 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10924 .IgnoreParens().getAs<FunctionTypeLoc>()) 10925 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10926 10927 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10928 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10929 } 10930 } 10931 } 10932 10933 if (Redeclaration) { 10934 // NewFD and OldDecl represent declarations that need to be 10935 // merged. 10936 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10937 NewFD->setInvalidDecl(); 10938 return Redeclaration; 10939 } 10940 10941 Previous.clear(); 10942 Previous.addDecl(OldDecl); 10943 10944 if (FunctionTemplateDecl *OldTemplateDecl = 10945 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10946 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10947 FunctionTemplateDecl *NewTemplateDecl 10948 = NewFD->getDescribedFunctionTemplate(); 10949 assert(NewTemplateDecl && "Template/non-template mismatch"); 10950 10951 // The call to MergeFunctionDecl above may have created some state in 10952 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10953 // can add it as a redeclaration. 10954 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10955 10956 NewFD->setPreviousDeclaration(OldFD); 10957 if (NewFD->isCXXClassMember()) { 10958 NewFD->setAccess(OldTemplateDecl->getAccess()); 10959 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10960 } 10961 10962 // If this is an explicit specialization of a member that is a function 10963 // template, mark it as a member specialization. 10964 if (IsMemberSpecialization && 10965 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10966 NewTemplateDecl->setMemberSpecialization(); 10967 assert(OldTemplateDecl->isMemberSpecialization()); 10968 // Explicit specializations of a member template do not inherit deleted 10969 // status from the parent member template that they are specializing. 10970 if (OldFD->isDeleted()) { 10971 // FIXME: This assert will not hold in the presence of modules. 10972 assert(OldFD->getCanonicalDecl() == OldFD); 10973 // FIXME: We need an update record for this AST mutation. 10974 OldFD->setDeletedAsWritten(false); 10975 } 10976 } 10977 10978 } else { 10979 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10980 auto *OldFD = cast<FunctionDecl>(OldDecl); 10981 // This needs to happen first so that 'inline' propagates. 10982 NewFD->setPreviousDeclaration(OldFD); 10983 if (NewFD->isCXXClassMember()) 10984 NewFD->setAccess(OldFD->getAccess()); 10985 } 10986 } 10987 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10988 !NewFD->getAttr<OverloadableAttr>()) { 10989 assert((Previous.empty() || 10990 llvm::any_of(Previous, 10991 [](const NamedDecl *ND) { 10992 return ND->hasAttr<OverloadableAttr>(); 10993 })) && 10994 "Non-redecls shouldn't happen without overloadable present"); 10995 10996 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10997 const auto *FD = dyn_cast<FunctionDecl>(ND); 10998 return FD && !FD->hasAttr<OverloadableAttr>(); 10999 }); 11000 11001 if (OtherUnmarkedIter != Previous.end()) { 11002 Diag(NewFD->getLocation(), 11003 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11004 Diag((*OtherUnmarkedIter)->getLocation(), 11005 diag::note_attribute_overloadable_prev_overload) 11006 << false; 11007 11008 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11009 } 11010 } 11011 11012 if (LangOpts.OpenMP) 11013 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11014 11015 // Semantic checking for this function declaration (in isolation). 11016 11017 if (getLangOpts().CPlusPlus) { 11018 // C++-specific checks. 11019 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11020 CheckConstructor(Constructor); 11021 } else if (CXXDestructorDecl *Destructor = 11022 dyn_cast<CXXDestructorDecl>(NewFD)) { 11023 CXXRecordDecl *Record = Destructor->getParent(); 11024 QualType ClassType = Context.getTypeDeclType(Record); 11025 11026 // FIXME: Shouldn't we be able to perform this check even when the class 11027 // type is dependent? Both gcc and edg can handle that. 11028 if (!ClassType->isDependentType()) { 11029 DeclarationName Name 11030 = Context.DeclarationNames.getCXXDestructorName( 11031 Context.getCanonicalType(ClassType)); 11032 if (NewFD->getDeclName() != Name) { 11033 Diag(NewFD->getLocation(), diag::err_destructor_name); 11034 NewFD->setInvalidDecl(); 11035 return Redeclaration; 11036 } 11037 } 11038 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11039 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11040 CheckDeductionGuideTemplate(TD); 11041 11042 // A deduction guide is not on the list of entities that can be 11043 // explicitly specialized. 11044 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11045 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11046 << /*explicit specialization*/ 1; 11047 } 11048 11049 // Find any virtual functions that this function overrides. 11050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11051 if (!Method->isFunctionTemplateSpecialization() && 11052 !Method->getDescribedFunctionTemplate() && 11053 Method->isCanonicalDecl()) { 11054 AddOverriddenMethods(Method->getParent(), Method); 11055 } 11056 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11057 // C++2a [class.virtual]p6 11058 // A virtual method shall not have a requires-clause. 11059 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11060 diag::err_constrained_virtual_method); 11061 11062 if (Method->isStatic()) 11063 checkThisInStaticMemberFunctionType(Method); 11064 } 11065 11066 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11067 ActOnConversionDeclarator(Conversion); 11068 11069 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11070 if (NewFD->isOverloadedOperator() && 11071 CheckOverloadedOperatorDeclaration(NewFD)) { 11072 NewFD->setInvalidDecl(); 11073 return Redeclaration; 11074 } 11075 11076 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11077 if (NewFD->getLiteralIdentifier() && 11078 CheckLiteralOperatorDeclaration(NewFD)) { 11079 NewFD->setInvalidDecl(); 11080 return Redeclaration; 11081 } 11082 11083 // In C++, check default arguments now that we have merged decls. Unless 11084 // the lexical context is the class, because in this case this is done 11085 // during delayed parsing anyway. 11086 if (!CurContext->isRecord()) 11087 CheckCXXDefaultArguments(NewFD); 11088 11089 // If this function is declared as being extern "C", then check to see if 11090 // the function returns a UDT (class, struct, or union type) that is not C 11091 // compatible, and if it does, warn the user. 11092 // But, issue any diagnostic on the first declaration only. 11093 if (Previous.empty() && NewFD->isExternC()) { 11094 QualType R = NewFD->getReturnType(); 11095 if (R->isIncompleteType() && !R->isVoidType()) 11096 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11097 << NewFD << R; 11098 else if (!R.isPODType(Context) && !R->isVoidType() && 11099 !R->isObjCObjectPointerType()) 11100 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11101 } 11102 11103 // C++1z [dcl.fct]p6: 11104 // [...] whether the function has a non-throwing exception-specification 11105 // [is] part of the function type 11106 // 11107 // This results in an ABI break between C++14 and C++17 for functions whose 11108 // declared type includes an exception-specification in a parameter or 11109 // return type. (Exception specifications on the function itself are OK in 11110 // most cases, and exception specifications are not permitted in most other 11111 // contexts where they could make it into a mangling.) 11112 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11113 auto HasNoexcept = [&](QualType T) -> bool { 11114 // Strip off declarator chunks that could be between us and a function 11115 // type. We don't need to look far, exception specifications are very 11116 // restricted prior to C++17. 11117 if (auto *RT = T->getAs<ReferenceType>()) 11118 T = RT->getPointeeType(); 11119 else if (T->isAnyPointerType()) 11120 T = T->getPointeeType(); 11121 else if (auto *MPT = T->getAs<MemberPointerType>()) 11122 T = MPT->getPointeeType(); 11123 if (auto *FPT = T->getAs<FunctionProtoType>()) 11124 if (FPT->isNothrow()) 11125 return true; 11126 return false; 11127 }; 11128 11129 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11130 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11131 for (QualType T : FPT->param_types()) 11132 AnyNoexcept |= HasNoexcept(T); 11133 if (AnyNoexcept) 11134 Diag(NewFD->getLocation(), 11135 diag::warn_cxx17_compat_exception_spec_in_signature) 11136 << NewFD; 11137 } 11138 11139 if (!Redeclaration && LangOpts.CUDA) 11140 checkCUDATargetOverload(NewFD, Previous); 11141 } 11142 return Redeclaration; 11143 } 11144 11145 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11146 // C++11 [basic.start.main]p3: 11147 // A program that [...] declares main to be inline, static or 11148 // constexpr is ill-formed. 11149 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11150 // appear in a declaration of main. 11151 // static main is not an error under C99, but we should warn about it. 11152 // We accept _Noreturn main as an extension. 11153 if (FD->getStorageClass() == SC_Static) 11154 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11155 ? diag::err_static_main : diag::warn_static_main) 11156 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11157 if (FD->isInlineSpecified()) 11158 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11159 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11160 if (DS.isNoreturnSpecified()) { 11161 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11162 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11163 Diag(NoreturnLoc, diag::ext_noreturn_main); 11164 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11165 << FixItHint::CreateRemoval(NoreturnRange); 11166 } 11167 if (FD->isConstexpr()) { 11168 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11169 << FD->isConsteval() 11170 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11171 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11172 } 11173 11174 if (getLangOpts().OpenCL) { 11175 Diag(FD->getLocation(), diag::err_opencl_no_main) 11176 << FD->hasAttr<OpenCLKernelAttr>(); 11177 FD->setInvalidDecl(); 11178 return; 11179 } 11180 11181 QualType T = FD->getType(); 11182 assert(T->isFunctionType() && "function decl is not of function type"); 11183 const FunctionType* FT = T->castAs<FunctionType>(); 11184 11185 // Set default calling convention for main() 11186 if (FT->getCallConv() != CC_C) { 11187 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11188 FD->setType(QualType(FT, 0)); 11189 T = Context.getCanonicalType(FD->getType()); 11190 } 11191 11192 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11193 // In C with GNU extensions we allow main() to have non-integer return 11194 // type, but we should warn about the extension, and we disable the 11195 // implicit-return-zero rule. 11196 11197 // GCC in C mode accepts qualified 'int'. 11198 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11199 FD->setHasImplicitReturnZero(true); 11200 else { 11201 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11202 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11203 if (RTRange.isValid()) 11204 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11205 << FixItHint::CreateReplacement(RTRange, "int"); 11206 } 11207 } else { 11208 // In C and C++, main magically returns 0 if you fall off the end; 11209 // set the flag which tells us that. 11210 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11211 11212 // All the standards say that main() should return 'int'. 11213 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11214 FD->setHasImplicitReturnZero(true); 11215 else { 11216 // Otherwise, this is just a flat-out error. 11217 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11218 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11219 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11220 : FixItHint()); 11221 FD->setInvalidDecl(true); 11222 } 11223 } 11224 11225 // Treat protoless main() as nullary. 11226 if (isa<FunctionNoProtoType>(FT)) return; 11227 11228 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11229 unsigned nparams = FTP->getNumParams(); 11230 assert(FD->getNumParams() == nparams); 11231 11232 bool HasExtraParameters = (nparams > 3); 11233 11234 if (FTP->isVariadic()) { 11235 Diag(FD->getLocation(), diag::ext_variadic_main); 11236 // FIXME: if we had information about the location of the ellipsis, we 11237 // could add a FixIt hint to remove it as a parameter. 11238 } 11239 11240 // Darwin passes an undocumented fourth argument of type char**. If 11241 // other platforms start sprouting these, the logic below will start 11242 // getting shifty. 11243 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11244 HasExtraParameters = false; 11245 11246 if (HasExtraParameters) { 11247 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11248 FD->setInvalidDecl(true); 11249 nparams = 3; 11250 } 11251 11252 // FIXME: a lot of the following diagnostics would be improved 11253 // if we had some location information about types. 11254 11255 QualType CharPP = 11256 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11257 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11258 11259 for (unsigned i = 0; i < nparams; ++i) { 11260 QualType AT = FTP->getParamType(i); 11261 11262 bool mismatch = true; 11263 11264 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11265 mismatch = false; 11266 else if (Expected[i] == CharPP) { 11267 // As an extension, the following forms are okay: 11268 // char const ** 11269 // char const * const * 11270 // char * const * 11271 11272 QualifierCollector qs; 11273 const PointerType* PT; 11274 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11275 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11276 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11277 Context.CharTy)) { 11278 qs.removeConst(); 11279 mismatch = !qs.empty(); 11280 } 11281 } 11282 11283 if (mismatch) { 11284 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11285 // TODO: suggest replacing given type with expected type 11286 FD->setInvalidDecl(true); 11287 } 11288 } 11289 11290 if (nparams == 1 && !FD->isInvalidDecl()) { 11291 Diag(FD->getLocation(), diag::warn_main_one_arg); 11292 } 11293 11294 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11295 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11296 FD->setInvalidDecl(); 11297 } 11298 } 11299 11300 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11301 11302 // Default calling convention for main and wmain is __cdecl 11303 if (FD->getName() == "main" || FD->getName() == "wmain") 11304 return false; 11305 11306 // Default calling convention for MinGW is __cdecl 11307 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11308 if (T.isWindowsGNUEnvironment()) 11309 return false; 11310 11311 // Default calling convention for WinMain, wWinMain and DllMain 11312 // is __stdcall on 32 bit Windows 11313 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11314 return true; 11315 11316 return false; 11317 } 11318 11319 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11320 QualType T = FD->getType(); 11321 assert(T->isFunctionType() && "function decl is not of function type"); 11322 const FunctionType *FT = T->castAs<FunctionType>(); 11323 11324 // Set an implicit return of 'zero' if the function can return some integral, 11325 // enumeration, pointer or nullptr type. 11326 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11327 FT->getReturnType()->isAnyPointerType() || 11328 FT->getReturnType()->isNullPtrType()) 11329 // DllMain is exempt because a return value of zero means it failed. 11330 if (FD->getName() != "DllMain") 11331 FD->setHasImplicitReturnZero(true); 11332 11333 // Explicity specified calling conventions are applied to MSVC entry points 11334 if (!hasExplicitCallingConv(T)) { 11335 if (isDefaultStdCall(FD, *this)) { 11336 if (FT->getCallConv() != CC_X86StdCall) { 11337 FT = Context.adjustFunctionType( 11338 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11339 FD->setType(QualType(FT, 0)); 11340 } 11341 } else if (FT->getCallConv() != CC_C) { 11342 FT = Context.adjustFunctionType(FT, 11343 FT->getExtInfo().withCallingConv(CC_C)); 11344 FD->setType(QualType(FT, 0)); 11345 } 11346 } 11347 11348 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11349 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11350 FD->setInvalidDecl(); 11351 } 11352 } 11353 11354 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11355 // FIXME: Need strict checking. In C89, we need to check for 11356 // any assignment, increment, decrement, function-calls, or 11357 // commas outside of a sizeof. In C99, it's the same list, 11358 // except that the aforementioned are allowed in unevaluated 11359 // expressions. Everything else falls under the 11360 // "may accept other forms of constant expressions" exception. 11361 // 11362 // Regular C++ code will not end up here (exceptions: language extensions, 11363 // OpenCL C++ etc), so the constant expression rules there don't matter. 11364 if (Init->isValueDependent()) { 11365 assert(Init->containsErrors() && 11366 "Dependent code should only occur in error-recovery path."); 11367 return true; 11368 } 11369 const Expr *Culprit; 11370 if (Init->isConstantInitializer(Context, false, &Culprit)) 11371 return false; 11372 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11373 << Culprit->getSourceRange(); 11374 return true; 11375 } 11376 11377 namespace { 11378 // Visits an initialization expression to see if OrigDecl is evaluated in 11379 // its own initialization and throws a warning if it does. 11380 class SelfReferenceChecker 11381 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11382 Sema &S; 11383 Decl *OrigDecl; 11384 bool isRecordType; 11385 bool isPODType; 11386 bool isReferenceType; 11387 11388 bool isInitList; 11389 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11390 11391 public: 11392 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11393 11394 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11395 S(S), OrigDecl(OrigDecl) { 11396 isPODType = false; 11397 isRecordType = false; 11398 isReferenceType = false; 11399 isInitList = false; 11400 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11401 isPODType = VD->getType().isPODType(S.Context); 11402 isRecordType = VD->getType()->isRecordType(); 11403 isReferenceType = VD->getType()->isReferenceType(); 11404 } 11405 } 11406 11407 // For most expressions, just call the visitor. For initializer lists, 11408 // track the index of the field being initialized since fields are 11409 // initialized in order allowing use of previously initialized fields. 11410 void CheckExpr(Expr *E) { 11411 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11412 if (!InitList) { 11413 Visit(E); 11414 return; 11415 } 11416 11417 // Track and increment the index here. 11418 isInitList = true; 11419 InitFieldIndex.push_back(0); 11420 for (auto Child : InitList->children()) { 11421 CheckExpr(cast<Expr>(Child)); 11422 ++InitFieldIndex.back(); 11423 } 11424 InitFieldIndex.pop_back(); 11425 } 11426 11427 // Returns true if MemberExpr is checked and no further checking is needed. 11428 // Returns false if additional checking is required. 11429 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11430 llvm::SmallVector<FieldDecl*, 4> Fields; 11431 Expr *Base = E; 11432 bool ReferenceField = false; 11433 11434 // Get the field members used. 11435 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11436 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11437 if (!FD) 11438 return false; 11439 Fields.push_back(FD); 11440 if (FD->getType()->isReferenceType()) 11441 ReferenceField = true; 11442 Base = ME->getBase()->IgnoreParenImpCasts(); 11443 } 11444 11445 // Keep checking only if the base Decl is the same. 11446 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11447 if (!DRE || DRE->getDecl() != OrigDecl) 11448 return false; 11449 11450 // A reference field can be bound to an unininitialized field. 11451 if (CheckReference && !ReferenceField) 11452 return true; 11453 11454 // Convert FieldDecls to their index number. 11455 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11456 for (const FieldDecl *I : llvm::reverse(Fields)) 11457 UsedFieldIndex.push_back(I->getFieldIndex()); 11458 11459 // See if a warning is needed by checking the first difference in index 11460 // numbers. If field being used has index less than the field being 11461 // initialized, then the use is safe. 11462 for (auto UsedIter = UsedFieldIndex.begin(), 11463 UsedEnd = UsedFieldIndex.end(), 11464 OrigIter = InitFieldIndex.begin(), 11465 OrigEnd = InitFieldIndex.end(); 11466 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11467 if (*UsedIter < *OrigIter) 11468 return true; 11469 if (*UsedIter > *OrigIter) 11470 break; 11471 } 11472 11473 // TODO: Add a different warning which will print the field names. 11474 HandleDeclRefExpr(DRE); 11475 return true; 11476 } 11477 11478 // For most expressions, the cast is directly above the DeclRefExpr. 11479 // For conditional operators, the cast can be outside the conditional 11480 // operator if both expressions are DeclRefExpr's. 11481 void HandleValue(Expr *E) { 11482 E = E->IgnoreParens(); 11483 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11484 HandleDeclRefExpr(DRE); 11485 return; 11486 } 11487 11488 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11489 Visit(CO->getCond()); 11490 HandleValue(CO->getTrueExpr()); 11491 HandleValue(CO->getFalseExpr()); 11492 return; 11493 } 11494 11495 if (BinaryConditionalOperator *BCO = 11496 dyn_cast<BinaryConditionalOperator>(E)) { 11497 Visit(BCO->getCond()); 11498 HandleValue(BCO->getFalseExpr()); 11499 return; 11500 } 11501 11502 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11503 HandleValue(OVE->getSourceExpr()); 11504 return; 11505 } 11506 11507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11508 if (BO->getOpcode() == BO_Comma) { 11509 Visit(BO->getLHS()); 11510 HandleValue(BO->getRHS()); 11511 return; 11512 } 11513 } 11514 11515 if (isa<MemberExpr>(E)) { 11516 if (isInitList) { 11517 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11518 false /*CheckReference*/)) 11519 return; 11520 } 11521 11522 Expr *Base = E->IgnoreParenImpCasts(); 11523 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11524 // Check for static member variables and don't warn on them. 11525 if (!isa<FieldDecl>(ME->getMemberDecl())) 11526 return; 11527 Base = ME->getBase()->IgnoreParenImpCasts(); 11528 } 11529 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11530 HandleDeclRefExpr(DRE); 11531 return; 11532 } 11533 11534 Visit(E); 11535 } 11536 11537 // Reference types not handled in HandleValue are handled here since all 11538 // uses of references are bad, not just r-value uses. 11539 void VisitDeclRefExpr(DeclRefExpr *E) { 11540 if (isReferenceType) 11541 HandleDeclRefExpr(E); 11542 } 11543 11544 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11545 if (E->getCastKind() == CK_LValueToRValue) { 11546 HandleValue(E->getSubExpr()); 11547 return; 11548 } 11549 11550 Inherited::VisitImplicitCastExpr(E); 11551 } 11552 11553 void VisitMemberExpr(MemberExpr *E) { 11554 if (isInitList) { 11555 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11556 return; 11557 } 11558 11559 // Don't warn on arrays since they can be treated as pointers. 11560 if (E->getType()->canDecayToPointerType()) return; 11561 11562 // Warn when a non-static method call is followed by non-static member 11563 // field accesses, which is followed by a DeclRefExpr. 11564 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11565 bool Warn = (MD && !MD->isStatic()); 11566 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11567 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11568 if (!isa<FieldDecl>(ME->getMemberDecl())) 11569 Warn = false; 11570 Base = ME->getBase()->IgnoreParenImpCasts(); 11571 } 11572 11573 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11574 if (Warn) 11575 HandleDeclRefExpr(DRE); 11576 return; 11577 } 11578 11579 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11580 // Visit that expression. 11581 Visit(Base); 11582 } 11583 11584 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11585 Expr *Callee = E->getCallee(); 11586 11587 if (isa<UnresolvedLookupExpr>(Callee)) 11588 return Inherited::VisitCXXOperatorCallExpr(E); 11589 11590 Visit(Callee); 11591 for (auto Arg: E->arguments()) 11592 HandleValue(Arg->IgnoreParenImpCasts()); 11593 } 11594 11595 void VisitUnaryOperator(UnaryOperator *E) { 11596 // For POD record types, addresses of its own members are well-defined. 11597 if (E->getOpcode() == UO_AddrOf && isRecordType && 11598 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11599 if (!isPODType) 11600 HandleValue(E->getSubExpr()); 11601 return; 11602 } 11603 11604 if (E->isIncrementDecrementOp()) { 11605 HandleValue(E->getSubExpr()); 11606 return; 11607 } 11608 11609 Inherited::VisitUnaryOperator(E); 11610 } 11611 11612 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11613 11614 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11615 if (E->getConstructor()->isCopyConstructor()) { 11616 Expr *ArgExpr = E->getArg(0); 11617 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11618 if (ILE->getNumInits() == 1) 11619 ArgExpr = ILE->getInit(0); 11620 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11621 if (ICE->getCastKind() == CK_NoOp) 11622 ArgExpr = ICE->getSubExpr(); 11623 HandleValue(ArgExpr); 11624 return; 11625 } 11626 Inherited::VisitCXXConstructExpr(E); 11627 } 11628 11629 void VisitCallExpr(CallExpr *E) { 11630 // Treat std::move as a use. 11631 if (E->isCallToStdMove()) { 11632 HandleValue(E->getArg(0)); 11633 return; 11634 } 11635 11636 Inherited::VisitCallExpr(E); 11637 } 11638 11639 void VisitBinaryOperator(BinaryOperator *E) { 11640 if (E->isCompoundAssignmentOp()) { 11641 HandleValue(E->getLHS()); 11642 Visit(E->getRHS()); 11643 return; 11644 } 11645 11646 Inherited::VisitBinaryOperator(E); 11647 } 11648 11649 // A custom visitor for BinaryConditionalOperator is needed because the 11650 // regular visitor would check the condition and true expression separately 11651 // but both point to the same place giving duplicate diagnostics. 11652 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11653 Visit(E->getCond()); 11654 Visit(E->getFalseExpr()); 11655 } 11656 11657 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11658 Decl* ReferenceDecl = DRE->getDecl(); 11659 if (OrigDecl != ReferenceDecl) return; 11660 unsigned diag; 11661 if (isReferenceType) { 11662 diag = diag::warn_uninit_self_reference_in_reference_init; 11663 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11664 diag = diag::warn_static_self_reference_in_init; 11665 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11666 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11667 DRE->getDecl()->getType()->isRecordType()) { 11668 diag = diag::warn_uninit_self_reference_in_init; 11669 } else { 11670 // Local variables will be handled by the CFG analysis. 11671 return; 11672 } 11673 11674 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11675 S.PDiag(diag) 11676 << DRE->getDecl() << OrigDecl->getLocation() 11677 << DRE->getSourceRange()); 11678 } 11679 }; 11680 11681 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11682 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11683 bool DirectInit) { 11684 // Parameters arguments are occassionially constructed with itself, 11685 // for instance, in recursive functions. Skip them. 11686 if (isa<ParmVarDecl>(OrigDecl)) 11687 return; 11688 11689 E = E->IgnoreParens(); 11690 11691 // Skip checking T a = a where T is not a record or reference type. 11692 // Doing so is a way to silence uninitialized warnings. 11693 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11694 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11695 if (ICE->getCastKind() == CK_LValueToRValue) 11696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11697 if (DRE->getDecl() == OrigDecl) 11698 return; 11699 11700 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11701 } 11702 } // end anonymous namespace 11703 11704 namespace { 11705 // Simple wrapper to add the name of a variable or (if no variable is 11706 // available) a DeclarationName into a diagnostic. 11707 struct VarDeclOrName { 11708 VarDecl *VDecl; 11709 DeclarationName Name; 11710 11711 friend const Sema::SemaDiagnosticBuilder & 11712 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11713 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11714 } 11715 }; 11716 } // end anonymous namespace 11717 11718 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11719 DeclarationName Name, QualType Type, 11720 TypeSourceInfo *TSI, 11721 SourceRange Range, bool DirectInit, 11722 Expr *Init) { 11723 bool IsInitCapture = !VDecl; 11724 assert((!VDecl || !VDecl->isInitCapture()) && 11725 "init captures are expected to be deduced prior to initialization"); 11726 11727 VarDeclOrName VN{VDecl, Name}; 11728 11729 DeducedType *Deduced = Type->getContainedDeducedType(); 11730 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11731 11732 // C++11 [dcl.spec.auto]p3 11733 if (!Init) { 11734 assert(VDecl && "no init for init capture deduction?"); 11735 11736 // Except for class argument deduction, and then for an initializing 11737 // declaration only, i.e. no static at class scope or extern. 11738 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11739 VDecl->hasExternalStorage() || 11740 VDecl->isStaticDataMember()) { 11741 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11742 << VDecl->getDeclName() << Type; 11743 return QualType(); 11744 } 11745 } 11746 11747 ArrayRef<Expr*> DeduceInits; 11748 if (Init) 11749 DeduceInits = Init; 11750 11751 if (DirectInit) { 11752 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11753 DeduceInits = PL->exprs(); 11754 } 11755 11756 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11757 assert(VDecl && "non-auto type for init capture deduction?"); 11758 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11759 InitializationKind Kind = InitializationKind::CreateForInit( 11760 VDecl->getLocation(), DirectInit, Init); 11761 // FIXME: Initialization should not be taking a mutable list of inits. 11762 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11763 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11764 InitsCopy); 11765 } 11766 11767 if (DirectInit) { 11768 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11769 DeduceInits = IL->inits(); 11770 } 11771 11772 // Deduction only works if we have exactly one source expression. 11773 if (DeduceInits.empty()) { 11774 // It isn't possible to write this directly, but it is possible to 11775 // end up in this situation with "auto x(some_pack...);" 11776 Diag(Init->getBeginLoc(), IsInitCapture 11777 ? diag::err_init_capture_no_expression 11778 : diag::err_auto_var_init_no_expression) 11779 << VN << Type << Range; 11780 return QualType(); 11781 } 11782 11783 if (DeduceInits.size() > 1) { 11784 Diag(DeduceInits[1]->getBeginLoc(), 11785 IsInitCapture ? diag::err_init_capture_multiple_expressions 11786 : diag::err_auto_var_init_multiple_expressions) 11787 << VN << Type << Range; 11788 return QualType(); 11789 } 11790 11791 Expr *DeduceInit = DeduceInits[0]; 11792 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11793 Diag(Init->getBeginLoc(), IsInitCapture 11794 ? diag::err_init_capture_paren_braces 11795 : diag::err_auto_var_init_paren_braces) 11796 << isa<InitListExpr>(Init) << VN << Type << Range; 11797 return QualType(); 11798 } 11799 11800 // Expressions default to 'id' when we're in a debugger. 11801 bool DefaultedAnyToId = false; 11802 if (getLangOpts().DebuggerCastResultToId && 11803 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11804 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11805 if (Result.isInvalid()) { 11806 return QualType(); 11807 } 11808 Init = Result.get(); 11809 DefaultedAnyToId = true; 11810 } 11811 11812 // C++ [dcl.decomp]p1: 11813 // If the assignment-expression [...] has array type A and no ref-qualifier 11814 // is present, e has type cv A 11815 if (VDecl && isa<DecompositionDecl>(VDecl) && 11816 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11817 DeduceInit->getType()->isConstantArrayType()) 11818 return Context.getQualifiedType(DeduceInit->getType(), 11819 Type.getQualifiers()); 11820 11821 QualType DeducedType; 11822 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11823 if (!IsInitCapture) 11824 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11825 else if (isa<InitListExpr>(Init)) 11826 Diag(Range.getBegin(), 11827 diag::err_init_capture_deduction_failure_from_init_list) 11828 << VN 11829 << (DeduceInit->getType().isNull() ? TSI->getType() 11830 : DeduceInit->getType()) 11831 << DeduceInit->getSourceRange(); 11832 else 11833 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11834 << VN << TSI->getType() 11835 << (DeduceInit->getType().isNull() ? TSI->getType() 11836 : DeduceInit->getType()) 11837 << DeduceInit->getSourceRange(); 11838 } 11839 11840 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11841 // 'id' instead of a specific object type prevents most of our usual 11842 // checks. 11843 // We only want to warn outside of template instantiations, though: 11844 // inside a template, the 'id' could have come from a parameter. 11845 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11846 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11847 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11848 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11849 } 11850 11851 return DeducedType; 11852 } 11853 11854 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11855 Expr *Init) { 11856 assert(!Init || !Init->containsErrors()); 11857 QualType DeducedType = deduceVarTypeFromInitializer( 11858 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11859 VDecl->getSourceRange(), DirectInit, Init); 11860 if (DeducedType.isNull()) { 11861 VDecl->setInvalidDecl(); 11862 return true; 11863 } 11864 11865 VDecl->setType(DeducedType); 11866 assert(VDecl->isLinkageValid()); 11867 11868 // In ARC, infer lifetime. 11869 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11870 VDecl->setInvalidDecl(); 11871 11872 if (getLangOpts().OpenCL) 11873 deduceOpenCLAddressSpace(VDecl); 11874 11875 // If this is a redeclaration, check that the type we just deduced matches 11876 // the previously declared type. 11877 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11878 // We never need to merge the type, because we cannot form an incomplete 11879 // array of auto, nor deduce such a type. 11880 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11881 } 11882 11883 // Check the deduced type is valid for a variable declaration. 11884 CheckVariableDeclarationType(VDecl); 11885 return VDecl->isInvalidDecl(); 11886 } 11887 11888 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11889 SourceLocation Loc) { 11890 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11891 Init = EWC->getSubExpr(); 11892 11893 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11894 Init = CE->getSubExpr(); 11895 11896 QualType InitType = Init->getType(); 11897 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11898 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11899 "shouldn't be called if type doesn't have a non-trivial C struct"); 11900 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11901 for (auto I : ILE->inits()) { 11902 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11903 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11904 continue; 11905 SourceLocation SL = I->getExprLoc(); 11906 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11907 } 11908 return; 11909 } 11910 11911 if (isa<ImplicitValueInitExpr>(Init)) { 11912 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11913 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11914 NTCUK_Init); 11915 } else { 11916 // Assume all other explicit initializers involving copying some existing 11917 // object. 11918 // TODO: ignore any explicit initializers where we can guarantee 11919 // copy-elision. 11920 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11921 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11922 } 11923 } 11924 11925 namespace { 11926 11927 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11928 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11929 // in the source code or implicitly by the compiler if it is in a union 11930 // defined in a system header and has non-trivial ObjC ownership 11931 // qualifications. We don't want those fields to participate in determining 11932 // whether the containing union is non-trivial. 11933 return FD->hasAttr<UnavailableAttr>(); 11934 } 11935 11936 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11937 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11938 void> { 11939 using Super = 11940 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11941 void>; 11942 11943 DiagNonTrivalCUnionDefaultInitializeVisitor( 11944 QualType OrigTy, SourceLocation OrigLoc, 11945 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11946 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11947 11948 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11949 const FieldDecl *FD, bool InNonTrivialUnion) { 11950 if (const auto *AT = S.Context.getAsArrayType(QT)) 11951 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11952 InNonTrivialUnion); 11953 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11954 } 11955 11956 void visitARCStrong(QualType QT, const FieldDecl *FD, 11957 bool InNonTrivialUnion) { 11958 if (InNonTrivialUnion) 11959 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11960 << 1 << 0 << QT << FD->getName(); 11961 } 11962 11963 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11964 if (InNonTrivialUnion) 11965 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11966 << 1 << 0 << QT << FD->getName(); 11967 } 11968 11969 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11970 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11971 if (RD->isUnion()) { 11972 if (OrigLoc.isValid()) { 11973 bool IsUnion = false; 11974 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11975 IsUnion = OrigRD->isUnion(); 11976 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11977 << 0 << OrigTy << IsUnion << UseContext; 11978 // Reset OrigLoc so that this diagnostic is emitted only once. 11979 OrigLoc = SourceLocation(); 11980 } 11981 InNonTrivialUnion = true; 11982 } 11983 11984 if (InNonTrivialUnion) 11985 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11986 << 0 << 0 << QT.getUnqualifiedType() << ""; 11987 11988 for (const FieldDecl *FD : RD->fields()) 11989 if (!shouldIgnoreForRecordTriviality(FD)) 11990 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11991 } 11992 11993 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11994 11995 // The non-trivial C union type or the struct/union type that contains a 11996 // non-trivial C union. 11997 QualType OrigTy; 11998 SourceLocation OrigLoc; 11999 Sema::NonTrivialCUnionContext UseContext; 12000 Sema &S; 12001 }; 12002 12003 struct DiagNonTrivalCUnionDestructedTypeVisitor 12004 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12005 using Super = 12006 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12007 12008 DiagNonTrivalCUnionDestructedTypeVisitor( 12009 QualType OrigTy, SourceLocation OrigLoc, 12010 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12011 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12012 12013 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12014 const FieldDecl *FD, bool InNonTrivialUnion) { 12015 if (const auto *AT = S.Context.getAsArrayType(QT)) 12016 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12017 InNonTrivialUnion); 12018 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12019 } 12020 12021 void visitARCStrong(QualType QT, const FieldDecl *FD, 12022 bool InNonTrivialUnion) { 12023 if (InNonTrivialUnion) 12024 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12025 << 1 << 1 << QT << FD->getName(); 12026 } 12027 12028 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12029 if (InNonTrivialUnion) 12030 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12031 << 1 << 1 << QT << FD->getName(); 12032 } 12033 12034 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12035 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12036 if (RD->isUnion()) { 12037 if (OrigLoc.isValid()) { 12038 bool IsUnion = false; 12039 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12040 IsUnion = OrigRD->isUnion(); 12041 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12042 << 1 << OrigTy << IsUnion << UseContext; 12043 // Reset OrigLoc so that this diagnostic is emitted only once. 12044 OrigLoc = SourceLocation(); 12045 } 12046 InNonTrivialUnion = true; 12047 } 12048 12049 if (InNonTrivialUnion) 12050 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12051 << 0 << 1 << QT.getUnqualifiedType() << ""; 12052 12053 for (const FieldDecl *FD : RD->fields()) 12054 if (!shouldIgnoreForRecordTriviality(FD)) 12055 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12056 } 12057 12058 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12059 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12060 bool InNonTrivialUnion) {} 12061 12062 // The non-trivial C union type or the struct/union type that contains a 12063 // non-trivial C union. 12064 QualType OrigTy; 12065 SourceLocation OrigLoc; 12066 Sema::NonTrivialCUnionContext UseContext; 12067 Sema &S; 12068 }; 12069 12070 struct DiagNonTrivalCUnionCopyVisitor 12071 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12072 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12073 12074 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12075 Sema::NonTrivialCUnionContext UseContext, 12076 Sema &S) 12077 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12078 12079 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12080 const FieldDecl *FD, bool InNonTrivialUnion) { 12081 if (const auto *AT = S.Context.getAsArrayType(QT)) 12082 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12083 InNonTrivialUnion); 12084 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12085 } 12086 12087 void visitARCStrong(QualType QT, const FieldDecl *FD, 12088 bool InNonTrivialUnion) { 12089 if (InNonTrivialUnion) 12090 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12091 << 1 << 2 << QT << FD->getName(); 12092 } 12093 12094 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12095 if (InNonTrivialUnion) 12096 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12097 << 1 << 2 << QT << FD->getName(); 12098 } 12099 12100 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12101 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12102 if (RD->isUnion()) { 12103 if (OrigLoc.isValid()) { 12104 bool IsUnion = false; 12105 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12106 IsUnion = OrigRD->isUnion(); 12107 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12108 << 2 << OrigTy << IsUnion << UseContext; 12109 // Reset OrigLoc so that this diagnostic is emitted only once. 12110 OrigLoc = SourceLocation(); 12111 } 12112 InNonTrivialUnion = true; 12113 } 12114 12115 if (InNonTrivialUnion) 12116 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12117 << 0 << 2 << QT.getUnqualifiedType() << ""; 12118 12119 for (const FieldDecl *FD : RD->fields()) 12120 if (!shouldIgnoreForRecordTriviality(FD)) 12121 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12122 } 12123 12124 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12125 const FieldDecl *FD, bool InNonTrivialUnion) {} 12126 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12127 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12128 bool InNonTrivialUnion) {} 12129 12130 // The non-trivial C union type or the struct/union type that contains a 12131 // non-trivial C union. 12132 QualType OrigTy; 12133 SourceLocation OrigLoc; 12134 Sema::NonTrivialCUnionContext UseContext; 12135 Sema &S; 12136 }; 12137 12138 } // namespace 12139 12140 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12141 NonTrivialCUnionContext UseContext, 12142 unsigned NonTrivialKind) { 12143 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12144 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12145 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12146 "shouldn't be called if type doesn't have a non-trivial C union"); 12147 12148 if ((NonTrivialKind & NTCUK_Init) && 12149 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12150 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12151 .visit(QT, nullptr, false); 12152 if ((NonTrivialKind & NTCUK_Destruct) && 12153 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12154 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12155 .visit(QT, nullptr, false); 12156 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12157 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12158 .visit(QT, nullptr, false); 12159 } 12160 12161 /// AddInitializerToDecl - Adds the initializer Init to the 12162 /// declaration dcl. If DirectInit is true, this is C++ direct 12163 /// initialization rather than copy initialization. 12164 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12165 // If there is no declaration, there was an error parsing it. Just ignore 12166 // the initializer. 12167 if (!RealDecl || RealDecl->isInvalidDecl()) { 12168 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12169 return; 12170 } 12171 12172 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12173 // Pure-specifiers are handled in ActOnPureSpecifier. 12174 Diag(Method->getLocation(), diag::err_member_function_initialization) 12175 << Method->getDeclName() << Init->getSourceRange(); 12176 Method->setInvalidDecl(); 12177 return; 12178 } 12179 12180 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12181 if (!VDecl) { 12182 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12183 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12184 RealDecl->setInvalidDecl(); 12185 return; 12186 } 12187 12188 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12189 if (VDecl->getType()->isUndeducedType()) { 12190 // Attempt typo correction early so that the type of the init expression can 12191 // be deduced based on the chosen correction if the original init contains a 12192 // TypoExpr. 12193 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12194 if (!Res.isUsable()) { 12195 // There are unresolved typos in Init, just drop them. 12196 // FIXME: improve the recovery strategy to preserve the Init. 12197 RealDecl->setInvalidDecl(); 12198 return; 12199 } 12200 if (Res.get()->containsErrors()) { 12201 // Invalidate the decl as we don't know the type for recovery-expr yet. 12202 RealDecl->setInvalidDecl(); 12203 VDecl->setInit(Res.get()); 12204 return; 12205 } 12206 Init = Res.get(); 12207 12208 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12209 return; 12210 } 12211 12212 // dllimport cannot be used on variable definitions. 12213 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12214 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12215 VDecl->setInvalidDecl(); 12216 return; 12217 } 12218 12219 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12220 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12221 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12222 VDecl->setInvalidDecl(); 12223 return; 12224 } 12225 12226 if (!VDecl->getType()->isDependentType()) { 12227 // A definition must end up with a complete type, which means it must be 12228 // complete with the restriction that an array type might be completed by 12229 // the initializer; note that later code assumes this restriction. 12230 QualType BaseDeclType = VDecl->getType(); 12231 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12232 BaseDeclType = Array->getElementType(); 12233 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12234 diag::err_typecheck_decl_incomplete_type)) { 12235 RealDecl->setInvalidDecl(); 12236 return; 12237 } 12238 12239 // The variable can not have an abstract class type. 12240 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12241 diag::err_abstract_type_in_decl, 12242 AbstractVariableType)) 12243 VDecl->setInvalidDecl(); 12244 } 12245 12246 // If adding the initializer will turn this declaration into a definition, 12247 // and we already have a definition for this variable, diagnose or otherwise 12248 // handle the situation. 12249 if (VarDecl *Def = VDecl->getDefinition()) 12250 if (Def != VDecl && 12251 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12252 !VDecl->isThisDeclarationADemotedDefinition() && 12253 checkVarDeclRedefinition(Def, VDecl)) 12254 return; 12255 12256 if (getLangOpts().CPlusPlus) { 12257 // C++ [class.static.data]p4 12258 // If a static data member is of const integral or const 12259 // enumeration type, its declaration in the class definition can 12260 // specify a constant-initializer which shall be an integral 12261 // constant expression (5.19). In that case, the member can appear 12262 // in integral constant expressions. The member shall still be 12263 // defined in a namespace scope if it is used in the program and the 12264 // namespace scope definition shall not contain an initializer. 12265 // 12266 // We already performed a redefinition check above, but for static 12267 // data members we also need to check whether there was an in-class 12268 // declaration with an initializer. 12269 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12270 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12271 << VDecl->getDeclName(); 12272 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12273 diag::note_previous_initializer) 12274 << 0; 12275 return; 12276 } 12277 12278 if (VDecl->hasLocalStorage()) 12279 setFunctionHasBranchProtectedScope(); 12280 12281 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12282 VDecl->setInvalidDecl(); 12283 return; 12284 } 12285 } 12286 12287 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12288 // a kernel function cannot be initialized." 12289 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12290 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12291 VDecl->setInvalidDecl(); 12292 return; 12293 } 12294 12295 // The LoaderUninitialized attribute acts as a definition (of undef). 12296 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12297 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12298 VDecl->setInvalidDecl(); 12299 return; 12300 } 12301 12302 // Get the decls type and save a reference for later, since 12303 // CheckInitializerTypes may change it. 12304 QualType DclT = VDecl->getType(), SavT = DclT; 12305 12306 // Expressions default to 'id' when we're in a debugger 12307 // and we are assigning it to a variable of Objective-C pointer type. 12308 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12309 Init->getType() == Context.UnknownAnyTy) { 12310 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12311 if (Result.isInvalid()) { 12312 VDecl->setInvalidDecl(); 12313 return; 12314 } 12315 Init = Result.get(); 12316 } 12317 12318 // Perform the initialization. 12319 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12320 if (!VDecl->isInvalidDecl()) { 12321 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12322 InitializationKind Kind = InitializationKind::CreateForInit( 12323 VDecl->getLocation(), DirectInit, Init); 12324 12325 MultiExprArg Args = Init; 12326 if (CXXDirectInit) 12327 Args = MultiExprArg(CXXDirectInit->getExprs(), 12328 CXXDirectInit->getNumExprs()); 12329 12330 // Try to correct any TypoExprs in the initialization arguments. 12331 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12332 ExprResult Res = CorrectDelayedTyposInExpr( 12333 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12334 [this, Entity, Kind](Expr *E) { 12335 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12336 return Init.Failed() ? ExprError() : E; 12337 }); 12338 if (Res.isInvalid()) { 12339 VDecl->setInvalidDecl(); 12340 } else if (Res.get() != Args[Idx]) { 12341 Args[Idx] = Res.get(); 12342 } 12343 } 12344 if (VDecl->isInvalidDecl()) 12345 return; 12346 12347 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12348 /*TopLevelOfInitList=*/false, 12349 /*TreatUnavailableAsInvalid=*/false); 12350 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12351 if (Result.isInvalid()) { 12352 // If the provided initializer fails to initialize the var decl, 12353 // we attach a recovery expr for better recovery. 12354 auto RecoveryExpr = 12355 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12356 if (RecoveryExpr.get()) 12357 VDecl->setInit(RecoveryExpr.get()); 12358 return; 12359 } 12360 12361 Init = Result.getAs<Expr>(); 12362 } 12363 12364 // Check for self-references within variable initializers. 12365 // Variables declared within a function/method body (except for references) 12366 // are handled by a dataflow analysis. 12367 // This is undefined behavior in C++, but valid in C. 12368 if (getLangOpts().CPlusPlus) 12369 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12370 VDecl->getType()->isReferenceType()) 12371 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12372 12373 // If the type changed, it means we had an incomplete type that was 12374 // completed by the initializer. For example: 12375 // int ary[] = { 1, 3, 5 }; 12376 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12377 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12378 VDecl->setType(DclT); 12379 12380 if (!VDecl->isInvalidDecl()) { 12381 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12382 12383 if (VDecl->hasAttr<BlocksAttr>()) 12384 checkRetainCycles(VDecl, Init); 12385 12386 // It is safe to assign a weak reference into a strong variable. 12387 // Although this code can still have problems: 12388 // id x = self.weakProp; 12389 // id y = self.weakProp; 12390 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12391 // paths through the function. This should be revisited if 12392 // -Wrepeated-use-of-weak is made flow-sensitive. 12393 if (FunctionScopeInfo *FSI = getCurFunction()) 12394 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12395 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12396 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12397 Init->getBeginLoc())) 12398 FSI->markSafeWeakUse(Init); 12399 } 12400 12401 // The initialization is usually a full-expression. 12402 // 12403 // FIXME: If this is a braced initialization of an aggregate, it is not 12404 // an expression, and each individual field initializer is a separate 12405 // full-expression. For instance, in: 12406 // 12407 // struct Temp { ~Temp(); }; 12408 // struct S { S(Temp); }; 12409 // struct T { S a, b; } t = { Temp(), Temp() } 12410 // 12411 // we should destroy the first Temp before constructing the second. 12412 ExprResult Result = 12413 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12414 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12415 if (Result.isInvalid()) { 12416 VDecl->setInvalidDecl(); 12417 return; 12418 } 12419 Init = Result.get(); 12420 12421 // Attach the initializer to the decl. 12422 VDecl->setInit(Init); 12423 12424 if (VDecl->isLocalVarDecl()) { 12425 // Don't check the initializer if the declaration is malformed. 12426 if (VDecl->isInvalidDecl()) { 12427 // do nothing 12428 12429 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12430 // This is true even in C++ for OpenCL. 12431 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12432 CheckForConstantInitializer(Init, DclT); 12433 12434 // Otherwise, C++ does not restrict the initializer. 12435 } else if (getLangOpts().CPlusPlus) { 12436 // do nothing 12437 12438 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12439 // static storage duration shall be constant expressions or string literals. 12440 } else if (VDecl->getStorageClass() == SC_Static) { 12441 CheckForConstantInitializer(Init, DclT); 12442 12443 // C89 is stricter than C99 for aggregate initializers. 12444 // C89 6.5.7p3: All the expressions [...] in an initializer list 12445 // for an object that has aggregate or union type shall be 12446 // constant expressions. 12447 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12448 isa<InitListExpr>(Init)) { 12449 const Expr *Culprit; 12450 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12451 Diag(Culprit->getExprLoc(), 12452 diag::ext_aggregate_init_not_constant) 12453 << Culprit->getSourceRange(); 12454 } 12455 } 12456 12457 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12458 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12459 if (VDecl->hasLocalStorage()) 12460 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12461 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12462 VDecl->getLexicalDeclContext()->isRecord()) { 12463 // This is an in-class initialization for a static data member, e.g., 12464 // 12465 // struct S { 12466 // static const int value = 17; 12467 // }; 12468 12469 // C++ [class.mem]p4: 12470 // A member-declarator can contain a constant-initializer only 12471 // if it declares a static member (9.4) of const integral or 12472 // const enumeration type, see 9.4.2. 12473 // 12474 // C++11 [class.static.data]p3: 12475 // If a non-volatile non-inline const static data member is of integral 12476 // or enumeration type, its declaration in the class definition can 12477 // specify a brace-or-equal-initializer in which every initializer-clause 12478 // that is an assignment-expression is a constant expression. A static 12479 // data member of literal type can be declared in the class definition 12480 // with the constexpr specifier; if so, its declaration shall specify a 12481 // brace-or-equal-initializer in which every initializer-clause that is 12482 // an assignment-expression is a constant expression. 12483 12484 // Do nothing on dependent types. 12485 if (DclT->isDependentType()) { 12486 12487 // Allow any 'static constexpr' members, whether or not they are of literal 12488 // type. We separately check that every constexpr variable is of literal 12489 // type. 12490 } else if (VDecl->isConstexpr()) { 12491 12492 // Require constness. 12493 } else if (!DclT.isConstQualified()) { 12494 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12495 << Init->getSourceRange(); 12496 VDecl->setInvalidDecl(); 12497 12498 // We allow integer constant expressions in all cases. 12499 } else if (DclT->isIntegralOrEnumerationType()) { 12500 // Check whether the expression is a constant expression. 12501 SourceLocation Loc; 12502 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12503 // In C++11, a non-constexpr const static data member with an 12504 // in-class initializer cannot be volatile. 12505 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12506 else if (Init->isValueDependent()) 12507 ; // Nothing to check. 12508 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12509 ; // Ok, it's an ICE! 12510 else if (Init->getType()->isScopedEnumeralType() && 12511 Init->isCXX11ConstantExpr(Context)) 12512 ; // Ok, it is a scoped-enum constant expression. 12513 else if (Init->isEvaluatable(Context)) { 12514 // If we can constant fold the initializer through heroics, accept it, 12515 // but report this as a use of an extension for -pedantic. 12516 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12517 << Init->getSourceRange(); 12518 } else { 12519 // Otherwise, this is some crazy unknown case. Report the issue at the 12520 // location provided by the isIntegerConstantExpr failed check. 12521 Diag(Loc, diag::err_in_class_initializer_non_constant) 12522 << Init->getSourceRange(); 12523 VDecl->setInvalidDecl(); 12524 } 12525 12526 // We allow foldable floating-point constants as an extension. 12527 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12528 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12529 // it anyway and provide a fixit to add the 'constexpr'. 12530 if (getLangOpts().CPlusPlus11) { 12531 Diag(VDecl->getLocation(), 12532 diag::ext_in_class_initializer_float_type_cxx11) 12533 << DclT << Init->getSourceRange(); 12534 Diag(VDecl->getBeginLoc(), 12535 diag::note_in_class_initializer_float_type_cxx11) 12536 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12537 } else { 12538 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12539 << DclT << Init->getSourceRange(); 12540 12541 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12542 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12543 << Init->getSourceRange(); 12544 VDecl->setInvalidDecl(); 12545 } 12546 } 12547 12548 // Suggest adding 'constexpr' in C++11 for literal types. 12549 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12550 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12551 << DclT << Init->getSourceRange() 12552 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12553 VDecl->setConstexpr(true); 12554 12555 } else { 12556 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12557 << DclT << Init->getSourceRange(); 12558 VDecl->setInvalidDecl(); 12559 } 12560 } else if (VDecl->isFileVarDecl()) { 12561 // In C, extern is typically used to avoid tentative definitions when 12562 // declaring variables in headers, but adding an intializer makes it a 12563 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12564 // In C++, extern is often used to give implictly static const variables 12565 // external linkage, so don't warn in that case. If selectany is present, 12566 // this might be header code intended for C and C++ inclusion, so apply the 12567 // C++ rules. 12568 if (VDecl->getStorageClass() == SC_Extern && 12569 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12570 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12571 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12572 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12573 Diag(VDecl->getLocation(), diag::warn_extern_init); 12574 12575 // In Microsoft C++ mode, a const variable defined in namespace scope has 12576 // external linkage by default if the variable is declared with 12577 // __declspec(dllexport). 12578 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12579 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12580 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12581 VDecl->setStorageClass(SC_Extern); 12582 12583 // C99 6.7.8p4. All file scoped initializers need to be constant. 12584 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12585 CheckForConstantInitializer(Init, DclT); 12586 } 12587 12588 QualType InitType = Init->getType(); 12589 if (!InitType.isNull() && 12590 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12591 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12592 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12593 12594 // We will represent direct-initialization similarly to copy-initialization: 12595 // int x(1); -as-> int x = 1; 12596 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12597 // 12598 // Clients that want to distinguish between the two forms, can check for 12599 // direct initializer using VarDecl::getInitStyle(). 12600 // A major benefit is that clients that don't particularly care about which 12601 // exactly form was it (like the CodeGen) can handle both cases without 12602 // special case code. 12603 12604 // C++ 8.5p11: 12605 // The form of initialization (using parentheses or '=') is generally 12606 // insignificant, but does matter when the entity being initialized has a 12607 // class type. 12608 if (CXXDirectInit) { 12609 assert(DirectInit && "Call-style initializer must be direct init."); 12610 VDecl->setInitStyle(VarDecl::CallInit); 12611 } else if (DirectInit) { 12612 // This must be list-initialization. No other way is direct-initialization. 12613 VDecl->setInitStyle(VarDecl::ListInit); 12614 } 12615 12616 if (LangOpts.OpenMP && 12617 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12618 VDecl->isFileVarDecl()) 12619 DeclsToCheckForDeferredDiags.insert(VDecl); 12620 CheckCompleteVariableDeclaration(VDecl); 12621 } 12622 12623 /// ActOnInitializerError - Given that there was an error parsing an 12624 /// initializer for the given declaration, try to return to some form 12625 /// of sanity. 12626 void Sema::ActOnInitializerError(Decl *D) { 12627 // Our main concern here is re-establishing invariants like "a 12628 // variable's type is either dependent or complete". 12629 if (!D || D->isInvalidDecl()) return; 12630 12631 VarDecl *VD = dyn_cast<VarDecl>(D); 12632 if (!VD) return; 12633 12634 // Bindings are not usable if we can't make sense of the initializer. 12635 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12636 for (auto *BD : DD->bindings()) 12637 BD->setInvalidDecl(); 12638 12639 // Auto types are meaningless if we can't make sense of the initializer. 12640 if (VD->getType()->isUndeducedType()) { 12641 D->setInvalidDecl(); 12642 return; 12643 } 12644 12645 QualType Ty = VD->getType(); 12646 if (Ty->isDependentType()) return; 12647 12648 // Require a complete type. 12649 if (RequireCompleteType(VD->getLocation(), 12650 Context.getBaseElementType(Ty), 12651 diag::err_typecheck_decl_incomplete_type)) { 12652 VD->setInvalidDecl(); 12653 return; 12654 } 12655 12656 // Require a non-abstract type. 12657 if (RequireNonAbstractType(VD->getLocation(), Ty, 12658 diag::err_abstract_type_in_decl, 12659 AbstractVariableType)) { 12660 VD->setInvalidDecl(); 12661 return; 12662 } 12663 12664 // Don't bother complaining about constructors or destructors, 12665 // though. 12666 } 12667 12668 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12669 // If there is no declaration, there was an error parsing it. Just ignore it. 12670 if (!RealDecl) 12671 return; 12672 12673 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12674 QualType Type = Var->getType(); 12675 12676 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12677 if (isa<DecompositionDecl>(RealDecl)) { 12678 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12679 Var->setInvalidDecl(); 12680 return; 12681 } 12682 12683 if (Type->isUndeducedType() && 12684 DeduceVariableDeclarationType(Var, false, nullptr)) 12685 return; 12686 12687 // C++11 [class.static.data]p3: A static data member can be declared with 12688 // the constexpr specifier; if so, its declaration shall specify 12689 // a brace-or-equal-initializer. 12690 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12691 // the definition of a variable [...] or the declaration of a static data 12692 // member. 12693 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12694 !Var->isThisDeclarationADemotedDefinition()) { 12695 if (Var->isStaticDataMember()) { 12696 // C++1z removes the relevant rule; the in-class declaration is always 12697 // a definition there. 12698 if (!getLangOpts().CPlusPlus17 && 12699 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12700 Diag(Var->getLocation(), 12701 diag::err_constexpr_static_mem_var_requires_init) 12702 << Var; 12703 Var->setInvalidDecl(); 12704 return; 12705 } 12706 } else { 12707 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12708 Var->setInvalidDecl(); 12709 return; 12710 } 12711 } 12712 12713 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12714 // be initialized. 12715 if (!Var->isInvalidDecl() && 12716 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12717 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12718 bool HasConstExprDefaultConstructor = false; 12719 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12720 for (auto *Ctor : RD->ctors()) { 12721 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12722 Ctor->getMethodQualifiers().getAddressSpace() == 12723 LangAS::opencl_constant) { 12724 HasConstExprDefaultConstructor = true; 12725 } 12726 } 12727 } 12728 if (!HasConstExprDefaultConstructor) { 12729 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12730 Var->setInvalidDecl(); 12731 return; 12732 } 12733 } 12734 12735 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12736 if (Var->getStorageClass() == SC_Extern) { 12737 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12738 << Var; 12739 Var->setInvalidDecl(); 12740 return; 12741 } 12742 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12743 diag::err_typecheck_decl_incomplete_type)) { 12744 Var->setInvalidDecl(); 12745 return; 12746 } 12747 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12748 if (!RD->hasTrivialDefaultConstructor()) { 12749 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12750 Var->setInvalidDecl(); 12751 return; 12752 } 12753 } 12754 // The declaration is unitialized, no need for further checks. 12755 return; 12756 } 12757 12758 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12759 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12760 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12761 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12762 NTCUC_DefaultInitializedObject, NTCUK_Init); 12763 12764 12765 switch (DefKind) { 12766 case VarDecl::Definition: 12767 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12768 break; 12769 12770 // We have an out-of-line definition of a static data member 12771 // that has an in-class initializer, so we type-check this like 12772 // a declaration. 12773 // 12774 LLVM_FALLTHROUGH; 12775 12776 case VarDecl::DeclarationOnly: 12777 // It's only a declaration. 12778 12779 // Block scope. C99 6.7p7: If an identifier for an object is 12780 // declared with no linkage (C99 6.2.2p6), the type for the 12781 // object shall be complete. 12782 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12783 !Var->hasLinkage() && !Var->isInvalidDecl() && 12784 RequireCompleteType(Var->getLocation(), Type, 12785 diag::err_typecheck_decl_incomplete_type)) 12786 Var->setInvalidDecl(); 12787 12788 // Make sure that the type is not abstract. 12789 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12790 RequireNonAbstractType(Var->getLocation(), Type, 12791 diag::err_abstract_type_in_decl, 12792 AbstractVariableType)) 12793 Var->setInvalidDecl(); 12794 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12795 Var->getStorageClass() == SC_PrivateExtern) { 12796 Diag(Var->getLocation(), diag::warn_private_extern); 12797 Diag(Var->getLocation(), diag::note_private_extern); 12798 } 12799 12800 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12801 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12802 ExternalDeclarations.push_back(Var); 12803 12804 return; 12805 12806 case VarDecl::TentativeDefinition: 12807 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12808 // object that has file scope without an initializer, and without a 12809 // storage-class specifier or with the storage-class specifier "static", 12810 // constitutes a tentative definition. Note: A tentative definition with 12811 // external linkage is valid (C99 6.2.2p5). 12812 if (!Var->isInvalidDecl()) { 12813 if (const IncompleteArrayType *ArrayT 12814 = Context.getAsIncompleteArrayType(Type)) { 12815 if (RequireCompleteSizedType( 12816 Var->getLocation(), ArrayT->getElementType(), 12817 diag::err_array_incomplete_or_sizeless_type)) 12818 Var->setInvalidDecl(); 12819 } else if (Var->getStorageClass() == SC_Static) { 12820 // C99 6.9.2p3: If the declaration of an identifier for an object is 12821 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12822 // declared type shall not be an incomplete type. 12823 // NOTE: code such as the following 12824 // static struct s; 12825 // struct s { int a; }; 12826 // is accepted by gcc. Hence here we issue a warning instead of 12827 // an error and we do not invalidate the static declaration. 12828 // NOTE: to avoid multiple warnings, only check the first declaration. 12829 if (Var->isFirstDecl()) 12830 RequireCompleteType(Var->getLocation(), Type, 12831 diag::ext_typecheck_decl_incomplete_type); 12832 } 12833 } 12834 12835 // Record the tentative definition; we're done. 12836 if (!Var->isInvalidDecl()) 12837 TentativeDefinitions.push_back(Var); 12838 return; 12839 } 12840 12841 // Provide a specific diagnostic for uninitialized variable 12842 // definitions with incomplete array type. 12843 if (Type->isIncompleteArrayType()) { 12844 Diag(Var->getLocation(), 12845 diag::err_typecheck_incomplete_array_needs_initializer); 12846 Var->setInvalidDecl(); 12847 return; 12848 } 12849 12850 // Provide a specific diagnostic for uninitialized variable 12851 // definitions with reference type. 12852 if (Type->isReferenceType()) { 12853 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12854 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12855 Var->setInvalidDecl(); 12856 return; 12857 } 12858 12859 // Do not attempt to type-check the default initializer for a 12860 // variable with dependent type. 12861 if (Type->isDependentType()) 12862 return; 12863 12864 if (Var->isInvalidDecl()) 12865 return; 12866 12867 if (!Var->hasAttr<AliasAttr>()) { 12868 if (RequireCompleteType(Var->getLocation(), 12869 Context.getBaseElementType(Type), 12870 diag::err_typecheck_decl_incomplete_type)) { 12871 Var->setInvalidDecl(); 12872 return; 12873 } 12874 } else { 12875 return; 12876 } 12877 12878 // The variable can not have an abstract class type. 12879 if (RequireNonAbstractType(Var->getLocation(), Type, 12880 diag::err_abstract_type_in_decl, 12881 AbstractVariableType)) { 12882 Var->setInvalidDecl(); 12883 return; 12884 } 12885 12886 // Check for jumps past the implicit initializer. C++0x 12887 // clarifies that this applies to a "variable with automatic 12888 // storage duration", not a "local variable". 12889 // C++11 [stmt.dcl]p3 12890 // A program that jumps from a point where a variable with automatic 12891 // storage duration is not in scope to a point where it is in scope is 12892 // ill-formed unless the variable has scalar type, class type with a 12893 // trivial default constructor and a trivial destructor, a cv-qualified 12894 // version of one of these types, or an array of one of the preceding 12895 // types and is declared without an initializer. 12896 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12897 if (const RecordType *Record 12898 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12899 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12900 // Mark the function (if we're in one) for further checking even if the 12901 // looser rules of C++11 do not require such checks, so that we can 12902 // diagnose incompatibilities with C++98. 12903 if (!CXXRecord->isPOD()) 12904 setFunctionHasBranchProtectedScope(); 12905 } 12906 } 12907 // In OpenCL, we can't initialize objects in the __local address space, 12908 // even implicitly, so don't synthesize an implicit initializer. 12909 if (getLangOpts().OpenCL && 12910 Var->getType().getAddressSpace() == LangAS::opencl_local) 12911 return; 12912 // C++03 [dcl.init]p9: 12913 // If no initializer is specified for an object, and the 12914 // object is of (possibly cv-qualified) non-POD class type (or 12915 // array thereof), the object shall be default-initialized; if 12916 // the object is of const-qualified type, the underlying class 12917 // type shall have a user-declared default 12918 // constructor. Otherwise, if no initializer is specified for 12919 // a non- static object, the object and its subobjects, if 12920 // any, have an indeterminate initial value); if the object 12921 // or any of its subobjects are of const-qualified type, the 12922 // program is ill-formed. 12923 // C++0x [dcl.init]p11: 12924 // If no initializer is specified for an object, the object is 12925 // default-initialized; [...]. 12926 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12927 InitializationKind Kind 12928 = InitializationKind::CreateDefault(Var->getLocation()); 12929 12930 InitializationSequence InitSeq(*this, Entity, Kind, None); 12931 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12932 12933 if (Init.get()) { 12934 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12935 // This is important for template substitution. 12936 Var->setInitStyle(VarDecl::CallInit); 12937 } else if (Init.isInvalid()) { 12938 // If default-init fails, attach a recovery-expr initializer to track 12939 // that initialization was attempted and failed. 12940 auto RecoveryExpr = 12941 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12942 if (RecoveryExpr.get()) 12943 Var->setInit(RecoveryExpr.get()); 12944 } 12945 12946 CheckCompleteVariableDeclaration(Var); 12947 } 12948 } 12949 12950 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12951 // If there is no declaration, there was an error parsing it. Ignore it. 12952 if (!D) 12953 return; 12954 12955 VarDecl *VD = dyn_cast<VarDecl>(D); 12956 if (!VD) { 12957 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12958 D->setInvalidDecl(); 12959 return; 12960 } 12961 12962 VD->setCXXForRangeDecl(true); 12963 12964 // for-range-declaration cannot be given a storage class specifier. 12965 int Error = -1; 12966 switch (VD->getStorageClass()) { 12967 case SC_None: 12968 break; 12969 case SC_Extern: 12970 Error = 0; 12971 break; 12972 case SC_Static: 12973 Error = 1; 12974 break; 12975 case SC_PrivateExtern: 12976 Error = 2; 12977 break; 12978 case SC_Auto: 12979 Error = 3; 12980 break; 12981 case SC_Register: 12982 Error = 4; 12983 break; 12984 } 12985 12986 // for-range-declaration cannot be given a storage class specifier con't. 12987 switch (VD->getTSCSpec()) { 12988 case TSCS_thread_local: 12989 Error = 6; 12990 break; 12991 case TSCS___thread: 12992 case TSCS__Thread_local: 12993 case TSCS_unspecified: 12994 break; 12995 } 12996 12997 if (Error != -1) { 12998 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12999 << VD << Error; 13000 D->setInvalidDecl(); 13001 } 13002 } 13003 13004 StmtResult 13005 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13006 IdentifierInfo *Ident, 13007 ParsedAttributes &Attrs, 13008 SourceLocation AttrEnd) { 13009 // C++1y [stmt.iter]p1: 13010 // A range-based for statement of the form 13011 // for ( for-range-identifier : for-range-initializer ) statement 13012 // is equivalent to 13013 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13014 DeclSpec DS(Attrs.getPool().getFactory()); 13015 13016 const char *PrevSpec; 13017 unsigned DiagID; 13018 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13019 getPrintingPolicy()); 13020 13021 Declarator D(DS, DeclaratorContext::ForInit); 13022 D.SetIdentifier(Ident, IdentLoc); 13023 D.takeAttributes(Attrs, AttrEnd); 13024 13025 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13026 IdentLoc); 13027 Decl *Var = ActOnDeclarator(S, D); 13028 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13029 FinalizeDeclaration(Var); 13030 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13031 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13032 } 13033 13034 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13035 if (var->isInvalidDecl()) return; 13036 13037 MaybeAddCUDAConstantAttr(var); 13038 13039 if (getLangOpts().OpenCL) { 13040 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13041 // initialiser 13042 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13043 !var->hasInit()) { 13044 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13045 << 1 /*Init*/; 13046 var->setInvalidDecl(); 13047 return; 13048 } 13049 } 13050 13051 // In Objective-C, don't allow jumps past the implicit initialization of a 13052 // local retaining variable. 13053 if (getLangOpts().ObjC && 13054 var->hasLocalStorage()) { 13055 switch (var->getType().getObjCLifetime()) { 13056 case Qualifiers::OCL_None: 13057 case Qualifiers::OCL_ExplicitNone: 13058 case Qualifiers::OCL_Autoreleasing: 13059 break; 13060 13061 case Qualifiers::OCL_Weak: 13062 case Qualifiers::OCL_Strong: 13063 setFunctionHasBranchProtectedScope(); 13064 break; 13065 } 13066 } 13067 13068 if (var->hasLocalStorage() && 13069 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13070 setFunctionHasBranchProtectedScope(); 13071 13072 // Warn about externally-visible variables being defined without a 13073 // prior declaration. We only want to do this for global 13074 // declarations, but we also specifically need to avoid doing it for 13075 // class members because the linkage of an anonymous class can 13076 // change if it's later given a typedef name. 13077 if (var->isThisDeclarationADefinition() && 13078 var->getDeclContext()->getRedeclContext()->isFileContext() && 13079 var->isExternallyVisible() && var->hasLinkage() && 13080 !var->isInline() && !var->getDescribedVarTemplate() && 13081 !isa<VarTemplatePartialSpecializationDecl>(var) && 13082 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13083 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13084 var->getLocation())) { 13085 // Find a previous declaration that's not a definition. 13086 VarDecl *prev = var->getPreviousDecl(); 13087 while (prev && prev->isThisDeclarationADefinition()) 13088 prev = prev->getPreviousDecl(); 13089 13090 if (!prev) { 13091 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13092 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13093 << /* variable */ 0; 13094 } 13095 } 13096 13097 // Cache the result of checking for constant initialization. 13098 Optional<bool> CacheHasConstInit; 13099 const Expr *CacheCulprit = nullptr; 13100 auto checkConstInit = [&]() mutable { 13101 if (!CacheHasConstInit) 13102 CacheHasConstInit = var->getInit()->isConstantInitializer( 13103 Context, var->getType()->isReferenceType(), &CacheCulprit); 13104 return *CacheHasConstInit; 13105 }; 13106 13107 if (var->getTLSKind() == VarDecl::TLS_Static) { 13108 if (var->getType().isDestructedType()) { 13109 // GNU C++98 edits for __thread, [basic.start.term]p3: 13110 // The type of an object with thread storage duration shall not 13111 // have a non-trivial destructor. 13112 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13113 if (getLangOpts().CPlusPlus11) 13114 Diag(var->getLocation(), diag::note_use_thread_local); 13115 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13116 if (!checkConstInit()) { 13117 // GNU C++98 edits for __thread, [basic.start.init]p4: 13118 // An object of thread storage duration shall not require dynamic 13119 // initialization. 13120 // FIXME: Need strict checking here. 13121 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13122 << CacheCulprit->getSourceRange(); 13123 if (getLangOpts().CPlusPlus11) 13124 Diag(var->getLocation(), diag::note_use_thread_local); 13125 } 13126 } 13127 } 13128 13129 13130 if (!var->getType()->isStructureType() && var->hasInit() && 13131 isa<InitListExpr>(var->getInit())) { 13132 const auto *ILE = cast<InitListExpr>(var->getInit()); 13133 unsigned NumInits = ILE->getNumInits(); 13134 if (NumInits > 2) 13135 for (unsigned I = 0; I < NumInits; ++I) { 13136 const auto *Init = ILE->getInit(I); 13137 if (!Init) 13138 break; 13139 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13140 if (!SL) 13141 break; 13142 13143 unsigned NumConcat = SL->getNumConcatenated(); 13144 // Diagnose missing comma in string array initialization. 13145 // Do not warn when all the elements in the initializer are concatenated 13146 // together. Do not warn for macros too. 13147 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13148 bool OnlyOneMissingComma = true; 13149 for (unsigned J = I + 1; J < NumInits; ++J) { 13150 const auto *Init = ILE->getInit(J); 13151 if (!Init) 13152 break; 13153 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13154 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13155 OnlyOneMissingComma = false; 13156 break; 13157 } 13158 } 13159 13160 if (OnlyOneMissingComma) { 13161 SmallVector<FixItHint, 1> Hints; 13162 for (unsigned i = 0; i < NumConcat - 1; ++i) 13163 Hints.push_back(FixItHint::CreateInsertion( 13164 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13165 13166 Diag(SL->getStrTokenLoc(1), 13167 diag::warn_concatenated_literal_array_init) 13168 << Hints; 13169 Diag(SL->getBeginLoc(), 13170 diag::note_concatenated_string_literal_silence); 13171 } 13172 // In any case, stop now. 13173 break; 13174 } 13175 } 13176 } 13177 13178 13179 QualType type = var->getType(); 13180 13181 if (var->hasAttr<BlocksAttr>()) 13182 getCurFunction()->addByrefBlockVar(var); 13183 13184 Expr *Init = var->getInit(); 13185 bool GlobalStorage = var->hasGlobalStorage(); 13186 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13187 QualType baseType = Context.getBaseElementType(type); 13188 bool HasConstInit = true; 13189 13190 // Check whether the initializer is sufficiently constant. 13191 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13192 !Init->isValueDependent() && 13193 (GlobalStorage || var->isConstexpr() || 13194 var->mightBeUsableInConstantExpressions(Context))) { 13195 // If this variable might have a constant initializer or might be usable in 13196 // constant expressions, check whether or not it actually is now. We can't 13197 // do this lazily, because the result might depend on things that change 13198 // later, such as which constexpr functions happen to be defined. 13199 SmallVector<PartialDiagnosticAt, 8> Notes; 13200 if (!getLangOpts().CPlusPlus11) { 13201 // Prior to C++11, in contexts where a constant initializer is required, 13202 // the set of valid constant initializers is described by syntactic rules 13203 // in [expr.const]p2-6. 13204 // FIXME: Stricter checking for these rules would be useful for constinit / 13205 // -Wglobal-constructors. 13206 HasConstInit = checkConstInit(); 13207 13208 // Compute and cache the constant value, and remember that we have a 13209 // constant initializer. 13210 if (HasConstInit) { 13211 (void)var->checkForConstantInitialization(Notes); 13212 Notes.clear(); 13213 } else if (CacheCulprit) { 13214 Notes.emplace_back(CacheCulprit->getExprLoc(), 13215 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13216 Notes.back().second << CacheCulprit->getSourceRange(); 13217 } 13218 } else { 13219 // Evaluate the initializer to see if it's a constant initializer. 13220 HasConstInit = var->checkForConstantInitialization(Notes); 13221 } 13222 13223 if (HasConstInit) { 13224 // FIXME: Consider replacing the initializer with a ConstantExpr. 13225 } else if (var->isConstexpr()) { 13226 SourceLocation DiagLoc = var->getLocation(); 13227 // If the note doesn't add any useful information other than a source 13228 // location, fold it into the primary diagnostic. 13229 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13230 diag::note_invalid_subexpr_in_const_expr) { 13231 DiagLoc = Notes[0].first; 13232 Notes.clear(); 13233 } 13234 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13235 << var << Init->getSourceRange(); 13236 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13237 Diag(Notes[I].first, Notes[I].second); 13238 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13239 auto *Attr = var->getAttr<ConstInitAttr>(); 13240 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13241 << Init->getSourceRange(); 13242 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13243 << Attr->getRange() << Attr->isConstinit(); 13244 for (auto &it : Notes) 13245 Diag(it.first, it.second); 13246 } else if (IsGlobal && 13247 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13248 var->getLocation())) { 13249 // Warn about globals which don't have a constant initializer. Don't 13250 // warn about globals with a non-trivial destructor because we already 13251 // warned about them. 13252 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13253 if (!(RD && !RD->hasTrivialDestructor())) { 13254 // checkConstInit() here permits trivial default initialization even in 13255 // C++11 onwards, where such an initializer is not a constant initializer 13256 // but nonetheless doesn't require a global constructor. 13257 if (!checkConstInit()) 13258 Diag(var->getLocation(), diag::warn_global_constructor) 13259 << Init->getSourceRange(); 13260 } 13261 } 13262 } 13263 13264 // Apply section attributes and pragmas to global variables. 13265 if (GlobalStorage && var->isThisDeclarationADefinition() && 13266 !inTemplateInstantiation()) { 13267 PragmaStack<StringLiteral *> *Stack = nullptr; 13268 int SectionFlags = ASTContext::PSF_Read; 13269 if (var->getType().isConstQualified()) { 13270 if (HasConstInit) 13271 Stack = &ConstSegStack; 13272 else { 13273 Stack = &BSSSegStack; 13274 SectionFlags |= ASTContext::PSF_Write; 13275 } 13276 } else if (var->hasInit() && HasConstInit) { 13277 Stack = &DataSegStack; 13278 SectionFlags |= ASTContext::PSF_Write; 13279 } else { 13280 Stack = &BSSSegStack; 13281 SectionFlags |= ASTContext::PSF_Write; 13282 } 13283 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13284 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13285 SectionFlags |= ASTContext::PSF_Implicit; 13286 UnifySection(SA->getName(), SectionFlags, var); 13287 } else if (Stack->CurrentValue) { 13288 SectionFlags |= ASTContext::PSF_Implicit; 13289 auto SectionName = Stack->CurrentValue->getString(); 13290 var->addAttr(SectionAttr::CreateImplicit( 13291 Context, SectionName, Stack->CurrentPragmaLocation, 13292 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13293 if (UnifySection(SectionName, SectionFlags, var)) 13294 var->dropAttr<SectionAttr>(); 13295 } 13296 13297 // Apply the init_seg attribute if this has an initializer. If the 13298 // initializer turns out to not be dynamic, we'll end up ignoring this 13299 // attribute. 13300 if (CurInitSeg && var->getInit()) 13301 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13302 CurInitSegLoc, 13303 AttributeCommonInfo::AS_Pragma)); 13304 } 13305 13306 // All the following checks are C++ only. 13307 if (!getLangOpts().CPlusPlus) { 13308 // If this variable must be emitted, add it as an initializer for the 13309 // current module. 13310 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13311 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13312 return; 13313 } 13314 13315 // Require the destructor. 13316 if (!type->isDependentType()) 13317 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13318 FinalizeVarWithDestructor(var, recordType); 13319 13320 // If this variable must be emitted, add it as an initializer for the current 13321 // module. 13322 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13323 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13324 13325 // Build the bindings if this is a structured binding declaration. 13326 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13327 CheckCompleteDecompositionDeclaration(DD); 13328 } 13329 13330 /// Check if VD needs to be dllexport/dllimport due to being in a 13331 /// dllexport/import function. 13332 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13333 assert(VD->isStaticLocal()); 13334 13335 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13336 13337 // Find outermost function when VD is in lambda function. 13338 while (FD && !getDLLAttr(FD) && 13339 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13340 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13341 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13342 } 13343 13344 if (!FD) 13345 return; 13346 13347 // Static locals inherit dll attributes from their function. 13348 if (Attr *A = getDLLAttr(FD)) { 13349 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13350 NewAttr->setInherited(true); 13351 VD->addAttr(NewAttr); 13352 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13353 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13354 NewAttr->setInherited(true); 13355 VD->addAttr(NewAttr); 13356 13357 // Export this function to enforce exporting this static variable even 13358 // if it is not used in this compilation unit. 13359 if (!FD->hasAttr<DLLExportAttr>()) 13360 FD->addAttr(NewAttr); 13361 13362 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13363 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13364 NewAttr->setInherited(true); 13365 VD->addAttr(NewAttr); 13366 } 13367 } 13368 13369 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13370 /// any semantic actions necessary after any initializer has been attached. 13371 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13372 // Note that we are no longer parsing the initializer for this declaration. 13373 ParsingInitForAutoVars.erase(ThisDecl); 13374 13375 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13376 if (!VD) 13377 return; 13378 13379 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13380 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13381 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13382 if (PragmaClangBSSSection.Valid) 13383 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13384 Context, PragmaClangBSSSection.SectionName, 13385 PragmaClangBSSSection.PragmaLocation, 13386 AttributeCommonInfo::AS_Pragma)); 13387 if (PragmaClangDataSection.Valid) 13388 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13389 Context, PragmaClangDataSection.SectionName, 13390 PragmaClangDataSection.PragmaLocation, 13391 AttributeCommonInfo::AS_Pragma)); 13392 if (PragmaClangRodataSection.Valid) 13393 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13394 Context, PragmaClangRodataSection.SectionName, 13395 PragmaClangRodataSection.PragmaLocation, 13396 AttributeCommonInfo::AS_Pragma)); 13397 if (PragmaClangRelroSection.Valid) 13398 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13399 Context, PragmaClangRelroSection.SectionName, 13400 PragmaClangRelroSection.PragmaLocation, 13401 AttributeCommonInfo::AS_Pragma)); 13402 } 13403 13404 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13405 for (auto *BD : DD->bindings()) { 13406 FinalizeDeclaration(BD); 13407 } 13408 } 13409 13410 checkAttributesAfterMerging(*this, *VD); 13411 13412 // Perform TLS alignment check here after attributes attached to the variable 13413 // which may affect the alignment have been processed. Only perform the check 13414 // if the target has a maximum TLS alignment (zero means no constraints). 13415 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13416 // Protect the check so that it's not performed on dependent types and 13417 // dependent alignments (we can't determine the alignment in that case). 13418 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13419 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13420 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13421 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13422 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13423 << (unsigned)MaxAlignChars.getQuantity(); 13424 } 13425 } 13426 } 13427 13428 if (VD->isStaticLocal()) 13429 CheckStaticLocalForDllExport(VD); 13430 13431 // Perform check for initializers of device-side global variables. 13432 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13433 // 7.5). We must also apply the same checks to all __shared__ 13434 // variables whether they are local or not. CUDA also allows 13435 // constant initializers for __constant__ and __device__ variables. 13436 if (getLangOpts().CUDA) 13437 checkAllowedCUDAInitializer(VD); 13438 13439 // Grab the dllimport or dllexport attribute off of the VarDecl. 13440 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13441 13442 // Imported static data members cannot be defined out-of-line. 13443 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13444 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13445 VD->isThisDeclarationADefinition()) { 13446 // We allow definitions of dllimport class template static data members 13447 // with a warning. 13448 CXXRecordDecl *Context = 13449 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13450 bool IsClassTemplateMember = 13451 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13452 Context->getDescribedClassTemplate(); 13453 13454 Diag(VD->getLocation(), 13455 IsClassTemplateMember 13456 ? diag::warn_attribute_dllimport_static_field_definition 13457 : diag::err_attribute_dllimport_static_field_definition); 13458 Diag(IA->getLocation(), diag::note_attribute); 13459 if (!IsClassTemplateMember) 13460 VD->setInvalidDecl(); 13461 } 13462 } 13463 13464 // dllimport/dllexport variables cannot be thread local, their TLS index 13465 // isn't exported with the variable. 13466 if (DLLAttr && VD->getTLSKind()) { 13467 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13468 if (F && getDLLAttr(F)) { 13469 assert(VD->isStaticLocal()); 13470 // But if this is a static local in a dlimport/dllexport function, the 13471 // function will never be inlined, which means the var would never be 13472 // imported, so having it marked import/export is safe. 13473 } else { 13474 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13475 << DLLAttr; 13476 VD->setInvalidDecl(); 13477 } 13478 } 13479 13480 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13481 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13482 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13483 << Attr; 13484 VD->dropAttr<UsedAttr>(); 13485 } 13486 } 13487 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13488 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13489 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13490 << Attr; 13491 VD->dropAttr<RetainAttr>(); 13492 } 13493 } 13494 13495 const DeclContext *DC = VD->getDeclContext(); 13496 // If there's a #pragma GCC visibility in scope, and this isn't a class 13497 // member, set the visibility of this variable. 13498 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13499 AddPushedVisibilityAttribute(VD); 13500 13501 // FIXME: Warn on unused var template partial specializations. 13502 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13503 MarkUnusedFileScopedDecl(VD); 13504 13505 // Now we have parsed the initializer and can update the table of magic 13506 // tag values. 13507 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13508 !VD->getType()->isIntegralOrEnumerationType()) 13509 return; 13510 13511 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13512 const Expr *MagicValueExpr = VD->getInit(); 13513 if (!MagicValueExpr) { 13514 continue; 13515 } 13516 Optional<llvm::APSInt> MagicValueInt; 13517 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13518 Diag(I->getRange().getBegin(), 13519 diag::err_type_tag_for_datatype_not_ice) 13520 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13521 continue; 13522 } 13523 if (MagicValueInt->getActiveBits() > 64) { 13524 Diag(I->getRange().getBegin(), 13525 diag::err_type_tag_for_datatype_too_large) 13526 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13527 continue; 13528 } 13529 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13530 RegisterTypeTagForDatatype(I->getArgumentKind(), 13531 MagicValue, 13532 I->getMatchingCType(), 13533 I->getLayoutCompatible(), 13534 I->getMustBeNull()); 13535 } 13536 } 13537 13538 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13539 auto *VD = dyn_cast<VarDecl>(DD); 13540 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13541 } 13542 13543 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13544 ArrayRef<Decl *> Group) { 13545 SmallVector<Decl*, 8> Decls; 13546 13547 if (DS.isTypeSpecOwned()) 13548 Decls.push_back(DS.getRepAsDecl()); 13549 13550 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13551 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13552 bool DiagnosedMultipleDecomps = false; 13553 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13554 bool DiagnosedNonDeducedAuto = false; 13555 13556 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13557 if (Decl *D = Group[i]) { 13558 // For declarators, there are some additional syntactic-ish checks we need 13559 // to perform. 13560 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13561 if (!FirstDeclaratorInGroup) 13562 FirstDeclaratorInGroup = DD; 13563 if (!FirstDecompDeclaratorInGroup) 13564 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13565 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13566 !hasDeducedAuto(DD)) 13567 FirstNonDeducedAutoInGroup = DD; 13568 13569 if (FirstDeclaratorInGroup != DD) { 13570 // A decomposition declaration cannot be combined with any other 13571 // declaration in the same group. 13572 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13573 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13574 diag::err_decomp_decl_not_alone) 13575 << FirstDeclaratorInGroup->getSourceRange() 13576 << DD->getSourceRange(); 13577 DiagnosedMultipleDecomps = true; 13578 } 13579 13580 // A declarator that uses 'auto' in any way other than to declare a 13581 // variable with a deduced type cannot be combined with any other 13582 // declarator in the same group. 13583 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13584 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13585 diag::err_auto_non_deduced_not_alone) 13586 << FirstNonDeducedAutoInGroup->getType() 13587 ->hasAutoForTrailingReturnType() 13588 << FirstDeclaratorInGroup->getSourceRange() 13589 << DD->getSourceRange(); 13590 DiagnosedNonDeducedAuto = true; 13591 } 13592 } 13593 } 13594 13595 Decls.push_back(D); 13596 } 13597 } 13598 13599 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13600 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13601 handleTagNumbering(Tag, S); 13602 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13603 getLangOpts().CPlusPlus) 13604 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13605 } 13606 } 13607 13608 return BuildDeclaratorGroup(Decls); 13609 } 13610 13611 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13612 /// group, performing any necessary semantic checking. 13613 Sema::DeclGroupPtrTy 13614 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13615 // C++14 [dcl.spec.auto]p7: (DR1347) 13616 // If the type that replaces the placeholder type is not the same in each 13617 // deduction, the program is ill-formed. 13618 if (Group.size() > 1) { 13619 QualType Deduced; 13620 VarDecl *DeducedDecl = nullptr; 13621 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13622 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13623 if (!D || D->isInvalidDecl()) 13624 break; 13625 DeducedType *DT = D->getType()->getContainedDeducedType(); 13626 if (!DT || DT->getDeducedType().isNull()) 13627 continue; 13628 if (Deduced.isNull()) { 13629 Deduced = DT->getDeducedType(); 13630 DeducedDecl = D; 13631 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13632 auto *AT = dyn_cast<AutoType>(DT); 13633 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13634 diag::err_auto_different_deductions) 13635 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13636 << DeducedDecl->getDeclName() << DT->getDeducedType() 13637 << D->getDeclName(); 13638 if (DeducedDecl->hasInit()) 13639 Dia << DeducedDecl->getInit()->getSourceRange(); 13640 if (D->getInit()) 13641 Dia << D->getInit()->getSourceRange(); 13642 D->setInvalidDecl(); 13643 break; 13644 } 13645 } 13646 } 13647 13648 ActOnDocumentableDecls(Group); 13649 13650 return DeclGroupPtrTy::make( 13651 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13652 } 13653 13654 void Sema::ActOnDocumentableDecl(Decl *D) { 13655 ActOnDocumentableDecls(D); 13656 } 13657 13658 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13659 // Don't parse the comment if Doxygen diagnostics are ignored. 13660 if (Group.empty() || !Group[0]) 13661 return; 13662 13663 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13664 Group[0]->getLocation()) && 13665 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13666 Group[0]->getLocation())) 13667 return; 13668 13669 if (Group.size() >= 2) { 13670 // This is a decl group. Normally it will contain only declarations 13671 // produced from declarator list. But in case we have any definitions or 13672 // additional declaration references: 13673 // 'typedef struct S {} S;' 13674 // 'typedef struct S *S;' 13675 // 'struct S *pS;' 13676 // FinalizeDeclaratorGroup adds these as separate declarations. 13677 Decl *MaybeTagDecl = Group[0]; 13678 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13679 Group = Group.slice(1); 13680 } 13681 } 13682 13683 // FIMXE: We assume every Decl in the group is in the same file. 13684 // This is false when preprocessor constructs the group from decls in 13685 // different files (e. g. macros or #include). 13686 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13687 } 13688 13689 /// Common checks for a parameter-declaration that should apply to both function 13690 /// parameters and non-type template parameters. 13691 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13692 // Check that there are no default arguments inside the type of this 13693 // parameter. 13694 if (getLangOpts().CPlusPlus) 13695 CheckExtraCXXDefaultArguments(D); 13696 13697 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13698 if (D.getCXXScopeSpec().isSet()) { 13699 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13700 << D.getCXXScopeSpec().getRange(); 13701 } 13702 13703 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13704 // simple identifier except [...irrelevant cases...]. 13705 switch (D.getName().getKind()) { 13706 case UnqualifiedIdKind::IK_Identifier: 13707 break; 13708 13709 case UnqualifiedIdKind::IK_OperatorFunctionId: 13710 case UnqualifiedIdKind::IK_ConversionFunctionId: 13711 case UnqualifiedIdKind::IK_LiteralOperatorId: 13712 case UnqualifiedIdKind::IK_ConstructorName: 13713 case UnqualifiedIdKind::IK_DestructorName: 13714 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13715 case UnqualifiedIdKind::IK_DeductionGuideName: 13716 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13717 << GetNameForDeclarator(D).getName(); 13718 break; 13719 13720 case UnqualifiedIdKind::IK_TemplateId: 13721 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13722 // GetNameForDeclarator would not produce a useful name in this case. 13723 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13724 break; 13725 } 13726 } 13727 13728 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13729 /// to introduce parameters into function prototype scope. 13730 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13731 const DeclSpec &DS = D.getDeclSpec(); 13732 13733 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13734 13735 // C++03 [dcl.stc]p2 also permits 'auto'. 13736 StorageClass SC = SC_None; 13737 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13738 SC = SC_Register; 13739 // In C++11, the 'register' storage class specifier is deprecated. 13740 // In C++17, it is not allowed, but we tolerate it as an extension. 13741 if (getLangOpts().CPlusPlus11) { 13742 Diag(DS.getStorageClassSpecLoc(), 13743 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13744 : diag::warn_deprecated_register) 13745 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13746 } 13747 } else if (getLangOpts().CPlusPlus && 13748 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13749 SC = SC_Auto; 13750 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13751 Diag(DS.getStorageClassSpecLoc(), 13752 diag::err_invalid_storage_class_in_func_decl); 13753 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13754 } 13755 13756 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13757 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13758 << DeclSpec::getSpecifierName(TSCS); 13759 if (DS.isInlineSpecified()) 13760 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13761 << getLangOpts().CPlusPlus17; 13762 if (DS.hasConstexprSpecifier()) 13763 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13764 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13765 13766 DiagnoseFunctionSpecifiers(DS); 13767 13768 CheckFunctionOrTemplateParamDeclarator(S, D); 13769 13770 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13771 QualType parmDeclType = TInfo->getType(); 13772 13773 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13774 IdentifierInfo *II = D.getIdentifier(); 13775 if (II) { 13776 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13777 ForVisibleRedeclaration); 13778 LookupName(R, S); 13779 if (R.isSingleResult()) { 13780 NamedDecl *PrevDecl = R.getFoundDecl(); 13781 if (PrevDecl->isTemplateParameter()) { 13782 // Maybe we will complain about the shadowed template parameter. 13783 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13784 // Just pretend that we didn't see the previous declaration. 13785 PrevDecl = nullptr; 13786 } else if (S->isDeclScope(PrevDecl)) { 13787 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13788 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13789 13790 // Recover by removing the name 13791 II = nullptr; 13792 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13793 D.setInvalidType(true); 13794 } 13795 } 13796 } 13797 13798 // Temporarily put parameter variables in the translation unit, not 13799 // the enclosing context. This prevents them from accidentally 13800 // looking like class members in C++. 13801 ParmVarDecl *New = 13802 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13803 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13804 13805 if (D.isInvalidType()) 13806 New->setInvalidDecl(); 13807 13808 assert(S->isFunctionPrototypeScope()); 13809 assert(S->getFunctionPrototypeDepth() >= 1); 13810 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13811 S->getNextFunctionPrototypeIndex()); 13812 13813 // Add the parameter declaration into this scope. 13814 S->AddDecl(New); 13815 if (II) 13816 IdResolver.AddDecl(New); 13817 13818 ProcessDeclAttributes(S, New, D); 13819 13820 if (D.getDeclSpec().isModulePrivateSpecified()) 13821 Diag(New->getLocation(), diag::err_module_private_local) 13822 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13823 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13824 13825 if (New->hasAttr<BlocksAttr>()) { 13826 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13827 } 13828 13829 if (getLangOpts().OpenCL) 13830 deduceOpenCLAddressSpace(New); 13831 13832 return New; 13833 } 13834 13835 /// Synthesizes a variable for a parameter arising from a 13836 /// typedef. 13837 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13838 SourceLocation Loc, 13839 QualType T) { 13840 /* FIXME: setting StartLoc == Loc. 13841 Would it be worth to modify callers so as to provide proper source 13842 location for the unnamed parameters, embedding the parameter's type? */ 13843 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13844 T, Context.getTrivialTypeSourceInfo(T, Loc), 13845 SC_None, nullptr); 13846 Param->setImplicit(); 13847 return Param; 13848 } 13849 13850 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13851 // Don't diagnose unused-parameter errors in template instantiations; we 13852 // will already have done so in the template itself. 13853 if (inTemplateInstantiation()) 13854 return; 13855 13856 for (const ParmVarDecl *Parameter : Parameters) { 13857 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13858 !Parameter->hasAttr<UnusedAttr>()) { 13859 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13860 << Parameter->getDeclName(); 13861 } 13862 } 13863 } 13864 13865 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13866 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13867 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13868 return; 13869 13870 // Warn if the return value is pass-by-value and larger than the specified 13871 // threshold. 13872 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13873 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13874 if (Size > LangOpts.NumLargeByValueCopy) 13875 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13876 } 13877 13878 // Warn if any parameter is pass-by-value and larger than the specified 13879 // threshold. 13880 for (const ParmVarDecl *Parameter : Parameters) { 13881 QualType T = Parameter->getType(); 13882 if (T->isDependentType() || !T.isPODType(Context)) 13883 continue; 13884 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13885 if (Size > LangOpts.NumLargeByValueCopy) 13886 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13887 << Parameter << Size; 13888 } 13889 } 13890 13891 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13892 SourceLocation NameLoc, IdentifierInfo *Name, 13893 QualType T, TypeSourceInfo *TSInfo, 13894 StorageClass SC) { 13895 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13896 if (getLangOpts().ObjCAutoRefCount && 13897 T.getObjCLifetime() == Qualifiers::OCL_None && 13898 T->isObjCLifetimeType()) { 13899 13900 Qualifiers::ObjCLifetime lifetime; 13901 13902 // Special cases for arrays: 13903 // - if it's const, use __unsafe_unretained 13904 // - otherwise, it's an error 13905 if (T->isArrayType()) { 13906 if (!T.isConstQualified()) { 13907 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13908 DelayedDiagnostics.add( 13909 sema::DelayedDiagnostic::makeForbiddenType( 13910 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13911 else 13912 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13913 << TSInfo->getTypeLoc().getSourceRange(); 13914 } 13915 lifetime = Qualifiers::OCL_ExplicitNone; 13916 } else { 13917 lifetime = T->getObjCARCImplicitLifetime(); 13918 } 13919 T = Context.getLifetimeQualifiedType(T, lifetime); 13920 } 13921 13922 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13923 Context.getAdjustedParameterType(T), 13924 TSInfo, SC, nullptr); 13925 13926 // Make a note if we created a new pack in the scope of a lambda, so that 13927 // we know that references to that pack must also be expanded within the 13928 // lambda scope. 13929 if (New->isParameterPack()) 13930 if (auto *LSI = getEnclosingLambda()) 13931 LSI->LocalPacks.push_back(New); 13932 13933 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13934 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13935 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13936 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13937 13938 // Parameters can not be abstract class types. 13939 // For record types, this is done by the AbstractClassUsageDiagnoser once 13940 // the class has been completely parsed. 13941 if (!CurContext->isRecord() && 13942 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13943 AbstractParamType)) 13944 New->setInvalidDecl(); 13945 13946 // Parameter declarators cannot be interface types. All ObjC objects are 13947 // passed by reference. 13948 if (T->isObjCObjectType()) { 13949 SourceLocation TypeEndLoc = 13950 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13951 Diag(NameLoc, 13952 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13953 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13954 T = Context.getObjCObjectPointerType(T); 13955 New->setType(T); 13956 } 13957 13958 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13959 // duration shall not be qualified by an address-space qualifier." 13960 // Since all parameters have automatic store duration, they can not have 13961 // an address space. 13962 if (T.getAddressSpace() != LangAS::Default && 13963 // OpenCL allows function arguments declared to be an array of a type 13964 // to be qualified with an address space. 13965 !(getLangOpts().OpenCL && 13966 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13967 Diag(NameLoc, diag::err_arg_with_address_space); 13968 New->setInvalidDecl(); 13969 } 13970 13971 // PPC MMA non-pointer types are not allowed as function argument types. 13972 if (Context.getTargetInfo().getTriple().isPPC64() && 13973 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13974 New->setInvalidDecl(); 13975 } 13976 13977 return New; 13978 } 13979 13980 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13981 SourceLocation LocAfterDecls) { 13982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13983 13984 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13985 // for a K&R function. 13986 if (!FTI.hasPrototype) { 13987 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13988 --i; 13989 if (FTI.Params[i].Param == nullptr) { 13990 SmallString<256> Code; 13991 llvm::raw_svector_ostream(Code) 13992 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13993 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13994 << FTI.Params[i].Ident 13995 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13996 13997 // Implicitly declare the argument as type 'int' for lack of a better 13998 // type. 13999 AttributeFactory attrs; 14000 DeclSpec DS(attrs); 14001 const char* PrevSpec; // unused 14002 unsigned DiagID; // unused 14003 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14004 DiagID, Context.getPrintingPolicy()); 14005 // Use the identifier location for the type source range. 14006 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14007 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14008 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14009 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14010 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14011 } 14012 } 14013 } 14014 } 14015 14016 Decl * 14017 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14018 MultiTemplateParamsArg TemplateParameterLists, 14019 SkipBodyInfo *SkipBody) { 14020 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14021 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14022 Scope *ParentScope = FnBodyScope->getParent(); 14023 14024 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14025 // we define a non-templated function definition, we will create a declaration 14026 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14027 // The base function declaration will have the equivalent of an `omp declare 14028 // variant` annotation which specifies the mangled definition as a 14029 // specialization function under the OpenMP context defined as part of the 14030 // `omp begin declare variant`. 14031 SmallVector<FunctionDecl *, 4> Bases; 14032 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14033 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14034 ParentScope, D, TemplateParameterLists, Bases); 14035 14036 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14037 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14038 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14039 14040 if (!Bases.empty()) 14041 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14042 14043 return Dcl; 14044 } 14045 14046 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14047 Consumer.HandleInlineFunctionDefinition(D); 14048 } 14049 14050 static bool 14051 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14052 const FunctionDecl *&PossiblePrototype) { 14053 // Don't warn about invalid declarations. 14054 if (FD->isInvalidDecl()) 14055 return false; 14056 14057 // Or declarations that aren't global. 14058 if (!FD->isGlobal()) 14059 return false; 14060 14061 // Don't warn about C++ member functions. 14062 if (isa<CXXMethodDecl>(FD)) 14063 return false; 14064 14065 // Don't warn about 'main'. 14066 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14067 if (IdentifierInfo *II = FD->getIdentifier()) 14068 if (II->isStr("main") || II->isStr("efi_main")) 14069 return false; 14070 14071 // Don't warn about inline functions. 14072 if (FD->isInlined()) 14073 return false; 14074 14075 // Don't warn about function templates. 14076 if (FD->getDescribedFunctionTemplate()) 14077 return false; 14078 14079 // Don't warn about function template specializations. 14080 if (FD->isFunctionTemplateSpecialization()) 14081 return false; 14082 14083 // Don't warn for OpenCL kernels. 14084 if (FD->hasAttr<OpenCLKernelAttr>()) 14085 return false; 14086 14087 // Don't warn on explicitly deleted functions. 14088 if (FD->isDeleted()) 14089 return false; 14090 14091 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14092 Prev; Prev = Prev->getPreviousDecl()) { 14093 // Ignore any declarations that occur in function or method 14094 // scope, because they aren't visible from the header. 14095 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14096 continue; 14097 14098 PossiblePrototype = Prev; 14099 return Prev->getType()->isFunctionNoProtoType(); 14100 } 14101 14102 return true; 14103 } 14104 14105 void 14106 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14107 const FunctionDecl *EffectiveDefinition, 14108 SkipBodyInfo *SkipBody) { 14109 const FunctionDecl *Definition = EffectiveDefinition; 14110 if (!Definition && 14111 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14112 return; 14113 14114 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14115 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14116 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14117 // A merged copy of the same function, instantiated as a member of 14118 // the same class, is OK. 14119 if (declaresSameEntity(OrigFD, OrigDef) && 14120 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14121 cast<Decl>(FD->getLexicalDeclContext()))) 14122 return; 14123 } 14124 } 14125 } 14126 14127 if (canRedefineFunction(Definition, getLangOpts())) 14128 return; 14129 14130 // Don't emit an error when this is redefinition of a typo-corrected 14131 // definition. 14132 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14133 return; 14134 14135 // If we don't have a visible definition of the function, and it's inline or 14136 // a template, skip the new definition. 14137 if (SkipBody && !hasVisibleDefinition(Definition) && 14138 (Definition->getFormalLinkage() == InternalLinkage || 14139 Definition->isInlined() || 14140 Definition->getDescribedFunctionTemplate() || 14141 Definition->getNumTemplateParameterLists())) { 14142 SkipBody->ShouldSkip = true; 14143 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14144 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14145 makeMergedDefinitionVisible(TD); 14146 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14147 return; 14148 } 14149 14150 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14151 Definition->getStorageClass() == SC_Extern) 14152 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14153 << FD << getLangOpts().CPlusPlus; 14154 else 14155 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14156 14157 Diag(Definition->getLocation(), diag::note_previous_definition); 14158 FD->setInvalidDecl(); 14159 } 14160 14161 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14162 Sema &S) { 14163 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14164 14165 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14166 LSI->CallOperator = CallOperator; 14167 LSI->Lambda = LambdaClass; 14168 LSI->ReturnType = CallOperator->getReturnType(); 14169 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14170 14171 if (LCD == LCD_None) 14172 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14173 else if (LCD == LCD_ByCopy) 14174 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14175 else if (LCD == LCD_ByRef) 14176 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14177 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14178 14179 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14180 LSI->Mutable = !CallOperator->isConst(); 14181 14182 // Add the captures to the LSI so they can be noted as already 14183 // captured within tryCaptureVar. 14184 auto I = LambdaClass->field_begin(); 14185 for (const auto &C : LambdaClass->captures()) { 14186 if (C.capturesVariable()) { 14187 VarDecl *VD = C.getCapturedVar(); 14188 if (VD->isInitCapture()) 14189 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14190 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14191 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14192 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14193 /*EllipsisLoc*/C.isPackExpansion() 14194 ? C.getEllipsisLoc() : SourceLocation(), 14195 I->getType(), /*Invalid*/false); 14196 14197 } else if (C.capturesThis()) { 14198 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14199 C.getCaptureKind() == LCK_StarThis); 14200 } else { 14201 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14202 I->getType()); 14203 } 14204 ++I; 14205 } 14206 } 14207 14208 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14209 SkipBodyInfo *SkipBody) { 14210 if (!D) { 14211 // Parsing the function declaration failed in some way. Push on a fake scope 14212 // anyway so we can try to parse the function body. 14213 PushFunctionScope(); 14214 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14215 return D; 14216 } 14217 14218 FunctionDecl *FD = nullptr; 14219 14220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14221 FD = FunTmpl->getTemplatedDecl(); 14222 else 14223 FD = cast<FunctionDecl>(D); 14224 14225 // Do not push if it is a lambda because one is already pushed when building 14226 // the lambda in ActOnStartOfLambdaDefinition(). 14227 if (!isLambdaCallOperator(FD)) 14228 PushExpressionEvaluationContext( 14229 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14230 : ExprEvalContexts.back().Context); 14231 14232 // Check for defining attributes before the check for redefinition. 14233 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14234 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14235 FD->dropAttr<AliasAttr>(); 14236 FD->setInvalidDecl(); 14237 } 14238 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14239 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14240 FD->dropAttr<IFuncAttr>(); 14241 FD->setInvalidDecl(); 14242 } 14243 14244 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14245 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14246 Ctor->isDefaultConstructor() && 14247 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14248 // If this is an MS ABI dllexport default constructor, instantiate any 14249 // default arguments. 14250 InstantiateDefaultCtorDefaultArgs(Ctor); 14251 } 14252 } 14253 14254 // See if this is a redefinition. If 'will have body' (or similar) is already 14255 // set, then these checks were already performed when it was set. 14256 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14257 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14258 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14259 14260 // If we're skipping the body, we're done. Don't enter the scope. 14261 if (SkipBody && SkipBody->ShouldSkip) 14262 return D; 14263 } 14264 14265 // Mark this function as "will have a body eventually". This lets users to 14266 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14267 // this function. 14268 FD->setWillHaveBody(); 14269 14270 // If we are instantiating a generic lambda call operator, push 14271 // a LambdaScopeInfo onto the function stack. But use the information 14272 // that's already been calculated (ActOnLambdaExpr) to prime the current 14273 // LambdaScopeInfo. 14274 // When the template operator is being specialized, the LambdaScopeInfo, 14275 // has to be properly restored so that tryCaptureVariable doesn't try 14276 // and capture any new variables. In addition when calculating potential 14277 // captures during transformation of nested lambdas, it is necessary to 14278 // have the LSI properly restored. 14279 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14280 assert(inTemplateInstantiation() && 14281 "There should be an active template instantiation on the stack " 14282 "when instantiating a generic lambda!"); 14283 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14284 } else { 14285 // Enter a new function scope 14286 PushFunctionScope(); 14287 } 14288 14289 // Builtin functions cannot be defined. 14290 if (unsigned BuiltinID = FD->getBuiltinID()) { 14291 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14292 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14293 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14294 FD->setInvalidDecl(); 14295 } 14296 } 14297 14298 // The return type of a function definition must be complete 14299 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14300 QualType ResultType = FD->getReturnType(); 14301 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14302 !FD->isInvalidDecl() && 14303 RequireCompleteType(FD->getLocation(), ResultType, 14304 diag::err_func_def_incomplete_result)) 14305 FD->setInvalidDecl(); 14306 14307 if (FnBodyScope) 14308 PushDeclContext(FnBodyScope, FD); 14309 14310 // Check the validity of our function parameters 14311 CheckParmsForFunctionDef(FD->parameters(), 14312 /*CheckParameterNames=*/true); 14313 14314 // Add non-parameter declarations already in the function to the current 14315 // scope. 14316 if (FnBodyScope) { 14317 for (Decl *NPD : FD->decls()) { 14318 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14319 if (!NonParmDecl) 14320 continue; 14321 assert(!isa<ParmVarDecl>(NonParmDecl) && 14322 "parameters should not be in newly created FD yet"); 14323 14324 // If the decl has a name, make it accessible in the current scope. 14325 if (NonParmDecl->getDeclName()) 14326 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14327 14328 // Similarly, dive into enums and fish their constants out, making them 14329 // accessible in this scope. 14330 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14331 for (auto *EI : ED->enumerators()) 14332 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14333 } 14334 } 14335 } 14336 14337 // Introduce our parameters into the function scope 14338 for (auto Param : FD->parameters()) { 14339 Param->setOwningFunction(FD); 14340 14341 // If this has an identifier, add it to the scope stack. 14342 if (Param->getIdentifier() && FnBodyScope) { 14343 CheckShadow(FnBodyScope, Param); 14344 14345 PushOnScopeChains(Param, FnBodyScope); 14346 } 14347 } 14348 14349 // Ensure that the function's exception specification is instantiated. 14350 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14351 ResolveExceptionSpec(D->getLocation(), FPT); 14352 14353 // dllimport cannot be applied to non-inline function definitions. 14354 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14355 !FD->isTemplateInstantiation()) { 14356 assert(!FD->hasAttr<DLLExportAttr>()); 14357 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14358 FD->setInvalidDecl(); 14359 return D; 14360 } 14361 // We want to attach documentation to original Decl (which might be 14362 // a function template). 14363 ActOnDocumentableDecl(D); 14364 if (getCurLexicalContext()->isObjCContainer() && 14365 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14366 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14367 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14368 14369 return D; 14370 } 14371 14372 /// Given the set of return statements within a function body, 14373 /// compute the variables that are subject to the named return value 14374 /// optimization. 14375 /// 14376 /// Each of the variables that is subject to the named return value 14377 /// optimization will be marked as NRVO variables in the AST, and any 14378 /// return statement that has a marked NRVO variable as its NRVO candidate can 14379 /// use the named return value optimization. 14380 /// 14381 /// This function applies a very simplistic algorithm for NRVO: if every return 14382 /// statement in the scope of a variable has the same NRVO candidate, that 14383 /// candidate is an NRVO variable. 14384 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14385 ReturnStmt **Returns = Scope->Returns.data(); 14386 14387 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14388 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14389 if (!NRVOCandidate->isNRVOVariable()) 14390 Returns[I]->setNRVOCandidate(nullptr); 14391 } 14392 } 14393 } 14394 14395 bool Sema::canDelayFunctionBody(const Declarator &D) { 14396 // We can't delay parsing the body of a constexpr function template (yet). 14397 if (D.getDeclSpec().hasConstexprSpecifier()) 14398 return false; 14399 14400 // We can't delay parsing the body of a function template with a deduced 14401 // return type (yet). 14402 if (D.getDeclSpec().hasAutoTypeSpec()) { 14403 // If the placeholder introduces a non-deduced trailing return type, 14404 // we can still delay parsing it. 14405 if (D.getNumTypeObjects()) { 14406 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14407 if (Outer.Kind == DeclaratorChunk::Function && 14408 Outer.Fun.hasTrailingReturnType()) { 14409 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14410 return Ty.isNull() || !Ty->isUndeducedType(); 14411 } 14412 } 14413 return false; 14414 } 14415 14416 return true; 14417 } 14418 14419 bool Sema::canSkipFunctionBody(Decl *D) { 14420 // We cannot skip the body of a function (or function template) which is 14421 // constexpr, since we may need to evaluate its body in order to parse the 14422 // rest of the file. 14423 // We cannot skip the body of a function with an undeduced return type, 14424 // because any callers of that function need to know the type. 14425 if (const FunctionDecl *FD = D->getAsFunction()) { 14426 if (FD->isConstexpr()) 14427 return false; 14428 // We can't simply call Type::isUndeducedType here, because inside template 14429 // auto can be deduced to a dependent type, which is not considered 14430 // "undeduced". 14431 if (FD->getReturnType()->getContainedDeducedType()) 14432 return false; 14433 } 14434 return Consumer.shouldSkipFunctionBody(D); 14435 } 14436 14437 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14438 if (!Decl) 14439 return nullptr; 14440 if (FunctionDecl *FD = Decl->getAsFunction()) 14441 FD->setHasSkippedBody(); 14442 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14443 MD->setHasSkippedBody(); 14444 return Decl; 14445 } 14446 14447 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14448 return ActOnFinishFunctionBody(D, BodyArg, false); 14449 } 14450 14451 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14452 /// body. 14453 class ExitFunctionBodyRAII { 14454 public: 14455 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14456 ~ExitFunctionBodyRAII() { 14457 if (!IsLambda) 14458 S.PopExpressionEvaluationContext(); 14459 } 14460 14461 private: 14462 Sema &S; 14463 bool IsLambda = false; 14464 }; 14465 14466 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14467 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14468 14469 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14470 if (EscapeInfo.count(BD)) 14471 return EscapeInfo[BD]; 14472 14473 bool R = false; 14474 const BlockDecl *CurBD = BD; 14475 14476 do { 14477 R = !CurBD->doesNotEscape(); 14478 if (R) 14479 break; 14480 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14481 } while (CurBD); 14482 14483 return EscapeInfo[BD] = R; 14484 }; 14485 14486 // If the location where 'self' is implicitly retained is inside a escaping 14487 // block, emit a diagnostic. 14488 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14489 S.ImplicitlyRetainedSelfLocs) 14490 if (IsOrNestedInEscapingBlock(P.second)) 14491 S.Diag(P.first, diag::warn_implicitly_retains_self) 14492 << FixItHint::CreateInsertion(P.first, "self->"); 14493 } 14494 14495 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14496 bool IsInstantiation) { 14497 FunctionScopeInfo *FSI = getCurFunction(); 14498 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14499 14500 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14501 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14502 14503 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14504 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14505 14506 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14507 CheckCompletedCoroutineBody(FD, Body); 14508 14509 { 14510 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14511 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14512 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14513 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14514 14515 if (FD) { 14516 FD->setBody(Body); 14517 FD->setWillHaveBody(false); 14518 14519 if (getLangOpts().CPlusPlus14) { 14520 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14521 FD->getReturnType()->isUndeducedType()) { 14522 // If the function has a deduced result type but contains no 'return' 14523 // statements, the result type as written must be exactly 'auto', and 14524 // the deduced result type is 'void'. 14525 if (!FD->getReturnType()->getAs<AutoType>()) { 14526 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14527 << FD->getReturnType(); 14528 FD->setInvalidDecl(); 14529 } else { 14530 // Substitute 'void' for the 'auto' in the type. 14531 TypeLoc ResultType = getReturnTypeLoc(FD); 14532 Context.adjustDeducedFunctionResultType( 14533 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14534 } 14535 } 14536 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14537 // In C++11, we don't use 'auto' deduction rules for lambda call 14538 // operators because we don't support return type deduction. 14539 auto *LSI = getCurLambda(); 14540 if (LSI->HasImplicitReturnType) { 14541 deduceClosureReturnType(*LSI); 14542 14543 // C++11 [expr.prim.lambda]p4: 14544 // [...] if there are no return statements in the compound-statement 14545 // [the deduced type is] the type void 14546 QualType RetType = 14547 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14548 14549 // Update the return type to the deduced type. 14550 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14551 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14552 Proto->getExtProtoInfo())); 14553 } 14554 } 14555 14556 // If the function implicitly returns zero (like 'main') or is naked, 14557 // don't complain about missing return statements. 14558 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14559 WP.disableCheckFallThrough(); 14560 14561 // MSVC permits the use of pure specifier (=0) on function definition, 14562 // defined at class scope, warn about this non-standard construct. 14563 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14564 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14565 14566 if (!FD->isInvalidDecl()) { 14567 // Don't diagnose unused parameters of defaulted or deleted functions. 14568 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14569 DiagnoseUnusedParameters(FD->parameters()); 14570 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14571 FD->getReturnType(), FD); 14572 14573 // If this is a structor, we need a vtable. 14574 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14575 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14576 else if (CXXDestructorDecl *Destructor = 14577 dyn_cast<CXXDestructorDecl>(FD)) 14578 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14579 14580 // Try to apply the named return value optimization. We have to check 14581 // if we can do this here because lambdas keep return statements around 14582 // to deduce an implicit return type. 14583 if (FD->getReturnType()->isRecordType() && 14584 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14585 computeNRVO(Body, FSI); 14586 } 14587 14588 // GNU warning -Wmissing-prototypes: 14589 // Warn if a global function is defined without a previous 14590 // prototype declaration. This warning is issued even if the 14591 // definition itself provides a prototype. The aim is to detect 14592 // global functions that fail to be declared in header files. 14593 const FunctionDecl *PossiblePrototype = nullptr; 14594 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14595 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14596 14597 if (PossiblePrototype) { 14598 // We found a declaration that is not a prototype, 14599 // but that could be a zero-parameter prototype 14600 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14601 TypeLoc TL = TI->getTypeLoc(); 14602 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14603 Diag(PossiblePrototype->getLocation(), 14604 diag::note_declaration_not_a_prototype) 14605 << (FD->getNumParams() != 0) 14606 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14607 FTL.getRParenLoc(), "void") 14608 : FixItHint{}); 14609 } 14610 } else { 14611 // Returns true if the token beginning at this Loc is `const`. 14612 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14613 const LangOptions &LangOpts) { 14614 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14615 if (LocInfo.first.isInvalid()) 14616 return false; 14617 14618 bool Invalid = false; 14619 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14620 if (Invalid) 14621 return false; 14622 14623 if (LocInfo.second > Buffer.size()) 14624 return false; 14625 14626 const char *LexStart = Buffer.data() + LocInfo.second; 14627 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14628 14629 return StartTok.consume_front("const") && 14630 (StartTok.empty() || isWhitespace(StartTok[0]) || 14631 StartTok.startswith("/*") || StartTok.startswith("//")); 14632 }; 14633 14634 auto findBeginLoc = [&]() { 14635 // If the return type has `const` qualifier, we want to insert 14636 // `static` before `const` (and not before the typename). 14637 if ((FD->getReturnType()->isAnyPointerType() && 14638 FD->getReturnType()->getPointeeType().isConstQualified()) || 14639 FD->getReturnType().isConstQualified()) { 14640 // But only do this if we can determine where the `const` is. 14641 14642 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14643 getLangOpts())) 14644 14645 return FD->getBeginLoc(); 14646 } 14647 return FD->getTypeSpecStartLoc(); 14648 }; 14649 Diag(FD->getTypeSpecStartLoc(), 14650 diag::note_static_for_internal_linkage) 14651 << /* function */ 1 14652 << (FD->getStorageClass() == SC_None 14653 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14654 : FixItHint{}); 14655 } 14656 14657 // GNU warning -Wstrict-prototypes 14658 // Warn if K&R function is defined without a previous declaration. 14659 // This warning is issued only if the definition itself does not 14660 // provide a prototype. Only K&R definitions do not provide a 14661 // prototype. 14662 if (!FD->hasWrittenPrototype()) { 14663 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14664 TypeLoc TL = TI->getTypeLoc(); 14665 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14666 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14667 } 14668 } 14669 14670 // Warn on CPUDispatch with an actual body. 14671 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14672 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14673 if (!CmpndBody->body_empty()) 14674 Diag(CmpndBody->body_front()->getBeginLoc(), 14675 diag::warn_dispatch_body_ignored); 14676 14677 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14678 const CXXMethodDecl *KeyFunction; 14679 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14680 MD->isVirtual() && 14681 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14682 MD == KeyFunction->getCanonicalDecl()) { 14683 // Update the key-function state if necessary for this ABI. 14684 if (FD->isInlined() && 14685 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14686 Context.setNonKeyFunction(MD); 14687 14688 // If the newly-chosen key function is already defined, then we 14689 // need to mark the vtable as used retroactively. 14690 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14691 const FunctionDecl *Definition; 14692 if (KeyFunction && KeyFunction->isDefined(Definition)) 14693 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14694 } else { 14695 // We just defined they key function; mark the vtable as used. 14696 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14697 } 14698 } 14699 } 14700 14701 assert( 14702 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14703 "Function parsing confused"); 14704 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14705 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14706 MD->setBody(Body); 14707 if (!MD->isInvalidDecl()) { 14708 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14709 MD->getReturnType(), MD); 14710 14711 if (Body) 14712 computeNRVO(Body, FSI); 14713 } 14714 if (FSI->ObjCShouldCallSuper) { 14715 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14716 << MD->getSelector().getAsString(); 14717 FSI->ObjCShouldCallSuper = false; 14718 } 14719 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14720 const ObjCMethodDecl *InitMethod = nullptr; 14721 bool isDesignated = 14722 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14723 assert(isDesignated && InitMethod); 14724 (void)isDesignated; 14725 14726 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14727 auto IFace = MD->getClassInterface(); 14728 if (!IFace) 14729 return false; 14730 auto SuperD = IFace->getSuperClass(); 14731 if (!SuperD) 14732 return false; 14733 return SuperD->getIdentifier() == 14734 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14735 }; 14736 // Don't issue this warning for unavailable inits or direct subclasses 14737 // of NSObject. 14738 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14739 Diag(MD->getLocation(), 14740 diag::warn_objc_designated_init_missing_super_call); 14741 Diag(InitMethod->getLocation(), 14742 diag::note_objc_designated_init_marked_here); 14743 } 14744 FSI->ObjCWarnForNoDesignatedInitChain = false; 14745 } 14746 if (FSI->ObjCWarnForNoInitDelegation) { 14747 // Don't issue this warning for unavaialable inits. 14748 if (!MD->isUnavailable()) 14749 Diag(MD->getLocation(), 14750 diag::warn_objc_secondary_init_missing_init_call); 14751 FSI->ObjCWarnForNoInitDelegation = false; 14752 } 14753 14754 diagnoseImplicitlyRetainedSelf(*this); 14755 } else { 14756 // Parsing the function declaration failed in some way. Pop the fake scope 14757 // we pushed on. 14758 PopFunctionScopeInfo(ActivePolicy, dcl); 14759 return nullptr; 14760 } 14761 14762 if (Body && FSI->HasPotentialAvailabilityViolations) 14763 DiagnoseUnguardedAvailabilityViolations(dcl); 14764 14765 assert(!FSI->ObjCShouldCallSuper && 14766 "This should only be set for ObjC methods, which should have been " 14767 "handled in the block above."); 14768 14769 // Verify and clean out per-function state. 14770 if (Body && (!FD || !FD->isDefaulted())) { 14771 // C++ constructors that have function-try-blocks can't have return 14772 // statements in the handlers of that block. (C++ [except.handle]p14) 14773 // Verify this. 14774 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14775 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14776 14777 // Verify that gotos and switch cases don't jump into scopes illegally. 14778 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 14779 DiagnoseInvalidJumps(Body); 14780 14781 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14782 if (!Destructor->getParent()->isDependentType()) 14783 CheckDestructor(Destructor); 14784 14785 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14786 Destructor->getParent()); 14787 } 14788 14789 // If any errors have occurred, clear out any temporaries that may have 14790 // been leftover. This ensures that these temporaries won't be picked up 14791 // for deletion in some later function. 14792 if (hasUncompilableErrorOccurred() || 14793 getDiagnostics().getSuppressAllDiagnostics()) { 14794 DiscardCleanupsInEvaluationContext(); 14795 } 14796 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 14797 // Since the body is valid, issue any analysis-based warnings that are 14798 // enabled. 14799 ActivePolicy = &WP; 14800 } 14801 14802 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14803 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14804 FD->setInvalidDecl(); 14805 14806 if (FD && FD->hasAttr<NakedAttr>()) { 14807 for (const Stmt *S : Body->children()) { 14808 // Allow local register variables without initializer as they don't 14809 // require prologue. 14810 bool RegisterVariables = false; 14811 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14812 for (const auto *Decl : DS->decls()) { 14813 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14814 RegisterVariables = 14815 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14816 if (!RegisterVariables) 14817 break; 14818 } 14819 } 14820 } 14821 if (RegisterVariables) 14822 continue; 14823 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14824 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14825 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14826 FD->setInvalidDecl(); 14827 break; 14828 } 14829 } 14830 } 14831 14832 assert(ExprCleanupObjects.size() == 14833 ExprEvalContexts.back().NumCleanupObjects && 14834 "Leftover temporaries in function"); 14835 assert(!Cleanup.exprNeedsCleanups() && 14836 "Unaccounted cleanups in function"); 14837 assert(MaybeODRUseExprs.empty() && 14838 "Leftover expressions for odr-use checking"); 14839 } 14840 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 14841 // the declaration context below. Otherwise, we're unable to transform 14842 // 'this' expressions when transforming immediate context functions. 14843 14844 if (!IsInstantiation) 14845 PopDeclContext(); 14846 14847 PopFunctionScopeInfo(ActivePolicy, dcl); 14848 // If any errors have occurred, clear out any temporaries that may have 14849 // been leftover. This ensures that these temporaries won't be picked up for 14850 // deletion in some later function. 14851 if (hasUncompilableErrorOccurred()) { 14852 DiscardCleanupsInEvaluationContext(); 14853 } 14854 14855 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 14856 !LangOpts.OMPTargetTriples.empty())) || 14857 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14858 auto ES = getEmissionStatus(FD); 14859 if (ES == Sema::FunctionEmissionStatus::Emitted || 14860 ES == Sema::FunctionEmissionStatus::Unknown) 14861 DeclsToCheckForDeferredDiags.insert(FD); 14862 } 14863 14864 if (FD && !FD->isDeleted()) 14865 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 14866 14867 return dcl; 14868 } 14869 14870 /// When we finish delayed parsing of an attribute, we must attach it to the 14871 /// relevant Decl. 14872 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14873 ParsedAttributes &Attrs) { 14874 // Always attach attributes to the underlying decl. 14875 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14876 D = TD->getTemplatedDecl(); 14877 ProcessDeclAttributeList(S, D, Attrs); 14878 14879 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14880 if (Method->isStatic()) 14881 checkThisInStaticMemberFunctionAttributes(Method); 14882 } 14883 14884 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14885 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14886 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14887 IdentifierInfo &II, Scope *S) { 14888 // Find the scope in which the identifier is injected and the corresponding 14889 // DeclContext. 14890 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14891 // In that case, we inject the declaration into the translation unit scope 14892 // instead. 14893 Scope *BlockScope = S; 14894 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14895 BlockScope = BlockScope->getParent(); 14896 14897 Scope *ContextScope = BlockScope; 14898 while (!ContextScope->getEntity()) 14899 ContextScope = ContextScope->getParent(); 14900 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14901 14902 // Before we produce a declaration for an implicitly defined 14903 // function, see whether there was a locally-scoped declaration of 14904 // this name as a function or variable. If so, use that 14905 // (non-visible) declaration, and complain about it. 14906 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14907 if (ExternCPrev) { 14908 // We still need to inject the function into the enclosing block scope so 14909 // that later (non-call) uses can see it. 14910 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14911 14912 // C89 footnote 38: 14913 // If in fact it is not defined as having type "function returning int", 14914 // the behavior is undefined. 14915 if (!isa<FunctionDecl>(ExternCPrev) || 14916 !Context.typesAreCompatible( 14917 cast<FunctionDecl>(ExternCPrev)->getType(), 14918 Context.getFunctionNoProtoType(Context.IntTy))) { 14919 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14920 << ExternCPrev << !getLangOpts().C99; 14921 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14922 return ExternCPrev; 14923 } 14924 } 14925 14926 // Extension in C99. Legal in C90, but warn about it. 14927 unsigned diag_id; 14928 if (II.getName().startswith("__builtin_")) 14929 diag_id = diag::warn_builtin_unknown; 14930 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14931 else if (getLangOpts().OpenCL) 14932 diag_id = diag::err_opencl_implicit_function_decl; 14933 else if (getLangOpts().C99) 14934 diag_id = diag::ext_implicit_function_decl; 14935 else 14936 diag_id = diag::warn_implicit_function_decl; 14937 Diag(Loc, diag_id) << &II; 14938 14939 // If we found a prior declaration of this function, don't bother building 14940 // another one. We've already pushed that one into scope, so there's nothing 14941 // more to do. 14942 if (ExternCPrev) 14943 return ExternCPrev; 14944 14945 // Because typo correction is expensive, only do it if the implicit 14946 // function declaration is going to be treated as an error. 14947 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14948 TypoCorrection Corrected; 14949 DeclFilterCCC<FunctionDecl> CCC{}; 14950 if (S && (Corrected = 14951 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14952 S, nullptr, CCC, CTK_NonError))) 14953 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14954 /*ErrorRecovery*/false); 14955 } 14956 14957 // Set a Declarator for the implicit definition: int foo(); 14958 const char *Dummy; 14959 AttributeFactory attrFactory; 14960 DeclSpec DS(attrFactory); 14961 unsigned DiagID; 14962 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14963 Context.getPrintingPolicy()); 14964 (void)Error; // Silence warning. 14965 assert(!Error && "Error setting up implicit decl!"); 14966 SourceLocation NoLoc; 14967 Declarator D(DS, DeclaratorContext::Block); 14968 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14969 /*IsAmbiguous=*/false, 14970 /*LParenLoc=*/NoLoc, 14971 /*Params=*/nullptr, 14972 /*NumParams=*/0, 14973 /*EllipsisLoc=*/NoLoc, 14974 /*RParenLoc=*/NoLoc, 14975 /*RefQualifierIsLvalueRef=*/true, 14976 /*RefQualifierLoc=*/NoLoc, 14977 /*MutableLoc=*/NoLoc, EST_None, 14978 /*ESpecRange=*/SourceRange(), 14979 /*Exceptions=*/nullptr, 14980 /*ExceptionRanges=*/nullptr, 14981 /*NumExceptions=*/0, 14982 /*NoexceptExpr=*/nullptr, 14983 /*ExceptionSpecTokens=*/nullptr, 14984 /*DeclsInPrototype=*/None, Loc, 14985 Loc, D), 14986 std::move(DS.getAttributes()), SourceLocation()); 14987 D.SetIdentifier(&II, Loc); 14988 14989 // Insert this function into the enclosing block scope. 14990 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14991 FD->setImplicit(); 14992 14993 AddKnownFunctionAttributes(FD); 14994 14995 return FD; 14996 } 14997 14998 /// If this function is a C++ replaceable global allocation function 14999 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15000 /// adds any function attributes that we know a priori based on the standard. 15001 /// 15002 /// We need to check for duplicate attributes both here and where user-written 15003 /// attributes are applied to declarations. 15004 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15005 FunctionDecl *FD) { 15006 if (FD->isInvalidDecl()) 15007 return; 15008 15009 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15010 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15011 return; 15012 15013 Optional<unsigned> AlignmentParam; 15014 bool IsNothrow = false; 15015 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15016 return; 15017 15018 // C++2a [basic.stc.dynamic.allocation]p4: 15019 // An allocation function that has a non-throwing exception specification 15020 // indicates failure by returning a null pointer value. Any other allocation 15021 // function never returns a null pointer value and indicates failure only by 15022 // throwing an exception [...] 15023 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15024 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15025 15026 // C++2a [basic.stc.dynamic.allocation]p2: 15027 // An allocation function attempts to allocate the requested amount of 15028 // storage. [...] If the request succeeds, the value returned by a 15029 // replaceable allocation function is a [...] pointer value p0 different 15030 // from any previously returned value p1 [...] 15031 // 15032 // However, this particular information is being added in codegen, 15033 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15034 15035 // C++2a [basic.stc.dynamic.allocation]p2: 15036 // An allocation function attempts to allocate the requested amount of 15037 // storage. If it is successful, it returns the address of the start of a 15038 // block of storage whose length in bytes is at least as large as the 15039 // requested size. 15040 if (!FD->hasAttr<AllocSizeAttr>()) { 15041 FD->addAttr(AllocSizeAttr::CreateImplicit( 15042 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15043 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15044 } 15045 15046 // C++2a [basic.stc.dynamic.allocation]p3: 15047 // For an allocation function [...], the pointer returned on a successful 15048 // call shall represent the address of storage that is aligned as follows: 15049 // (3.1) If the allocation function takes an argument of type 15050 // std::align_val_t, the storage will have the alignment 15051 // specified by the value of this argument. 15052 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15053 FD->addAttr(AllocAlignAttr::CreateImplicit( 15054 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15055 } 15056 15057 // FIXME: 15058 // C++2a [basic.stc.dynamic.allocation]p3: 15059 // For an allocation function [...], the pointer returned on a successful 15060 // call shall represent the address of storage that is aligned as follows: 15061 // (3.2) Otherwise, if the allocation function is named operator new[], 15062 // the storage is aligned for any object that does not have 15063 // new-extended alignment ([basic.align]) and is no larger than the 15064 // requested size. 15065 // (3.3) Otherwise, the storage is aligned for any object that does not 15066 // have new-extended alignment and is of the requested size. 15067 } 15068 15069 /// Adds any function attributes that we know a priori based on 15070 /// the declaration of this function. 15071 /// 15072 /// These attributes can apply both to implicitly-declared builtins 15073 /// (like __builtin___printf_chk) or to library-declared functions 15074 /// like NSLog or printf. 15075 /// 15076 /// We need to check for duplicate attributes both here and where user-written 15077 /// attributes are applied to declarations. 15078 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15079 if (FD->isInvalidDecl()) 15080 return; 15081 15082 // If this is a built-in function, map its builtin attributes to 15083 // actual attributes. 15084 if (unsigned BuiltinID = FD->getBuiltinID()) { 15085 // Handle printf-formatting attributes. 15086 unsigned FormatIdx; 15087 bool HasVAListArg; 15088 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15089 if (!FD->hasAttr<FormatAttr>()) { 15090 const char *fmt = "printf"; 15091 unsigned int NumParams = FD->getNumParams(); 15092 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15093 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15094 fmt = "NSString"; 15095 FD->addAttr(FormatAttr::CreateImplicit(Context, 15096 &Context.Idents.get(fmt), 15097 FormatIdx+1, 15098 HasVAListArg ? 0 : FormatIdx+2, 15099 FD->getLocation())); 15100 } 15101 } 15102 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15103 HasVAListArg)) { 15104 if (!FD->hasAttr<FormatAttr>()) 15105 FD->addAttr(FormatAttr::CreateImplicit(Context, 15106 &Context.Idents.get("scanf"), 15107 FormatIdx+1, 15108 HasVAListArg ? 0 : FormatIdx+2, 15109 FD->getLocation())); 15110 } 15111 15112 // Handle automatically recognized callbacks. 15113 SmallVector<int, 4> Encoding; 15114 if (!FD->hasAttr<CallbackAttr>() && 15115 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15116 FD->addAttr(CallbackAttr::CreateImplicit( 15117 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15118 15119 // Mark const if we don't care about errno and that is the only thing 15120 // preventing the function from being const. This allows IRgen to use LLVM 15121 // intrinsics for such functions. 15122 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15123 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15124 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15125 15126 // We make "fma" on some platforms const because we know it does not set 15127 // errno in those environments even though it could set errno based on the 15128 // C standard. 15129 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15130 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15131 !FD->hasAttr<ConstAttr>()) { 15132 switch (BuiltinID) { 15133 case Builtin::BI__builtin_fma: 15134 case Builtin::BI__builtin_fmaf: 15135 case Builtin::BI__builtin_fmal: 15136 case Builtin::BIfma: 15137 case Builtin::BIfmaf: 15138 case Builtin::BIfmal: 15139 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15140 break; 15141 default: 15142 break; 15143 } 15144 } 15145 15146 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15147 !FD->hasAttr<ReturnsTwiceAttr>()) 15148 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15149 FD->getLocation())); 15150 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15151 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15152 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15153 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15154 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15155 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15156 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15157 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15158 // Add the appropriate attribute, depending on the CUDA compilation mode 15159 // and which target the builtin belongs to. For example, during host 15160 // compilation, aux builtins are __device__, while the rest are __host__. 15161 if (getLangOpts().CUDAIsDevice != 15162 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15163 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15164 else 15165 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15166 } 15167 15168 // Add known guaranteed alignment for allocation functions. 15169 switch (BuiltinID) { 15170 case Builtin::BIaligned_alloc: 15171 if (!FD->hasAttr<AllocAlignAttr>()) 15172 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15173 FD->getLocation())); 15174 LLVM_FALLTHROUGH; 15175 case Builtin::BIcalloc: 15176 case Builtin::BImalloc: 15177 case Builtin::BImemalign: 15178 case Builtin::BIrealloc: 15179 case Builtin::BIstrdup: 15180 case Builtin::BIstrndup: { 15181 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15182 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15183 Context.getTargetInfo().getCharWidth(); 15184 IntegerLiteral *Alignment = IntegerLiteral::Create( 15185 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15186 Context.UnsignedIntTy, FD->getLocation()); 15187 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15188 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15189 } 15190 break; 15191 } 15192 default: 15193 break; 15194 } 15195 } 15196 15197 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15198 15199 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15200 // throw, add an implicit nothrow attribute to any extern "C" function we come 15201 // across. 15202 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15203 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15204 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15205 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15206 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15207 } 15208 15209 IdentifierInfo *Name = FD->getIdentifier(); 15210 if (!Name) 15211 return; 15212 if ((!getLangOpts().CPlusPlus && 15213 FD->getDeclContext()->isTranslationUnit()) || 15214 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15215 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15216 LinkageSpecDecl::lang_c)) { 15217 // Okay: this could be a libc/libm/Objective-C function we know 15218 // about. 15219 } else 15220 return; 15221 15222 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15223 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15224 // target-specific builtins, perhaps? 15225 if (!FD->hasAttr<FormatAttr>()) 15226 FD->addAttr(FormatAttr::CreateImplicit(Context, 15227 &Context.Idents.get("printf"), 2, 15228 Name->isStr("vasprintf") ? 0 : 3, 15229 FD->getLocation())); 15230 } 15231 15232 if (Name->isStr("__CFStringMakeConstantString")) { 15233 // We already have a __builtin___CFStringMakeConstantString, 15234 // but builds that use -fno-constant-cfstrings don't go through that. 15235 if (!FD->hasAttr<FormatArgAttr>()) 15236 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15237 FD->getLocation())); 15238 } 15239 } 15240 15241 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15242 TypeSourceInfo *TInfo) { 15243 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15244 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15245 15246 if (!TInfo) { 15247 assert(D.isInvalidType() && "no declarator info for valid type"); 15248 TInfo = Context.getTrivialTypeSourceInfo(T); 15249 } 15250 15251 // Scope manipulation handled by caller. 15252 TypedefDecl *NewTD = 15253 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15254 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15255 15256 // Bail out immediately if we have an invalid declaration. 15257 if (D.isInvalidType()) { 15258 NewTD->setInvalidDecl(); 15259 return NewTD; 15260 } 15261 15262 if (D.getDeclSpec().isModulePrivateSpecified()) { 15263 if (CurContext->isFunctionOrMethod()) 15264 Diag(NewTD->getLocation(), diag::err_module_private_local) 15265 << 2 << NewTD 15266 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15267 << FixItHint::CreateRemoval( 15268 D.getDeclSpec().getModulePrivateSpecLoc()); 15269 else 15270 NewTD->setModulePrivate(); 15271 } 15272 15273 // C++ [dcl.typedef]p8: 15274 // If the typedef declaration defines an unnamed class (or 15275 // enum), the first typedef-name declared by the declaration 15276 // to be that class type (or enum type) is used to denote the 15277 // class type (or enum type) for linkage purposes only. 15278 // We need to check whether the type was declared in the declaration. 15279 switch (D.getDeclSpec().getTypeSpecType()) { 15280 case TST_enum: 15281 case TST_struct: 15282 case TST_interface: 15283 case TST_union: 15284 case TST_class: { 15285 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15286 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15287 break; 15288 } 15289 15290 default: 15291 break; 15292 } 15293 15294 return NewTD; 15295 } 15296 15297 /// Check that this is a valid underlying type for an enum declaration. 15298 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15299 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15300 QualType T = TI->getType(); 15301 15302 if (T->isDependentType()) 15303 return false; 15304 15305 // This doesn't use 'isIntegralType' despite the error message mentioning 15306 // integral type because isIntegralType would also allow enum types in C. 15307 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15308 if (BT->isInteger()) 15309 return false; 15310 15311 if (T->isExtIntType()) 15312 return false; 15313 15314 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15315 } 15316 15317 /// Check whether this is a valid redeclaration of a previous enumeration. 15318 /// \return true if the redeclaration was invalid. 15319 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15320 QualType EnumUnderlyingTy, bool IsFixed, 15321 const EnumDecl *Prev) { 15322 if (IsScoped != Prev->isScoped()) { 15323 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15324 << Prev->isScoped(); 15325 Diag(Prev->getLocation(), diag::note_previous_declaration); 15326 return true; 15327 } 15328 15329 if (IsFixed && Prev->isFixed()) { 15330 if (!EnumUnderlyingTy->isDependentType() && 15331 !Prev->getIntegerType()->isDependentType() && 15332 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15333 Prev->getIntegerType())) { 15334 // TODO: Highlight the underlying type of the redeclaration. 15335 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15336 << EnumUnderlyingTy << Prev->getIntegerType(); 15337 Diag(Prev->getLocation(), diag::note_previous_declaration) 15338 << Prev->getIntegerTypeRange(); 15339 return true; 15340 } 15341 } else if (IsFixed != Prev->isFixed()) { 15342 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15343 << Prev->isFixed(); 15344 Diag(Prev->getLocation(), diag::note_previous_declaration); 15345 return true; 15346 } 15347 15348 return false; 15349 } 15350 15351 /// Get diagnostic %select index for tag kind for 15352 /// redeclaration diagnostic message. 15353 /// WARNING: Indexes apply to particular diagnostics only! 15354 /// 15355 /// \returns diagnostic %select index. 15356 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15357 switch (Tag) { 15358 case TTK_Struct: return 0; 15359 case TTK_Interface: return 1; 15360 case TTK_Class: return 2; 15361 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15362 } 15363 } 15364 15365 /// Determine if tag kind is a class-key compatible with 15366 /// class for redeclaration (class, struct, or __interface). 15367 /// 15368 /// \returns true iff the tag kind is compatible. 15369 static bool isClassCompatTagKind(TagTypeKind Tag) 15370 { 15371 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15372 } 15373 15374 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15375 TagTypeKind TTK) { 15376 if (isa<TypedefDecl>(PrevDecl)) 15377 return NTK_Typedef; 15378 else if (isa<TypeAliasDecl>(PrevDecl)) 15379 return NTK_TypeAlias; 15380 else if (isa<ClassTemplateDecl>(PrevDecl)) 15381 return NTK_Template; 15382 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15383 return NTK_TypeAliasTemplate; 15384 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15385 return NTK_TemplateTemplateArgument; 15386 switch (TTK) { 15387 case TTK_Struct: 15388 case TTK_Interface: 15389 case TTK_Class: 15390 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15391 case TTK_Union: 15392 return NTK_NonUnion; 15393 case TTK_Enum: 15394 return NTK_NonEnum; 15395 } 15396 llvm_unreachable("invalid TTK"); 15397 } 15398 15399 /// Determine whether a tag with a given kind is acceptable 15400 /// as a redeclaration of the given tag declaration. 15401 /// 15402 /// \returns true if the new tag kind is acceptable, false otherwise. 15403 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15404 TagTypeKind NewTag, bool isDefinition, 15405 SourceLocation NewTagLoc, 15406 const IdentifierInfo *Name) { 15407 // C++ [dcl.type.elab]p3: 15408 // The class-key or enum keyword present in the 15409 // elaborated-type-specifier shall agree in kind with the 15410 // declaration to which the name in the elaborated-type-specifier 15411 // refers. This rule also applies to the form of 15412 // elaborated-type-specifier that declares a class-name or 15413 // friend class since it can be construed as referring to the 15414 // definition of the class. Thus, in any 15415 // elaborated-type-specifier, the enum keyword shall be used to 15416 // refer to an enumeration (7.2), the union class-key shall be 15417 // used to refer to a union (clause 9), and either the class or 15418 // struct class-key shall be used to refer to a class (clause 9) 15419 // declared using the class or struct class-key. 15420 TagTypeKind OldTag = Previous->getTagKind(); 15421 if (OldTag != NewTag && 15422 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15423 return false; 15424 15425 // Tags are compatible, but we might still want to warn on mismatched tags. 15426 // Non-class tags can't be mismatched at this point. 15427 if (!isClassCompatTagKind(NewTag)) 15428 return true; 15429 15430 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15431 // by our warning analysis. We don't want to warn about mismatches with (eg) 15432 // declarations in system headers that are designed to be specialized, but if 15433 // a user asks us to warn, we should warn if their code contains mismatched 15434 // declarations. 15435 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15436 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15437 Loc); 15438 }; 15439 if (IsIgnoredLoc(NewTagLoc)) 15440 return true; 15441 15442 auto IsIgnored = [&](const TagDecl *Tag) { 15443 return IsIgnoredLoc(Tag->getLocation()); 15444 }; 15445 while (IsIgnored(Previous)) { 15446 Previous = Previous->getPreviousDecl(); 15447 if (!Previous) 15448 return true; 15449 OldTag = Previous->getTagKind(); 15450 } 15451 15452 bool isTemplate = false; 15453 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15454 isTemplate = Record->getDescribedClassTemplate(); 15455 15456 if (inTemplateInstantiation()) { 15457 if (OldTag != NewTag) { 15458 // In a template instantiation, do not offer fix-its for tag mismatches 15459 // since they usually mess up the template instead of fixing the problem. 15460 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15461 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15462 << getRedeclDiagFromTagKind(OldTag); 15463 // FIXME: Note previous location? 15464 } 15465 return true; 15466 } 15467 15468 if (isDefinition) { 15469 // On definitions, check all previous tags and issue a fix-it for each 15470 // one that doesn't match the current tag. 15471 if (Previous->getDefinition()) { 15472 // Don't suggest fix-its for redefinitions. 15473 return true; 15474 } 15475 15476 bool previousMismatch = false; 15477 for (const TagDecl *I : Previous->redecls()) { 15478 if (I->getTagKind() != NewTag) { 15479 // Ignore previous declarations for which the warning was disabled. 15480 if (IsIgnored(I)) 15481 continue; 15482 15483 if (!previousMismatch) { 15484 previousMismatch = true; 15485 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15486 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15487 << getRedeclDiagFromTagKind(I->getTagKind()); 15488 } 15489 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15490 << getRedeclDiagFromTagKind(NewTag) 15491 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15492 TypeWithKeyword::getTagTypeKindName(NewTag)); 15493 } 15494 } 15495 return true; 15496 } 15497 15498 // Identify the prevailing tag kind: this is the kind of the definition (if 15499 // there is a non-ignored definition), or otherwise the kind of the prior 15500 // (non-ignored) declaration. 15501 const TagDecl *PrevDef = Previous->getDefinition(); 15502 if (PrevDef && IsIgnored(PrevDef)) 15503 PrevDef = nullptr; 15504 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15505 if (Redecl->getTagKind() != NewTag) { 15506 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15507 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15508 << getRedeclDiagFromTagKind(OldTag); 15509 Diag(Redecl->getLocation(), diag::note_previous_use); 15510 15511 // If there is a previous definition, suggest a fix-it. 15512 if (PrevDef) { 15513 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15514 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15515 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15516 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15517 } 15518 } 15519 15520 return true; 15521 } 15522 15523 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15524 /// from an outer enclosing namespace or file scope inside a friend declaration. 15525 /// This should provide the commented out code in the following snippet: 15526 /// namespace N { 15527 /// struct X; 15528 /// namespace M { 15529 /// struct Y { friend struct /*N::*/ X; }; 15530 /// } 15531 /// } 15532 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15533 SourceLocation NameLoc) { 15534 // While the decl is in a namespace, do repeated lookup of that name and see 15535 // if we get the same namespace back. If we do not, continue until 15536 // translation unit scope, at which point we have a fully qualified NNS. 15537 SmallVector<IdentifierInfo *, 4> Namespaces; 15538 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15539 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15540 // This tag should be declared in a namespace, which can only be enclosed by 15541 // other namespaces. Bail if there's an anonymous namespace in the chain. 15542 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15543 if (!Namespace || Namespace->isAnonymousNamespace()) 15544 return FixItHint(); 15545 IdentifierInfo *II = Namespace->getIdentifier(); 15546 Namespaces.push_back(II); 15547 NamedDecl *Lookup = SemaRef.LookupSingleName( 15548 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15549 if (Lookup == Namespace) 15550 break; 15551 } 15552 15553 // Once we have all the namespaces, reverse them to go outermost first, and 15554 // build an NNS. 15555 SmallString<64> Insertion; 15556 llvm::raw_svector_ostream OS(Insertion); 15557 if (DC->isTranslationUnit()) 15558 OS << "::"; 15559 std::reverse(Namespaces.begin(), Namespaces.end()); 15560 for (auto *II : Namespaces) 15561 OS << II->getName() << "::"; 15562 return FixItHint::CreateInsertion(NameLoc, Insertion); 15563 } 15564 15565 /// Determine whether a tag originally declared in context \p OldDC can 15566 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15567 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15568 /// using-declaration). 15569 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15570 DeclContext *NewDC) { 15571 OldDC = OldDC->getRedeclContext(); 15572 NewDC = NewDC->getRedeclContext(); 15573 15574 if (OldDC->Equals(NewDC)) 15575 return true; 15576 15577 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15578 // encloses the other). 15579 if (S.getLangOpts().MSVCCompat && 15580 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15581 return true; 15582 15583 return false; 15584 } 15585 15586 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15587 /// former case, Name will be non-null. In the later case, Name will be null. 15588 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15589 /// reference/declaration/definition of a tag. 15590 /// 15591 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15592 /// trailing-type-specifier) other than one in an alias-declaration. 15593 /// 15594 /// \param SkipBody If non-null, will be set to indicate if the caller should 15595 /// skip the definition of this tag and treat it as if it were a declaration. 15596 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15597 SourceLocation KWLoc, CXXScopeSpec &SS, 15598 IdentifierInfo *Name, SourceLocation NameLoc, 15599 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15600 SourceLocation ModulePrivateLoc, 15601 MultiTemplateParamsArg TemplateParameterLists, 15602 bool &OwnedDecl, bool &IsDependent, 15603 SourceLocation ScopedEnumKWLoc, 15604 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15605 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15606 SkipBodyInfo *SkipBody) { 15607 // If this is not a definition, it must have a name. 15608 IdentifierInfo *OrigName = Name; 15609 assert((Name != nullptr || TUK == TUK_Definition) && 15610 "Nameless record must be a definition!"); 15611 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15612 15613 OwnedDecl = false; 15614 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15615 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15616 15617 // FIXME: Check member specializations more carefully. 15618 bool isMemberSpecialization = false; 15619 bool Invalid = false; 15620 15621 // We only need to do this matching if we have template parameters 15622 // or a scope specifier, which also conveniently avoids this work 15623 // for non-C++ cases. 15624 if (TemplateParameterLists.size() > 0 || 15625 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15626 if (TemplateParameterList *TemplateParams = 15627 MatchTemplateParametersToScopeSpecifier( 15628 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15629 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15630 if (Kind == TTK_Enum) { 15631 Diag(KWLoc, diag::err_enum_template); 15632 return nullptr; 15633 } 15634 15635 if (TemplateParams->size() > 0) { 15636 // This is a declaration or definition of a class template (which may 15637 // be a member of another template). 15638 15639 if (Invalid) 15640 return nullptr; 15641 15642 OwnedDecl = false; 15643 DeclResult Result = CheckClassTemplate( 15644 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15645 AS, ModulePrivateLoc, 15646 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15647 TemplateParameterLists.data(), SkipBody); 15648 return Result.get(); 15649 } else { 15650 // The "template<>" header is extraneous. 15651 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15652 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15653 isMemberSpecialization = true; 15654 } 15655 } 15656 15657 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15658 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15659 return nullptr; 15660 } 15661 15662 // Figure out the underlying type if this a enum declaration. We need to do 15663 // this early, because it's needed to detect if this is an incompatible 15664 // redeclaration. 15665 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15666 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15667 15668 if (Kind == TTK_Enum) { 15669 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15670 // No underlying type explicitly specified, or we failed to parse the 15671 // type, default to int. 15672 EnumUnderlying = Context.IntTy.getTypePtr(); 15673 } else if (UnderlyingType.get()) { 15674 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15675 // integral type; any cv-qualification is ignored. 15676 TypeSourceInfo *TI = nullptr; 15677 GetTypeFromParser(UnderlyingType.get(), &TI); 15678 EnumUnderlying = TI; 15679 15680 if (CheckEnumUnderlyingType(TI)) 15681 // Recover by falling back to int. 15682 EnumUnderlying = Context.IntTy.getTypePtr(); 15683 15684 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15685 UPPC_FixedUnderlyingType)) 15686 EnumUnderlying = Context.IntTy.getTypePtr(); 15687 15688 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15689 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15690 // of 'int'. However, if this is an unfixed forward declaration, don't set 15691 // the underlying type unless the user enables -fms-compatibility. This 15692 // makes unfixed forward declared enums incomplete and is more conforming. 15693 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15694 EnumUnderlying = Context.IntTy.getTypePtr(); 15695 } 15696 } 15697 15698 DeclContext *SearchDC = CurContext; 15699 DeclContext *DC = CurContext; 15700 bool isStdBadAlloc = false; 15701 bool isStdAlignValT = false; 15702 15703 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15704 if (TUK == TUK_Friend || TUK == TUK_Reference) 15705 Redecl = NotForRedeclaration; 15706 15707 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15708 /// implemented asks for structural equivalence checking, the returned decl 15709 /// here is passed back to the parser, allowing the tag body to be parsed. 15710 auto createTagFromNewDecl = [&]() -> TagDecl * { 15711 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15712 // If there is an identifier, use the location of the identifier as the 15713 // location of the decl, otherwise use the location of the struct/union 15714 // keyword. 15715 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15716 TagDecl *New = nullptr; 15717 15718 if (Kind == TTK_Enum) { 15719 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15720 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15721 // If this is an undefined enum, bail. 15722 if (TUK != TUK_Definition && !Invalid) 15723 return nullptr; 15724 if (EnumUnderlying) { 15725 EnumDecl *ED = cast<EnumDecl>(New); 15726 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15727 ED->setIntegerTypeSourceInfo(TI); 15728 else 15729 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15730 ED->setPromotionType(ED->getIntegerType()); 15731 } 15732 } else { // struct/union 15733 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15734 nullptr); 15735 } 15736 15737 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15738 // Add alignment attributes if necessary; these attributes are checked 15739 // when the ASTContext lays out the structure. 15740 // 15741 // It is important for implementing the correct semantics that this 15742 // happen here (in ActOnTag). The #pragma pack stack is 15743 // maintained as a result of parser callbacks which can occur at 15744 // many points during the parsing of a struct declaration (because 15745 // the #pragma tokens are effectively skipped over during the 15746 // parsing of the struct). 15747 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15748 AddAlignmentAttributesForRecord(RD); 15749 AddMsStructLayoutForRecord(RD); 15750 } 15751 } 15752 New->setLexicalDeclContext(CurContext); 15753 return New; 15754 }; 15755 15756 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15757 if (Name && SS.isNotEmpty()) { 15758 // We have a nested-name tag ('struct foo::bar'). 15759 15760 // Check for invalid 'foo::'. 15761 if (SS.isInvalid()) { 15762 Name = nullptr; 15763 goto CreateNewDecl; 15764 } 15765 15766 // If this is a friend or a reference to a class in a dependent 15767 // context, don't try to make a decl for it. 15768 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15769 DC = computeDeclContext(SS, false); 15770 if (!DC) { 15771 IsDependent = true; 15772 return nullptr; 15773 } 15774 } else { 15775 DC = computeDeclContext(SS, true); 15776 if (!DC) { 15777 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15778 << SS.getRange(); 15779 return nullptr; 15780 } 15781 } 15782 15783 if (RequireCompleteDeclContext(SS, DC)) 15784 return nullptr; 15785 15786 SearchDC = DC; 15787 // Look-up name inside 'foo::'. 15788 LookupQualifiedName(Previous, DC); 15789 15790 if (Previous.isAmbiguous()) 15791 return nullptr; 15792 15793 if (Previous.empty()) { 15794 // Name lookup did not find anything. However, if the 15795 // nested-name-specifier refers to the current instantiation, 15796 // and that current instantiation has any dependent base 15797 // classes, we might find something at instantiation time: treat 15798 // this as a dependent elaborated-type-specifier. 15799 // But this only makes any sense for reference-like lookups. 15800 if (Previous.wasNotFoundInCurrentInstantiation() && 15801 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15802 IsDependent = true; 15803 return nullptr; 15804 } 15805 15806 // A tag 'foo::bar' must already exist. 15807 Diag(NameLoc, diag::err_not_tag_in_scope) 15808 << Kind << Name << DC << SS.getRange(); 15809 Name = nullptr; 15810 Invalid = true; 15811 goto CreateNewDecl; 15812 } 15813 } else if (Name) { 15814 // C++14 [class.mem]p14: 15815 // If T is the name of a class, then each of the following shall have a 15816 // name different from T: 15817 // -- every member of class T that is itself a type 15818 if (TUK != TUK_Reference && TUK != TUK_Friend && 15819 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15820 return nullptr; 15821 15822 // If this is a named struct, check to see if there was a previous forward 15823 // declaration or definition. 15824 // FIXME: We're looking into outer scopes here, even when we 15825 // shouldn't be. Doing so can result in ambiguities that we 15826 // shouldn't be diagnosing. 15827 LookupName(Previous, S); 15828 15829 // When declaring or defining a tag, ignore ambiguities introduced 15830 // by types using'ed into this scope. 15831 if (Previous.isAmbiguous() && 15832 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15833 LookupResult::Filter F = Previous.makeFilter(); 15834 while (F.hasNext()) { 15835 NamedDecl *ND = F.next(); 15836 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15837 SearchDC->getRedeclContext())) 15838 F.erase(); 15839 } 15840 F.done(); 15841 } 15842 15843 // C++11 [namespace.memdef]p3: 15844 // If the name in a friend declaration is neither qualified nor 15845 // a template-id and the declaration is a function or an 15846 // elaborated-type-specifier, the lookup to determine whether 15847 // the entity has been previously declared shall not consider 15848 // any scopes outside the innermost enclosing namespace. 15849 // 15850 // MSVC doesn't implement the above rule for types, so a friend tag 15851 // declaration may be a redeclaration of a type declared in an enclosing 15852 // scope. They do implement this rule for friend functions. 15853 // 15854 // Does it matter that this should be by scope instead of by 15855 // semantic context? 15856 if (!Previous.empty() && TUK == TUK_Friend) { 15857 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15858 LookupResult::Filter F = Previous.makeFilter(); 15859 bool FriendSawTagOutsideEnclosingNamespace = false; 15860 while (F.hasNext()) { 15861 NamedDecl *ND = F.next(); 15862 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15863 if (DC->isFileContext() && 15864 !EnclosingNS->Encloses(ND->getDeclContext())) { 15865 if (getLangOpts().MSVCCompat) 15866 FriendSawTagOutsideEnclosingNamespace = true; 15867 else 15868 F.erase(); 15869 } 15870 } 15871 F.done(); 15872 15873 // Diagnose this MSVC extension in the easy case where lookup would have 15874 // unambiguously found something outside the enclosing namespace. 15875 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15876 NamedDecl *ND = Previous.getFoundDecl(); 15877 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15878 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15879 } 15880 } 15881 15882 // Note: there used to be some attempt at recovery here. 15883 if (Previous.isAmbiguous()) 15884 return nullptr; 15885 15886 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15887 // FIXME: This makes sure that we ignore the contexts associated 15888 // with C structs, unions, and enums when looking for a matching 15889 // tag declaration or definition. See the similar lookup tweak 15890 // in Sema::LookupName; is there a better way to deal with this? 15891 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15892 SearchDC = SearchDC->getParent(); 15893 } 15894 } 15895 15896 if (Previous.isSingleResult() && 15897 Previous.getFoundDecl()->isTemplateParameter()) { 15898 // Maybe we will complain about the shadowed template parameter. 15899 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15900 // Just pretend that we didn't see the previous declaration. 15901 Previous.clear(); 15902 } 15903 15904 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15905 DC->Equals(getStdNamespace())) { 15906 if (Name->isStr("bad_alloc")) { 15907 // This is a declaration of or a reference to "std::bad_alloc". 15908 isStdBadAlloc = true; 15909 15910 // If std::bad_alloc has been implicitly declared (but made invisible to 15911 // name lookup), fill in this implicit declaration as the previous 15912 // declaration, so that the declarations get chained appropriately. 15913 if (Previous.empty() && StdBadAlloc) 15914 Previous.addDecl(getStdBadAlloc()); 15915 } else if (Name->isStr("align_val_t")) { 15916 isStdAlignValT = true; 15917 if (Previous.empty() && StdAlignValT) 15918 Previous.addDecl(getStdAlignValT()); 15919 } 15920 } 15921 15922 // If we didn't find a previous declaration, and this is a reference 15923 // (or friend reference), move to the correct scope. In C++, we 15924 // also need to do a redeclaration lookup there, just in case 15925 // there's a shadow friend decl. 15926 if (Name && Previous.empty() && 15927 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15928 if (Invalid) goto CreateNewDecl; 15929 assert(SS.isEmpty()); 15930 15931 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15932 // C++ [basic.scope.pdecl]p5: 15933 // -- for an elaborated-type-specifier of the form 15934 // 15935 // class-key identifier 15936 // 15937 // if the elaborated-type-specifier is used in the 15938 // decl-specifier-seq or parameter-declaration-clause of a 15939 // function defined in namespace scope, the identifier is 15940 // declared as a class-name in the namespace that contains 15941 // the declaration; otherwise, except as a friend 15942 // declaration, the identifier is declared in the smallest 15943 // non-class, non-function-prototype scope that contains the 15944 // declaration. 15945 // 15946 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15947 // C structs and unions. 15948 // 15949 // It is an error in C++ to declare (rather than define) an enum 15950 // type, including via an elaborated type specifier. We'll 15951 // diagnose that later; for now, declare the enum in the same 15952 // scope as we would have picked for any other tag type. 15953 // 15954 // GNU C also supports this behavior as part of its incomplete 15955 // enum types extension, while GNU C++ does not. 15956 // 15957 // Find the context where we'll be declaring the tag. 15958 // FIXME: We would like to maintain the current DeclContext as the 15959 // lexical context, 15960 SearchDC = getTagInjectionContext(SearchDC); 15961 15962 // Find the scope where we'll be declaring the tag. 15963 S = getTagInjectionScope(S, getLangOpts()); 15964 } else { 15965 assert(TUK == TUK_Friend); 15966 // C++ [namespace.memdef]p3: 15967 // If a friend declaration in a non-local class first declares a 15968 // class or function, the friend class or function is a member of 15969 // the innermost enclosing namespace. 15970 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15971 } 15972 15973 // In C++, we need to do a redeclaration lookup to properly 15974 // diagnose some problems. 15975 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15976 // hidden declaration so that we don't get ambiguity errors when using a 15977 // type declared by an elaborated-type-specifier. In C that is not correct 15978 // and we should instead merge compatible types found by lookup. 15979 if (getLangOpts().CPlusPlus) { 15980 // FIXME: This can perform qualified lookups into function contexts, 15981 // which are meaningless. 15982 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15983 LookupQualifiedName(Previous, SearchDC); 15984 } else { 15985 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15986 LookupName(Previous, S); 15987 } 15988 } 15989 15990 // If we have a known previous declaration to use, then use it. 15991 if (Previous.empty() && SkipBody && SkipBody->Previous) 15992 Previous.addDecl(SkipBody->Previous); 15993 15994 if (!Previous.empty()) { 15995 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15996 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15997 15998 // It's okay to have a tag decl in the same scope as a typedef 15999 // which hides a tag decl in the same scope. Finding this 16000 // insanity with a redeclaration lookup can only actually happen 16001 // in C++. 16002 // 16003 // This is also okay for elaborated-type-specifiers, which is 16004 // technically forbidden by the current standard but which is 16005 // okay according to the likely resolution of an open issue; 16006 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16007 if (getLangOpts().CPlusPlus) { 16008 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16009 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16010 TagDecl *Tag = TT->getDecl(); 16011 if (Tag->getDeclName() == Name && 16012 Tag->getDeclContext()->getRedeclContext() 16013 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16014 PrevDecl = Tag; 16015 Previous.clear(); 16016 Previous.addDecl(Tag); 16017 Previous.resolveKind(); 16018 } 16019 } 16020 } 16021 } 16022 16023 // If this is a redeclaration of a using shadow declaration, it must 16024 // declare a tag in the same context. In MSVC mode, we allow a 16025 // redefinition if either context is within the other. 16026 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16027 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16028 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16029 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16030 !(OldTag && isAcceptableTagRedeclContext( 16031 *this, OldTag->getDeclContext(), SearchDC))) { 16032 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16033 Diag(Shadow->getTargetDecl()->getLocation(), 16034 diag::note_using_decl_target); 16035 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16036 << 0; 16037 // Recover by ignoring the old declaration. 16038 Previous.clear(); 16039 goto CreateNewDecl; 16040 } 16041 } 16042 16043 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16044 // If this is a use of a previous tag, or if the tag is already declared 16045 // in the same scope (so that the definition/declaration completes or 16046 // rementions the tag), reuse the decl. 16047 if (TUK == TUK_Reference || TUK == TUK_Friend || 16048 isDeclInScope(DirectPrevDecl, SearchDC, S, 16049 SS.isNotEmpty() || isMemberSpecialization)) { 16050 // Make sure that this wasn't declared as an enum and now used as a 16051 // struct or something similar. 16052 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16053 TUK == TUK_Definition, KWLoc, 16054 Name)) { 16055 bool SafeToContinue 16056 = (PrevTagDecl->getTagKind() != TTK_Enum && 16057 Kind != TTK_Enum); 16058 if (SafeToContinue) 16059 Diag(KWLoc, diag::err_use_with_wrong_tag) 16060 << Name 16061 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16062 PrevTagDecl->getKindName()); 16063 else 16064 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16065 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16066 16067 if (SafeToContinue) 16068 Kind = PrevTagDecl->getTagKind(); 16069 else { 16070 // Recover by making this an anonymous redefinition. 16071 Name = nullptr; 16072 Previous.clear(); 16073 Invalid = true; 16074 } 16075 } 16076 16077 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16078 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16079 if (TUK == TUK_Reference || TUK == TUK_Friend) 16080 return PrevTagDecl; 16081 16082 QualType EnumUnderlyingTy; 16083 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16084 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16085 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16086 EnumUnderlyingTy = QualType(T, 0); 16087 16088 // All conflicts with previous declarations are recovered by 16089 // returning the previous declaration, unless this is a definition, 16090 // in which case we want the caller to bail out. 16091 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16092 ScopedEnum, EnumUnderlyingTy, 16093 IsFixed, PrevEnum)) 16094 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16095 } 16096 16097 // C++11 [class.mem]p1: 16098 // A member shall not be declared twice in the member-specification, 16099 // except that a nested class or member class template can be declared 16100 // and then later defined. 16101 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16102 S->isDeclScope(PrevDecl)) { 16103 Diag(NameLoc, diag::ext_member_redeclared); 16104 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16105 } 16106 16107 if (!Invalid) { 16108 // If this is a use, just return the declaration we found, unless 16109 // we have attributes. 16110 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16111 if (!Attrs.empty()) { 16112 // FIXME: Diagnose these attributes. For now, we create a new 16113 // declaration to hold them. 16114 } else if (TUK == TUK_Reference && 16115 (PrevTagDecl->getFriendObjectKind() == 16116 Decl::FOK_Undeclared || 16117 PrevDecl->getOwningModule() != getCurrentModule()) && 16118 SS.isEmpty()) { 16119 // This declaration is a reference to an existing entity, but 16120 // has different visibility from that entity: it either makes 16121 // a friend visible or it makes a type visible in a new module. 16122 // In either case, create a new declaration. We only do this if 16123 // the declaration would have meant the same thing if no prior 16124 // declaration were found, that is, if it was found in the same 16125 // scope where we would have injected a declaration. 16126 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16127 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16128 return PrevTagDecl; 16129 // This is in the injected scope, create a new declaration in 16130 // that scope. 16131 S = getTagInjectionScope(S, getLangOpts()); 16132 } else { 16133 return PrevTagDecl; 16134 } 16135 } 16136 16137 // Diagnose attempts to redefine a tag. 16138 if (TUK == TUK_Definition) { 16139 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16140 // If we're defining a specialization and the previous definition 16141 // is from an implicit instantiation, don't emit an error 16142 // here; we'll catch this in the general case below. 16143 bool IsExplicitSpecializationAfterInstantiation = false; 16144 if (isMemberSpecialization) { 16145 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16146 IsExplicitSpecializationAfterInstantiation = 16147 RD->getTemplateSpecializationKind() != 16148 TSK_ExplicitSpecialization; 16149 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16150 IsExplicitSpecializationAfterInstantiation = 16151 ED->getTemplateSpecializationKind() != 16152 TSK_ExplicitSpecialization; 16153 } 16154 16155 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16156 // not keep more that one definition around (merge them). However, 16157 // ensure the decl passes the structural compatibility check in 16158 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16159 NamedDecl *Hidden = nullptr; 16160 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16161 // There is a definition of this tag, but it is not visible. We 16162 // explicitly make use of C++'s one definition rule here, and 16163 // assume that this definition is identical to the hidden one 16164 // we already have. Make the existing definition visible and 16165 // use it in place of this one. 16166 if (!getLangOpts().CPlusPlus) { 16167 // Postpone making the old definition visible until after we 16168 // complete parsing the new one and do the structural 16169 // comparison. 16170 SkipBody->CheckSameAsPrevious = true; 16171 SkipBody->New = createTagFromNewDecl(); 16172 SkipBody->Previous = Def; 16173 return Def; 16174 } else { 16175 SkipBody->ShouldSkip = true; 16176 SkipBody->Previous = Def; 16177 makeMergedDefinitionVisible(Hidden); 16178 // Carry on and handle it like a normal definition. We'll 16179 // skip starting the definitiion later. 16180 } 16181 } else if (!IsExplicitSpecializationAfterInstantiation) { 16182 // A redeclaration in function prototype scope in C isn't 16183 // visible elsewhere, so merely issue a warning. 16184 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16185 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16186 else 16187 Diag(NameLoc, diag::err_redefinition) << Name; 16188 notePreviousDefinition(Def, 16189 NameLoc.isValid() ? NameLoc : KWLoc); 16190 // If this is a redefinition, recover by making this 16191 // struct be anonymous, which will make any later 16192 // references get the previous definition. 16193 Name = nullptr; 16194 Previous.clear(); 16195 Invalid = true; 16196 } 16197 } else { 16198 // If the type is currently being defined, complain 16199 // about a nested redefinition. 16200 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16201 if (TD->isBeingDefined()) { 16202 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16203 Diag(PrevTagDecl->getLocation(), 16204 diag::note_previous_definition); 16205 Name = nullptr; 16206 Previous.clear(); 16207 Invalid = true; 16208 } 16209 } 16210 16211 // Okay, this is definition of a previously declared or referenced 16212 // tag. We're going to create a new Decl for it. 16213 } 16214 16215 // Okay, we're going to make a redeclaration. If this is some kind 16216 // of reference, make sure we build the redeclaration in the same DC 16217 // as the original, and ignore the current access specifier. 16218 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16219 SearchDC = PrevTagDecl->getDeclContext(); 16220 AS = AS_none; 16221 } 16222 } 16223 // If we get here we have (another) forward declaration or we 16224 // have a definition. Just create a new decl. 16225 16226 } else { 16227 // If we get here, this is a definition of a new tag type in a nested 16228 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16229 // new decl/type. We set PrevDecl to NULL so that the entities 16230 // have distinct types. 16231 Previous.clear(); 16232 } 16233 // If we get here, we're going to create a new Decl. If PrevDecl 16234 // is non-NULL, it's a definition of the tag declared by 16235 // PrevDecl. If it's NULL, we have a new definition. 16236 16237 // Otherwise, PrevDecl is not a tag, but was found with tag 16238 // lookup. This is only actually possible in C++, where a few 16239 // things like templates still live in the tag namespace. 16240 } else { 16241 // Use a better diagnostic if an elaborated-type-specifier 16242 // found the wrong kind of type on the first 16243 // (non-redeclaration) lookup. 16244 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16245 !Previous.isForRedeclaration()) { 16246 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16247 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16248 << Kind; 16249 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16250 Invalid = true; 16251 16252 // Otherwise, only diagnose if the declaration is in scope. 16253 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16254 SS.isNotEmpty() || isMemberSpecialization)) { 16255 // do nothing 16256 16257 // Diagnose implicit declarations introduced by elaborated types. 16258 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16259 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16260 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16261 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16262 Invalid = true; 16263 16264 // Otherwise it's a declaration. Call out a particularly common 16265 // case here. 16266 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16267 unsigned Kind = 0; 16268 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16269 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16270 << Name << Kind << TND->getUnderlyingType(); 16271 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16272 Invalid = true; 16273 16274 // Otherwise, diagnose. 16275 } else { 16276 // The tag name clashes with something else in the target scope, 16277 // issue an error and recover by making this tag be anonymous. 16278 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16279 notePreviousDefinition(PrevDecl, NameLoc); 16280 Name = nullptr; 16281 Invalid = true; 16282 } 16283 16284 // The existing declaration isn't relevant to us; we're in a 16285 // new scope, so clear out the previous declaration. 16286 Previous.clear(); 16287 } 16288 } 16289 16290 CreateNewDecl: 16291 16292 TagDecl *PrevDecl = nullptr; 16293 if (Previous.isSingleResult()) 16294 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16295 16296 // If there is an identifier, use the location of the identifier as the 16297 // location of the decl, otherwise use the location of the struct/union 16298 // keyword. 16299 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16300 16301 // Otherwise, create a new declaration. If there is a previous 16302 // declaration of the same entity, the two will be linked via 16303 // PrevDecl. 16304 TagDecl *New; 16305 16306 if (Kind == TTK_Enum) { 16307 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16308 // enum X { A, B, C } D; D should chain to X. 16309 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16310 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16311 ScopedEnumUsesClassTag, IsFixed); 16312 16313 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16314 StdAlignValT = cast<EnumDecl>(New); 16315 16316 // If this is an undefined enum, warn. 16317 if (TUK != TUK_Definition && !Invalid) { 16318 TagDecl *Def; 16319 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16320 // C++0x: 7.2p2: opaque-enum-declaration. 16321 // Conflicts are diagnosed above. Do nothing. 16322 } 16323 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16324 Diag(Loc, diag::ext_forward_ref_enum_def) 16325 << New; 16326 Diag(Def->getLocation(), diag::note_previous_definition); 16327 } else { 16328 unsigned DiagID = diag::ext_forward_ref_enum; 16329 if (getLangOpts().MSVCCompat) 16330 DiagID = diag::ext_ms_forward_ref_enum; 16331 else if (getLangOpts().CPlusPlus) 16332 DiagID = diag::err_forward_ref_enum; 16333 Diag(Loc, DiagID); 16334 } 16335 } 16336 16337 if (EnumUnderlying) { 16338 EnumDecl *ED = cast<EnumDecl>(New); 16339 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16340 ED->setIntegerTypeSourceInfo(TI); 16341 else 16342 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16343 ED->setPromotionType(ED->getIntegerType()); 16344 assert(ED->isComplete() && "enum with type should be complete"); 16345 } 16346 } else { 16347 // struct/union/class 16348 16349 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16350 // struct X { int A; } D; D should chain to X. 16351 if (getLangOpts().CPlusPlus) { 16352 // FIXME: Look for a way to use RecordDecl for simple structs. 16353 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16354 cast_or_null<CXXRecordDecl>(PrevDecl)); 16355 16356 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16357 StdBadAlloc = cast<CXXRecordDecl>(New); 16358 } else 16359 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16360 cast_or_null<RecordDecl>(PrevDecl)); 16361 } 16362 16363 // C++11 [dcl.type]p3: 16364 // A type-specifier-seq shall not define a class or enumeration [...]. 16365 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16366 TUK == TUK_Definition) { 16367 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16368 << Context.getTagDeclType(New); 16369 Invalid = true; 16370 } 16371 16372 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16373 DC->getDeclKind() == Decl::Enum) { 16374 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16375 << Context.getTagDeclType(New); 16376 Invalid = true; 16377 } 16378 16379 // Maybe add qualifier info. 16380 if (SS.isNotEmpty()) { 16381 if (SS.isSet()) { 16382 // If this is either a declaration or a definition, check the 16383 // nested-name-specifier against the current context. 16384 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16385 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16386 isMemberSpecialization)) 16387 Invalid = true; 16388 16389 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16390 if (TemplateParameterLists.size() > 0) { 16391 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16392 } 16393 } 16394 else 16395 Invalid = true; 16396 } 16397 16398 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16399 // Add alignment attributes if necessary; these attributes are checked when 16400 // the ASTContext lays out the structure. 16401 // 16402 // It is important for implementing the correct semantics that this 16403 // happen here (in ActOnTag). The #pragma pack stack is 16404 // maintained as a result of parser callbacks which can occur at 16405 // many points during the parsing of a struct declaration (because 16406 // the #pragma tokens are effectively skipped over during the 16407 // parsing of the struct). 16408 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16409 AddAlignmentAttributesForRecord(RD); 16410 AddMsStructLayoutForRecord(RD); 16411 } 16412 } 16413 16414 if (ModulePrivateLoc.isValid()) { 16415 if (isMemberSpecialization) 16416 Diag(New->getLocation(), diag::err_module_private_specialization) 16417 << 2 16418 << FixItHint::CreateRemoval(ModulePrivateLoc); 16419 // __module_private__ does not apply to local classes. However, we only 16420 // diagnose this as an error when the declaration specifiers are 16421 // freestanding. Here, we just ignore the __module_private__. 16422 else if (!SearchDC->isFunctionOrMethod()) 16423 New->setModulePrivate(); 16424 } 16425 16426 // If this is a specialization of a member class (of a class template), 16427 // check the specialization. 16428 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16429 Invalid = true; 16430 16431 // If we're declaring or defining a tag in function prototype scope in C, 16432 // note that this type can only be used within the function and add it to 16433 // the list of decls to inject into the function definition scope. 16434 if ((Name || Kind == TTK_Enum) && 16435 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16436 if (getLangOpts().CPlusPlus) { 16437 // C++ [dcl.fct]p6: 16438 // Types shall not be defined in return or parameter types. 16439 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16440 Diag(Loc, diag::err_type_defined_in_param_type) 16441 << Name; 16442 Invalid = true; 16443 } 16444 } else if (!PrevDecl) { 16445 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16446 } 16447 } 16448 16449 if (Invalid) 16450 New->setInvalidDecl(); 16451 16452 // Set the lexical context. If the tag has a C++ scope specifier, the 16453 // lexical context will be different from the semantic context. 16454 New->setLexicalDeclContext(CurContext); 16455 16456 // Mark this as a friend decl if applicable. 16457 // In Microsoft mode, a friend declaration also acts as a forward 16458 // declaration so we always pass true to setObjectOfFriendDecl to make 16459 // the tag name visible. 16460 if (TUK == TUK_Friend) 16461 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16462 16463 // Set the access specifier. 16464 if (!Invalid && SearchDC->isRecord()) 16465 SetMemberAccessSpecifier(New, PrevDecl, AS); 16466 16467 if (PrevDecl) 16468 CheckRedeclarationModuleOwnership(New, PrevDecl); 16469 16470 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16471 New->startDefinition(); 16472 16473 ProcessDeclAttributeList(S, New, Attrs); 16474 AddPragmaAttributes(S, New); 16475 16476 // If this has an identifier, add it to the scope stack. 16477 if (TUK == TUK_Friend) { 16478 // We might be replacing an existing declaration in the lookup tables; 16479 // if so, borrow its access specifier. 16480 if (PrevDecl) 16481 New->setAccess(PrevDecl->getAccess()); 16482 16483 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16484 DC->makeDeclVisibleInContext(New); 16485 if (Name) // can be null along some error paths 16486 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16487 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16488 } else if (Name) { 16489 S = getNonFieldDeclScope(S); 16490 PushOnScopeChains(New, S, true); 16491 } else { 16492 CurContext->addDecl(New); 16493 } 16494 16495 // If this is the C FILE type, notify the AST context. 16496 if (IdentifierInfo *II = New->getIdentifier()) 16497 if (!New->isInvalidDecl() && 16498 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16499 II->isStr("FILE")) 16500 Context.setFILEDecl(New); 16501 16502 if (PrevDecl) 16503 mergeDeclAttributes(New, PrevDecl); 16504 16505 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16506 inferGslOwnerPointerAttribute(CXXRD); 16507 16508 // If there's a #pragma GCC visibility in scope, set the visibility of this 16509 // record. 16510 AddPushedVisibilityAttribute(New); 16511 16512 if (isMemberSpecialization && !New->isInvalidDecl()) 16513 CompleteMemberSpecialization(New, Previous); 16514 16515 OwnedDecl = true; 16516 // In C++, don't return an invalid declaration. We can't recover well from 16517 // the cases where we make the type anonymous. 16518 if (Invalid && getLangOpts().CPlusPlus) { 16519 if (New->isBeingDefined()) 16520 if (auto RD = dyn_cast<RecordDecl>(New)) 16521 RD->completeDefinition(); 16522 return nullptr; 16523 } else if (SkipBody && SkipBody->ShouldSkip) { 16524 return SkipBody->Previous; 16525 } else { 16526 return New; 16527 } 16528 } 16529 16530 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16531 AdjustDeclIfTemplate(TagD); 16532 TagDecl *Tag = cast<TagDecl>(TagD); 16533 16534 // Enter the tag context. 16535 PushDeclContext(S, Tag); 16536 16537 ActOnDocumentableDecl(TagD); 16538 16539 // If there's a #pragma GCC visibility in scope, set the visibility of this 16540 // record. 16541 AddPushedVisibilityAttribute(Tag); 16542 } 16543 16544 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16545 SkipBodyInfo &SkipBody) { 16546 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16547 return false; 16548 16549 // Make the previous decl visible. 16550 makeMergedDefinitionVisible(SkipBody.Previous); 16551 return true; 16552 } 16553 16554 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16555 assert(isa<ObjCContainerDecl>(IDecl) && 16556 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16557 DeclContext *OCD = cast<DeclContext>(IDecl); 16558 assert(OCD->getLexicalParent() == CurContext && 16559 "The next DeclContext should be lexically contained in the current one."); 16560 CurContext = OCD; 16561 return IDecl; 16562 } 16563 16564 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16565 SourceLocation FinalLoc, 16566 bool IsFinalSpelledSealed, 16567 bool IsAbstract, 16568 SourceLocation LBraceLoc) { 16569 AdjustDeclIfTemplate(TagD); 16570 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16571 16572 FieldCollector->StartClass(); 16573 16574 if (!Record->getIdentifier()) 16575 return; 16576 16577 if (IsAbstract) 16578 Record->markAbstract(); 16579 16580 if (FinalLoc.isValid()) { 16581 Record->addAttr(FinalAttr::Create( 16582 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16583 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16584 } 16585 // C++ [class]p2: 16586 // [...] The class-name is also inserted into the scope of the 16587 // class itself; this is known as the injected-class-name. For 16588 // purposes of access checking, the injected-class-name is treated 16589 // as if it were a public member name. 16590 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16591 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16592 Record->getLocation(), Record->getIdentifier(), 16593 /*PrevDecl=*/nullptr, 16594 /*DelayTypeCreation=*/true); 16595 Context.getTypeDeclType(InjectedClassName, Record); 16596 InjectedClassName->setImplicit(); 16597 InjectedClassName->setAccess(AS_public); 16598 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16599 InjectedClassName->setDescribedClassTemplate(Template); 16600 PushOnScopeChains(InjectedClassName, S); 16601 assert(InjectedClassName->isInjectedClassName() && 16602 "Broken injected-class-name"); 16603 } 16604 16605 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16606 SourceRange BraceRange) { 16607 AdjustDeclIfTemplate(TagD); 16608 TagDecl *Tag = cast<TagDecl>(TagD); 16609 Tag->setBraceRange(BraceRange); 16610 16611 // Make sure we "complete" the definition even it is invalid. 16612 if (Tag->isBeingDefined()) { 16613 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16614 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16615 RD->completeDefinition(); 16616 } 16617 16618 if (isa<CXXRecordDecl>(Tag)) { 16619 FieldCollector->FinishClass(); 16620 } 16621 16622 // Exit this scope of this tag's definition. 16623 PopDeclContext(); 16624 16625 if (getCurLexicalContext()->isObjCContainer() && 16626 Tag->getDeclContext()->isFileContext()) 16627 Tag->setTopLevelDeclInObjCContainer(); 16628 16629 // Notify the consumer that we've defined a tag. 16630 if (!Tag->isInvalidDecl()) 16631 Consumer.HandleTagDeclDefinition(Tag); 16632 16633 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16634 // from XLs and instead matches the XL #pragma pack(1) behavior. 16635 if (Context.getTargetInfo().getTriple().isOSAIX() && 16636 AlignPackStack.hasValue()) { 16637 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16638 // Only diagnose #pragma align(packed). 16639 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16640 return; 16641 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16642 if (!RD) 16643 return; 16644 // Only warn if there is at least 1 bitfield member. 16645 if (llvm::any_of(RD->fields(), 16646 [](const FieldDecl *FD) { return FD->isBitField(); })) 16647 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16648 } 16649 } 16650 16651 void Sema::ActOnObjCContainerFinishDefinition() { 16652 // Exit this scope of this interface definition. 16653 PopDeclContext(); 16654 } 16655 16656 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16657 assert(DC == CurContext && "Mismatch of container contexts"); 16658 OriginalLexicalContext = DC; 16659 ActOnObjCContainerFinishDefinition(); 16660 } 16661 16662 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16663 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16664 OriginalLexicalContext = nullptr; 16665 } 16666 16667 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16668 AdjustDeclIfTemplate(TagD); 16669 TagDecl *Tag = cast<TagDecl>(TagD); 16670 Tag->setInvalidDecl(); 16671 16672 // Make sure we "complete" the definition even it is invalid. 16673 if (Tag->isBeingDefined()) { 16674 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16675 RD->completeDefinition(); 16676 } 16677 16678 // We're undoing ActOnTagStartDefinition here, not 16679 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16680 // the FieldCollector. 16681 16682 PopDeclContext(); 16683 } 16684 16685 // Note that FieldName may be null for anonymous bitfields. 16686 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16687 IdentifierInfo *FieldName, 16688 QualType FieldTy, bool IsMsStruct, 16689 Expr *BitWidth, bool *ZeroWidth) { 16690 assert(BitWidth); 16691 if (BitWidth->containsErrors()) 16692 return ExprError(); 16693 16694 // Default to true; that shouldn't confuse checks for emptiness 16695 if (ZeroWidth) 16696 *ZeroWidth = true; 16697 16698 // C99 6.7.2.1p4 - verify the field type. 16699 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16700 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16701 // Handle incomplete and sizeless types with a specific error. 16702 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16703 diag::err_field_incomplete_or_sizeless)) 16704 return ExprError(); 16705 if (FieldName) 16706 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16707 << FieldName << FieldTy << BitWidth->getSourceRange(); 16708 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16709 << FieldTy << BitWidth->getSourceRange(); 16710 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16711 UPPC_BitFieldWidth)) 16712 return ExprError(); 16713 16714 // If the bit-width is type- or value-dependent, don't try to check 16715 // it now. 16716 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16717 return BitWidth; 16718 16719 llvm::APSInt Value; 16720 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16721 if (ICE.isInvalid()) 16722 return ICE; 16723 BitWidth = ICE.get(); 16724 16725 if (Value != 0 && ZeroWidth) 16726 *ZeroWidth = false; 16727 16728 // Zero-width bitfield is ok for anonymous field. 16729 if (Value == 0 && FieldName) 16730 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16731 16732 if (Value.isSigned() && Value.isNegative()) { 16733 if (FieldName) 16734 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16735 << FieldName << toString(Value, 10); 16736 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16737 << toString(Value, 10); 16738 } 16739 16740 // The size of the bit-field must not exceed our maximum permitted object 16741 // size. 16742 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16743 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16744 << !FieldName << FieldName << toString(Value, 10); 16745 } 16746 16747 if (!FieldTy->isDependentType()) { 16748 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16749 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16750 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16751 16752 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16753 // ABI. 16754 bool CStdConstraintViolation = 16755 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16756 bool MSBitfieldViolation = 16757 Value.ugt(TypeStorageSize) && 16758 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16759 if (CStdConstraintViolation || MSBitfieldViolation) { 16760 unsigned DiagWidth = 16761 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16762 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16763 << (bool)FieldName << FieldName << toString(Value, 10) 16764 << !CStdConstraintViolation << DiagWidth; 16765 } 16766 16767 // Warn on types where the user might conceivably expect to get all 16768 // specified bits as value bits: that's all integral types other than 16769 // 'bool'. 16770 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16771 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16772 << FieldName << toString(Value, 10) 16773 << (unsigned)TypeWidth; 16774 } 16775 } 16776 16777 return BitWidth; 16778 } 16779 16780 /// ActOnField - Each field of a C struct/union is passed into this in order 16781 /// to create a FieldDecl object for it. 16782 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16783 Declarator &D, Expr *BitfieldWidth) { 16784 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16785 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16786 /*InitStyle=*/ICIS_NoInit, AS_public); 16787 return Res; 16788 } 16789 16790 /// HandleField - Analyze a field of a C struct or a C++ data member. 16791 /// 16792 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16793 SourceLocation DeclStart, 16794 Declarator &D, Expr *BitWidth, 16795 InClassInitStyle InitStyle, 16796 AccessSpecifier AS) { 16797 if (D.isDecompositionDeclarator()) { 16798 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16799 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16800 << Decomp.getSourceRange(); 16801 return nullptr; 16802 } 16803 16804 IdentifierInfo *II = D.getIdentifier(); 16805 SourceLocation Loc = DeclStart; 16806 if (II) Loc = D.getIdentifierLoc(); 16807 16808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16809 QualType T = TInfo->getType(); 16810 if (getLangOpts().CPlusPlus) { 16811 CheckExtraCXXDefaultArguments(D); 16812 16813 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16814 UPPC_DataMemberType)) { 16815 D.setInvalidType(); 16816 T = Context.IntTy; 16817 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16818 } 16819 } 16820 16821 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16822 16823 if (D.getDeclSpec().isInlineSpecified()) 16824 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16825 << getLangOpts().CPlusPlus17; 16826 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16827 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16828 diag::err_invalid_thread) 16829 << DeclSpec::getSpecifierName(TSCS); 16830 16831 // Check to see if this name was declared as a member previously 16832 NamedDecl *PrevDecl = nullptr; 16833 LookupResult Previous(*this, II, Loc, LookupMemberName, 16834 ForVisibleRedeclaration); 16835 LookupName(Previous, S); 16836 switch (Previous.getResultKind()) { 16837 case LookupResult::Found: 16838 case LookupResult::FoundUnresolvedValue: 16839 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16840 break; 16841 16842 case LookupResult::FoundOverloaded: 16843 PrevDecl = Previous.getRepresentativeDecl(); 16844 break; 16845 16846 case LookupResult::NotFound: 16847 case LookupResult::NotFoundInCurrentInstantiation: 16848 case LookupResult::Ambiguous: 16849 break; 16850 } 16851 Previous.suppressDiagnostics(); 16852 16853 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16854 // Maybe we will complain about the shadowed template parameter. 16855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16856 // Just pretend that we didn't see the previous declaration. 16857 PrevDecl = nullptr; 16858 } 16859 16860 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16861 PrevDecl = nullptr; 16862 16863 bool Mutable 16864 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16865 SourceLocation TSSL = D.getBeginLoc(); 16866 FieldDecl *NewFD 16867 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16868 TSSL, AS, PrevDecl, &D); 16869 16870 if (NewFD->isInvalidDecl()) 16871 Record->setInvalidDecl(); 16872 16873 if (D.getDeclSpec().isModulePrivateSpecified()) 16874 NewFD->setModulePrivate(); 16875 16876 if (NewFD->isInvalidDecl() && PrevDecl) { 16877 // Don't introduce NewFD into scope; there's already something 16878 // with the same name in the same scope. 16879 } else if (II) { 16880 PushOnScopeChains(NewFD, S); 16881 } else 16882 Record->addDecl(NewFD); 16883 16884 return NewFD; 16885 } 16886 16887 /// Build a new FieldDecl and check its well-formedness. 16888 /// 16889 /// This routine builds a new FieldDecl given the fields name, type, 16890 /// record, etc. \p PrevDecl should refer to any previous declaration 16891 /// with the same name and in the same scope as the field to be 16892 /// created. 16893 /// 16894 /// \returns a new FieldDecl. 16895 /// 16896 /// \todo The Declarator argument is a hack. It will be removed once 16897 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16898 TypeSourceInfo *TInfo, 16899 RecordDecl *Record, SourceLocation Loc, 16900 bool Mutable, Expr *BitWidth, 16901 InClassInitStyle InitStyle, 16902 SourceLocation TSSL, 16903 AccessSpecifier AS, NamedDecl *PrevDecl, 16904 Declarator *D) { 16905 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16906 bool InvalidDecl = false; 16907 if (D) InvalidDecl = D->isInvalidType(); 16908 16909 // If we receive a broken type, recover by assuming 'int' and 16910 // marking this declaration as invalid. 16911 if (T.isNull() || T->containsErrors()) { 16912 InvalidDecl = true; 16913 T = Context.IntTy; 16914 } 16915 16916 QualType EltTy = Context.getBaseElementType(T); 16917 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16918 if (RequireCompleteSizedType(Loc, EltTy, 16919 diag::err_field_incomplete_or_sizeless)) { 16920 // Fields of incomplete type force their record to be invalid. 16921 Record->setInvalidDecl(); 16922 InvalidDecl = true; 16923 } else { 16924 NamedDecl *Def; 16925 EltTy->isIncompleteType(&Def); 16926 if (Def && Def->isInvalidDecl()) { 16927 Record->setInvalidDecl(); 16928 InvalidDecl = true; 16929 } 16930 } 16931 } 16932 16933 // TR 18037 does not allow fields to be declared with address space 16934 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16935 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16936 Diag(Loc, diag::err_field_with_address_space); 16937 Record->setInvalidDecl(); 16938 InvalidDecl = true; 16939 } 16940 16941 if (LangOpts.OpenCL) { 16942 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16943 // used as structure or union field: image, sampler, event or block types. 16944 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16945 T->isBlockPointerType()) { 16946 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16947 Record->setInvalidDecl(); 16948 InvalidDecl = true; 16949 } 16950 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 16951 // is enabled. 16952 if (BitWidth && !getOpenCLOptions().isAvailableOption( 16953 "__cl_clang_bitfields", LangOpts)) { 16954 Diag(Loc, diag::err_opencl_bitfields); 16955 InvalidDecl = true; 16956 } 16957 } 16958 16959 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16960 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16961 T.hasQualifiers()) { 16962 InvalidDecl = true; 16963 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16964 } 16965 16966 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16967 // than a variably modified type. 16968 if (!InvalidDecl && T->isVariablyModifiedType()) { 16969 if (!tryToFixVariablyModifiedVarType( 16970 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16971 InvalidDecl = true; 16972 } 16973 16974 // Fields can not have abstract class types 16975 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16976 diag::err_abstract_type_in_decl, 16977 AbstractFieldType)) 16978 InvalidDecl = true; 16979 16980 bool ZeroWidth = false; 16981 if (InvalidDecl) 16982 BitWidth = nullptr; 16983 // If this is declared as a bit-field, check the bit-field. 16984 if (BitWidth) { 16985 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16986 &ZeroWidth).get(); 16987 if (!BitWidth) { 16988 InvalidDecl = true; 16989 BitWidth = nullptr; 16990 ZeroWidth = false; 16991 } 16992 } 16993 16994 // Check that 'mutable' is consistent with the type of the declaration. 16995 if (!InvalidDecl && Mutable) { 16996 unsigned DiagID = 0; 16997 if (T->isReferenceType()) 16998 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16999 : diag::err_mutable_reference; 17000 else if (T.isConstQualified()) 17001 DiagID = diag::err_mutable_const; 17002 17003 if (DiagID) { 17004 SourceLocation ErrLoc = Loc; 17005 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17006 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17007 Diag(ErrLoc, DiagID); 17008 if (DiagID != diag::ext_mutable_reference) { 17009 Mutable = false; 17010 InvalidDecl = true; 17011 } 17012 } 17013 } 17014 17015 // C++11 [class.union]p8 (DR1460): 17016 // At most one variant member of a union may have a 17017 // brace-or-equal-initializer. 17018 if (InitStyle != ICIS_NoInit) 17019 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17020 17021 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17022 BitWidth, Mutable, InitStyle); 17023 if (InvalidDecl) 17024 NewFD->setInvalidDecl(); 17025 17026 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17027 Diag(Loc, diag::err_duplicate_member) << II; 17028 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17029 NewFD->setInvalidDecl(); 17030 } 17031 17032 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17033 if (Record->isUnion()) { 17034 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17035 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17036 if (RDecl->getDefinition()) { 17037 // C++ [class.union]p1: An object of a class with a non-trivial 17038 // constructor, a non-trivial copy constructor, a non-trivial 17039 // destructor, or a non-trivial copy assignment operator 17040 // cannot be a member of a union, nor can an array of such 17041 // objects. 17042 if (CheckNontrivialField(NewFD)) 17043 NewFD->setInvalidDecl(); 17044 } 17045 } 17046 17047 // C++ [class.union]p1: If a union contains a member of reference type, 17048 // the program is ill-formed, except when compiling with MSVC extensions 17049 // enabled. 17050 if (EltTy->isReferenceType()) { 17051 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17052 diag::ext_union_member_of_reference_type : 17053 diag::err_union_member_of_reference_type) 17054 << NewFD->getDeclName() << EltTy; 17055 if (!getLangOpts().MicrosoftExt) 17056 NewFD->setInvalidDecl(); 17057 } 17058 } 17059 } 17060 17061 // FIXME: We need to pass in the attributes given an AST 17062 // representation, not a parser representation. 17063 if (D) { 17064 // FIXME: The current scope is almost... but not entirely... correct here. 17065 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17066 17067 if (NewFD->hasAttrs()) 17068 CheckAlignasUnderalignment(NewFD); 17069 } 17070 17071 // In auto-retain/release, infer strong retension for fields of 17072 // retainable type. 17073 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17074 NewFD->setInvalidDecl(); 17075 17076 if (T.isObjCGCWeak()) 17077 Diag(Loc, diag::warn_attribute_weak_on_field); 17078 17079 // PPC MMA non-pointer types are not allowed as field types. 17080 if (Context.getTargetInfo().getTriple().isPPC64() && 17081 CheckPPCMMAType(T, NewFD->getLocation())) 17082 NewFD->setInvalidDecl(); 17083 17084 NewFD->setAccess(AS); 17085 return NewFD; 17086 } 17087 17088 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17089 assert(FD); 17090 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17091 17092 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17093 return false; 17094 17095 QualType EltTy = Context.getBaseElementType(FD->getType()); 17096 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17097 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17098 if (RDecl->getDefinition()) { 17099 // We check for copy constructors before constructors 17100 // because otherwise we'll never get complaints about 17101 // copy constructors. 17102 17103 CXXSpecialMember member = CXXInvalid; 17104 // We're required to check for any non-trivial constructors. Since the 17105 // implicit default constructor is suppressed if there are any 17106 // user-declared constructors, we just need to check that there is a 17107 // trivial default constructor and a trivial copy constructor. (We don't 17108 // worry about move constructors here, since this is a C++98 check.) 17109 if (RDecl->hasNonTrivialCopyConstructor()) 17110 member = CXXCopyConstructor; 17111 else if (!RDecl->hasTrivialDefaultConstructor()) 17112 member = CXXDefaultConstructor; 17113 else if (RDecl->hasNonTrivialCopyAssignment()) 17114 member = CXXCopyAssignment; 17115 else if (RDecl->hasNonTrivialDestructor()) 17116 member = CXXDestructor; 17117 17118 if (member != CXXInvalid) { 17119 if (!getLangOpts().CPlusPlus11 && 17120 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17121 // Objective-C++ ARC: it is an error to have a non-trivial field of 17122 // a union. However, system headers in Objective-C programs 17123 // occasionally have Objective-C lifetime objects within unions, 17124 // and rather than cause the program to fail, we make those 17125 // members unavailable. 17126 SourceLocation Loc = FD->getLocation(); 17127 if (getSourceManager().isInSystemHeader(Loc)) { 17128 if (!FD->hasAttr<UnavailableAttr>()) 17129 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17130 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17131 return false; 17132 } 17133 } 17134 17135 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17136 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17137 diag::err_illegal_union_or_anon_struct_member) 17138 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17139 DiagnoseNontrivial(RDecl, member); 17140 return !getLangOpts().CPlusPlus11; 17141 } 17142 } 17143 } 17144 17145 return false; 17146 } 17147 17148 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17149 /// AST enum value. 17150 static ObjCIvarDecl::AccessControl 17151 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17152 switch (ivarVisibility) { 17153 default: llvm_unreachable("Unknown visitibility kind"); 17154 case tok::objc_private: return ObjCIvarDecl::Private; 17155 case tok::objc_public: return ObjCIvarDecl::Public; 17156 case tok::objc_protected: return ObjCIvarDecl::Protected; 17157 case tok::objc_package: return ObjCIvarDecl::Package; 17158 } 17159 } 17160 17161 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17162 /// in order to create an IvarDecl object for it. 17163 Decl *Sema::ActOnIvar(Scope *S, 17164 SourceLocation DeclStart, 17165 Declarator &D, Expr *BitfieldWidth, 17166 tok::ObjCKeywordKind Visibility) { 17167 17168 IdentifierInfo *II = D.getIdentifier(); 17169 Expr *BitWidth = (Expr*)BitfieldWidth; 17170 SourceLocation Loc = DeclStart; 17171 if (II) Loc = D.getIdentifierLoc(); 17172 17173 // FIXME: Unnamed fields can be handled in various different ways, for 17174 // example, unnamed unions inject all members into the struct namespace! 17175 17176 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17177 QualType T = TInfo->getType(); 17178 17179 if (BitWidth) { 17180 // 6.7.2.1p3, 6.7.2.1p4 17181 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17182 if (!BitWidth) 17183 D.setInvalidType(); 17184 } else { 17185 // Not a bitfield. 17186 17187 // validate II. 17188 17189 } 17190 if (T->isReferenceType()) { 17191 Diag(Loc, diag::err_ivar_reference_type); 17192 D.setInvalidType(); 17193 } 17194 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17195 // than a variably modified type. 17196 else if (T->isVariablyModifiedType()) { 17197 if (!tryToFixVariablyModifiedVarType( 17198 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17199 D.setInvalidType(); 17200 } 17201 17202 // Get the visibility (access control) for this ivar. 17203 ObjCIvarDecl::AccessControl ac = 17204 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17205 : ObjCIvarDecl::None; 17206 // Must set ivar's DeclContext to its enclosing interface. 17207 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17208 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17209 return nullptr; 17210 ObjCContainerDecl *EnclosingContext; 17211 if (ObjCImplementationDecl *IMPDecl = 17212 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17213 if (LangOpts.ObjCRuntime.isFragile()) { 17214 // Case of ivar declared in an implementation. Context is that of its class. 17215 EnclosingContext = IMPDecl->getClassInterface(); 17216 assert(EnclosingContext && "Implementation has no class interface!"); 17217 } 17218 else 17219 EnclosingContext = EnclosingDecl; 17220 } else { 17221 if (ObjCCategoryDecl *CDecl = 17222 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17223 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17224 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17225 return nullptr; 17226 } 17227 } 17228 EnclosingContext = EnclosingDecl; 17229 } 17230 17231 // Construct the decl. 17232 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17233 DeclStart, Loc, II, T, 17234 TInfo, ac, (Expr *)BitfieldWidth); 17235 17236 if (II) { 17237 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17238 ForVisibleRedeclaration); 17239 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17240 && !isa<TagDecl>(PrevDecl)) { 17241 Diag(Loc, diag::err_duplicate_member) << II; 17242 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17243 NewID->setInvalidDecl(); 17244 } 17245 } 17246 17247 // Process attributes attached to the ivar. 17248 ProcessDeclAttributes(S, NewID, D); 17249 17250 if (D.isInvalidType()) 17251 NewID->setInvalidDecl(); 17252 17253 // In ARC, infer 'retaining' for ivars of retainable type. 17254 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17255 NewID->setInvalidDecl(); 17256 17257 if (D.getDeclSpec().isModulePrivateSpecified()) 17258 NewID->setModulePrivate(); 17259 17260 if (II) { 17261 // FIXME: When interfaces are DeclContexts, we'll need to add 17262 // these to the interface. 17263 S->AddDecl(NewID); 17264 IdResolver.AddDecl(NewID); 17265 } 17266 17267 if (LangOpts.ObjCRuntime.isNonFragile() && 17268 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17269 Diag(Loc, diag::warn_ivars_in_interface); 17270 17271 return NewID; 17272 } 17273 17274 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17275 /// class and class extensions. For every class \@interface and class 17276 /// extension \@interface, if the last ivar is a bitfield of any type, 17277 /// then add an implicit `char :0` ivar to the end of that interface. 17278 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17279 SmallVectorImpl<Decl *> &AllIvarDecls) { 17280 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17281 return; 17282 17283 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17284 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17285 17286 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17287 return; 17288 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17289 if (!ID) { 17290 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17291 if (!CD->IsClassExtension()) 17292 return; 17293 } 17294 // No need to add this to end of @implementation. 17295 else 17296 return; 17297 } 17298 // All conditions are met. Add a new bitfield to the tail end of ivars. 17299 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17300 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17301 17302 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17303 DeclLoc, DeclLoc, nullptr, 17304 Context.CharTy, 17305 Context.getTrivialTypeSourceInfo(Context.CharTy, 17306 DeclLoc), 17307 ObjCIvarDecl::Private, BW, 17308 true); 17309 AllIvarDecls.push_back(Ivar); 17310 } 17311 17312 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17313 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17314 SourceLocation RBrac, 17315 const ParsedAttributesView &Attrs) { 17316 assert(EnclosingDecl && "missing record or interface decl"); 17317 17318 // If this is an Objective-C @implementation or category and we have 17319 // new fields here we should reset the layout of the interface since 17320 // it will now change. 17321 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17322 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17323 switch (DC->getKind()) { 17324 default: break; 17325 case Decl::ObjCCategory: 17326 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17327 break; 17328 case Decl::ObjCImplementation: 17329 Context. 17330 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17331 break; 17332 } 17333 } 17334 17335 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17336 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17337 17338 // Start counting up the number of named members; make sure to include 17339 // members of anonymous structs and unions in the total. 17340 unsigned NumNamedMembers = 0; 17341 if (Record) { 17342 for (const auto *I : Record->decls()) { 17343 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17344 if (IFD->getDeclName()) 17345 ++NumNamedMembers; 17346 } 17347 } 17348 17349 // Verify that all the fields are okay. 17350 SmallVector<FieldDecl*, 32> RecFields; 17351 17352 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17353 i != end; ++i) { 17354 FieldDecl *FD = cast<FieldDecl>(*i); 17355 17356 // Get the type for the field. 17357 const Type *FDTy = FD->getType().getTypePtr(); 17358 17359 if (!FD->isAnonymousStructOrUnion()) { 17360 // Remember all fields written by the user. 17361 RecFields.push_back(FD); 17362 } 17363 17364 // If the field is already invalid for some reason, don't emit more 17365 // diagnostics about it. 17366 if (FD->isInvalidDecl()) { 17367 EnclosingDecl->setInvalidDecl(); 17368 continue; 17369 } 17370 17371 // C99 6.7.2.1p2: 17372 // A structure or union shall not contain a member with 17373 // incomplete or function type (hence, a structure shall not 17374 // contain an instance of itself, but may contain a pointer to 17375 // an instance of itself), except that the last member of a 17376 // structure with more than one named member may have incomplete 17377 // array type; such a structure (and any union containing, 17378 // possibly recursively, a member that is such a structure) 17379 // shall not be a member of a structure or an element of an 17380 // array. 17381 bool IsLastField = (i + 1 == Fields.end()); 17382 if (FDTy->isFunctionType()) { 17383 // Field declared as a function. 17384 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17385 << FD->getDeclName(); 17386 FD->setInvalidDecl(); 17387 EnclosingDecl->setInvalidDecl(); 17388 continue; 17389 } else if (FDTy->isIncompleteArrayType() && 17390 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17391 if (Record) { 17392 // Flexible array member. 17393 // Microsoft and g++ is more permissive regarding flexible array. 17394 // It will accept flexible array in union and also 17395 // as the sole element of a struct/class. 17396 unsigned DiagID = 0; 17397 if (!Record->isUnion() && !IsLastField) { 17398 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17399 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17400 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17401 FD->setInvalidDecl(); 17402 EnclosingDecl->setInvalidDecl(); 17403 continue; 17404 } else if (Record->isUnion()) 17405 DiagID = getLangOpts().MicrosoftExt 17406 ? diag::ext_flexible_array_union_ms 17407 : getLangOpts().CPlusPlus 17408 ? diag::ext_flexible_array_union_gnu 17409 : diag::err_flexible_array_union; 17410 else if (NumNamedMembers < 1) 17411 DiagID = getLangOpts().MicrosoftExt 17412 ? diag::ext_flexible_array_empty_aggregate_ms 17413 : getLangOpts().CPlusPlus 17414 ? diag::ext_flexible_array_empty_aggregate_gnu 17415 : diag::err_flexible_array_empty_aggregate; 17416 17417 if (DiagID) 17418 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17419 << Record->getTagKind(); 17420 // While the layout of types that contain virtual bases is not specified 17421 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17422 // virtual bases after the derived members. This would make a flexible 17423 // array member declared at the end of an object not adjacent to the end 17424 // of the type. 17425 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17426 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17427 << FD->getDeclName() << Record->getTagKind(); 17428 if (!getLangOpts().C99) 17429 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17430 << FD->getDeclName() << Record->getTagKind(); 17431 17432 // If the element type has a non-trivial destructor, we would not 17433 // implicitly destroy the elements, so disallow it for now. 17434 // 17435 // FIXME: GCC allows this. We should probably either implicitly delete 17436 // the destructor of the containing class, or just allow this. 17437 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17438 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17439 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17440 << FD->getDeclName() << FD->getType(); 17441 FD->setInvalidDecl(); 17442 EnclosingDecl->setInvalidDecl(); 17443 continue; 17444 } 17445 // Okay, we have a legal flexible array member at the end of the struct. 17446 Record->setHasFlexibleArrayMember(true); 17447 } else { 17448 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17449 // unless they are followed by another ivar. That check is done 17450 // elsewhere, after synthesized ivars are known. 17451 } 17452 } else if (!FDTy->isDependentType() && 17453 RequireCompleteSizedType( 17454 FD->getLocation(), FD->getType(), 17455 diag::err_field_incomplete_or_sizeless)) { 17456 // Incomplete type 17457 FD->setInvalidDecl(); 17458 EnclosingDecl->setInvalidDecl(); 17459 continue; 17460 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17461 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17462 // A type which contains a flexible array member is considered to be a 17463 // flexible array member. 17464 Record->setHasFlexibleArrayMember(true); 17465 if (!Record->isUnion()) { 17466 // If this is a struct/class and this is not the last element, reject 17467 // it. Note that GCC supports variable sized arrays in the middle of 17468 // structures. 17469 if (!IsLastField) 17470 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17471 << FD->getDeclName() << FD->getType(); 17472 else { 17473 // We support flexible arrays at the end of structs in 17474 // other structs as an extension. 17475 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17476 << FD->getDeclName(); 17477 } 17478 } 17479 } 17480 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17481 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17482 diag::err_abstract_type_in_decl, 17483 AbstractIvarType)) { 17484 // Ivars can not have abstract class types 17485 FD->setInvalidDecl(); 17486 } 17487 if (Record && FDTTy->getDecl()->hasObjectMember()) 17488 Record->setHasObjectMember(true); 17489 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17490 Record->setHasVolatileMember(true); 17491 } else if (FDTy->isObjCObjectType()) { 17492 /// A field cannot be an Objective-c object 17493 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17494 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17495 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17496 FD->setType(T); 17497 } else if (Record && Record->isUnion() && 17498 FD->getType().hasNonTrivialObjCLifetime() && 17499 getSourceManager().isInSystemHeader(FD->getLocation()) && 17500 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17501 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17502 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17503 // For backward compatibility, fields of C unions declared in system 17504 // headers that have non-trivial ObjC ownership qualifications are marked 17505 // as unavailable unless the qualifier is explicit and __strong. This can 17506 // break ABI compatibility between programs compiled with ARC and MRR, but 17507 // is a better option than rejecting programs using those unions under 17508 // ARC. 17509 FD->addAttr(UnavailableAttr::CreateImplicit( 17510 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17511 FD->getLocation())); 17512 } else if (getLangOpts().ObjC && 17513 getLangOpts().getGC() != LangOptions::NonGC && Record && 17514 !Record->hasObjectMember()) { 17515 if (FD->getType()->isObjCObjectPointerType() || 17516 FD->getType().isObjCGCStrong()) 17517 Record->setHasObjectMember(true); 17518 else if (Context.getAsArrayType(FD->getType())) { 17519 QualType BaseType = Context.getBaseElementType(FD->getType()); 17520 if (BaseType->isRecordType() && 17521 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17522 Record->setHasObjectMember(true); 17523 else if (BaseType->isObjCObjectPointerType() || 17524 BaseType.isObjCGCStrong()) 17525 Record->setHasObjectMember(true); 17526 } 17527 } 17528 17529 if (Record && !getLangOpts().CPlusPlus && 17530 !shouldIgnoreForRecordTriviality(FD)) { 17531 QualType FT = FD->getType(); 17532 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17533 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17534 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17535 Record->isUnion()) 17536 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17537 } 17538 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17539 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17540 Record->setNonTrivialToPrimitiveCopy(true); 17541 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17542 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17543 } 17544 if (FT.isDestructedType()) { 17545 Record->setNonTrivialToPrimitiveDestroy(true); 17546 Record->setParamDestroyedInCallee(true); 17547 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17548 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17549 } 17550 17551 if (const auto *RT = FT->getAs<RecordType>()) { 17552 if (RT->getDecl()->getArgPassingRestrictions() == 17553 RecordDecl::APK_CanNeverPassInRegs) 17554 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17555 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17556 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17557 } 17558 17559 if (Record && FD->getType().isVolatileQualified()) 17560 Record->setHasVolatileMember(true); 17561 // Keep track of the number of named members. 17562 if (FD->getIdentifier()) 17563 ++NumNamedMembers; 17564 } 17565 17566 // Okay, we successfully defined 'Record'. 17567 if (Record) { 17568 bool Completed = false; 17569 if (CXXRecord) { 17570 if (!CXXRecord->isInvalidDecl()) { 17571 // Set access bits correctly on the directly-declared conversions. 17572 for (CXXRecordDecl::conversion_iterator 17573 I = CXXRecord->conversion_begin(), 17574 E = CXXRecord->conversion_end(); I != E; ++I) 17575 I.setAccess((*I)->getAccess()); 17576 } 17577 17578 // Add any implicitly-declared members to this class. 17579 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17580 17581 if (!CXXRecord->isDependentType()) { 17582 if (!CXXRecord->isInvalidDecl()) { 17583 // If we have virtual base classes, we may end up finding multiple 17584 // final overriders for a given virtual function. Check for this 17585 // problem now. 17586 if (CXXRecord->getNumVBases()) { 17587 CXXFinalOverriderMap FinalOverriders; 17588 CXXRecord->getFinalOverriders(FinalOverriders); 17589 17590 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17591 MEnd = FinalOverriders.end(); 17592 M != MEnd; ++M) { 17593 for (OverridingMethods::iterator SO = M->second.begin(), 17594 SOEnd = M->second.end(); 17595 SO != SOEnd; ++SO) { 17596 assert(SO->second.size() > 0 && 17597 "Virtual function without overriding functions?"); 17598 if (SO->second.size() == 1) 17599 continue; 17600 17601 // C++ [class.virtual]p2: 17602 // In a derived class, if a virtual member function of a base 17603 // class subobject has more than one final overrider the 17604 // program is ill-formed. 17605 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17606 << (const NamedDecl *)M->first << Record; 17607 Diag(M->first->getLocation(), 17608 diag::note_overridden_virtual_function); 17609 for (OverridingMethods::overriding_iterator 17610 OM = SO->second.begin(), 17611 OMEnd = SO->second.end(); 17612 OM != OMEnd; ++OM) 17613 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17614 << (const NamedDecl *)M->first << OM->Method->getParent(); 17615 17616 Record->setInvalidDecl(); 17617 } 17618 } 17619 CXXRecord->completeDefinition(&FinalOverriders); 17620 Completed = true; 17621 } 17622 } 17623 } 17624 } 17625 17626 if (!Completed) 17627 Record->completeDefinition(); 17628 17629 // Handle attributes before checking the layout. 17630 ProcessDeclAttributeList(S, Record, Attrs); 17631 17632 // We may have deferred checking for a deleted destructor. Check now. 17633 if (CXXRecord) { 17634 auto *Dtor = CXXRecord->getDestructor(); 17635 if (Dtor && Dtor->isImplicit() && 17636 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17637 CXXRecord->setImplicitDestructorIsDeleted(); 17638 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17639 } 17640 } 17641 17642 if (Record->hasAttrs()) { 17643 CheckAlignasUnderalignment(Record); 17644 17645 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17646 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17647 IA->getRange(), IA->getBestCase(), 17648 IA->getInheritanceModel()); 17649 } 17650 17651 // Check if the structure/union declaration is a type that can have zero 17652 // size in C. For C this is a language extension, for C++ it may cause 17653 // compatibility problems. 17654 bool CheckForZeroSize; 17655 if (!getLangOpts().CPlusPlus) { 17656 CheckForZeroSize = true; 17657 } else { 17658 // For C++ filter out types that cannot be referenced in C code. 17659 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17660 CheckForZeroSize = 17661 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17662 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17663 CXXRecord->isCLike(); 17664 } 17665 if (CheckForZeroSize) { 17666 bool ZeroSize = true; 17667 bool IsEmpty = true; 17668 unsigned NonBitFields = 0; 17669 for (RecordDecl::field_iterator I = Record->field_begin(), 17670 E = Record->field_end(); 17671 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17672 IsEmpty = false; 17673 if (I->isUnnamedBitfield()) { 17674 if (!I->isZeroLengthBitField(Context)) 17675 ZeroSize = false; 17676 } else { 17677 ++NonBitFields; 17678 QualType FieldType = I->getType(); 17679 if (FieldType->isIncompleteType() || 17680 !Context.getTypeSizeInChars(FieldType).isZero()) 17681 ZeroSize = false; 17682 } 17683 } 17684 17685 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17686 // allowed in C++, but warn if its declaration is inside 17687 // extern "C" block. 17688 if (ZeroSize) { 17689 Diag(RecLoc, getLangOpts().CPlusPlus ? 17690 diag::warn_zero_size_struct_union_in_extern_c : 17691 diag::warn_zero_size_struct_union_compat) 17692 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17693 } 17694 17695 // Structs without named members are extension in C (C99 6.7.2.1p7), 17696 // but are accepted by GCC. 17697 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17698 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17699 diag::ext_no_named_members_in_struct_union) 17700 << Record->isUnion(); 17701 } 17702 } 17703 } else { 17704 ObjCIvarDecl **ClsFields = 17705 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17706 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17707 ID->setEndOfDefinitionLoc(RBrac); 17708 // Add ivar's to class's DeclContext. 17709 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17710 ClsFields[i]->setLexicalDeclContext(ID); 17711 ID->addDecl(ClsFields[i]); 17712 } 17713 // Must enforce the rule that ivars in the base classes may not be 17714 // duplicates. 17715 if (ID->getSuperClass()) 17716 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17717 } else if (ObjCImplementationDecl *IMPDecl = 17718 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17719 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17720 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17721 // Ivar declared in @implementation never belongs to the implementation. 17722 // Only it is in implementation's lexical context. 17723 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17724 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17725 IMPDecl->setIvarLBraceLoc(LBrac); 17726 IMPDecl->setIvarRBraceLoc(RBrac); 17727 } else if (ObjCCategoryDecl *CDecl = 17728 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17729 // case of ivars in class extension; all other cases have been 17730 // reported as errors elsewhere. 17731 // FIXME. Class extension does not have a LocEnd field. 17732 // CDecl->setLocEnd(RBrac); 17733 // Add ivar's to class extension's DeclContext. 17734 // Diagnose redeclaration of private ivars. 17735 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17736 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17737 if (IDecl) { 17738 if (const ObjCIvarDecl *ClsIvar = 17739 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17740 Diag(ClsFields[i]->getLocation(), 17741 diag::err_duplicate_ivar_declaration); 17742 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17743 continue; 17744 } 17745 for (const auto *Ext : IDecl->known_extensions()) { 17746 if (const ObjCIvarDecl *ClsExtIvar 17747 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17748 Diag(ClsFields[i]->getLocation(), 17749 diag::err_duplicate_ivar_declaration); 17750 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17751 continue; 17752 } 17753 } 17754 } 17755 ClsFields[i]->setLexicalDeclContext(CDecl); 17756 CDecl->addDecl(ClsFields[i]); 17757 } 17758 CDecl->setIvarLBraceLoc(LBrac); 17759 CDecl->setIvarRBraceLoc(RBrac); 17760 } 17761 } 17762 } 17763 17764 /// Determine whether the given integral value is representable within 17765 /// the given type T. 17766 static bool isRepresentableIntegerValue(ASTContext &Context, 17767 llvm::APSInt &Value, 17768 QualType T) { 17769 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17770 "Integral type required!"); 17771 unsigned BitWidth = Context.getIntWidth(T); 17772 17773 if (Value.isUnsigned() || Value.isNonNegative()) { 17774 if (T->isSignedIntegerOrEnumerationType()) 17775 --BitWidth; 17776 return Value.getActiveBits() <= BitWidth; 17777 } 17778 return Value.getMinSignedBits() <= BitWidth; 17779 } 17780 17781 // Given an integral type, return the next larger integral type 17782 // (or a NULL type of no such type exists). 17783 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17784 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17785 // enum checking below. 17786 assert((T->isIntegralType(Context) || 17787 T->isEnumeralType()) && "Integral type required!"); 17788 const unsigned NumTypes = 4; 17789 QualType SignedIntegralTypes[NumTypes] = { 17790 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17791 }; 17792 QualType UnsignedIntegralTypes[NumTypes] = { 17793 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17794 Context.UnsignedLongLongTy 17795 }; 17796 17797 unsigned BitWidth = Context.getTypeSize(T); 17798 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17799 : UnsignedIntegralTypes; 17800 for (unsigned I = 0; I != NumTypes; ++I) 17801 if (Context.getTypeSize(Types[I]) > BitWidth) 17802 return Types[I]; 17803 17804 return QualType(); 17805 } 17806 17807 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17808 EnumConstantDecl *LastEnumConst, 17809 SourceLocation IdLoc, 17810 IdentifierInfo *Id, 17811 Expr *Val) { 17812 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17813 llvm::APSInt EnumVal(IntWidth); 17814 QualType EltTy; 17815 17816 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17817 Val = nullptr; 17818 17819 if (Val) 17820 Val = DefaultLvalueConversion(Val).get(); 17821 17822 if (Val) { 17823 if (Enum->isDependentType() || Val->isTypeDependent() || 17824 Val->containsErrors()) 17825 EltTy = Context.DependentTy; 17826 else { 17827 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17828 // underlying type, but do allow it in all other contexts. 17829 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17830 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17831 // constant-expression in the enumerator-definition shall be a converted 17832 // constant expression of the underlying type. 17833 EltTy = Enum->getIntegerType(); 17834 ExprResult Converted = 17835 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17836 CCEK_Enumerator); 17837 if (Converted.isInvalid()) 17838 Val = nullptr; 17839 else 17840 Val = Converted.get(); 17841 } else if (!Val->isValueDependent() && 17842 !(Val = 17843 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17844 .get())) { 17845 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17846 } else { 17847 if (Enum->isComplete()) { 17848 EltTy = Enum->getIntegerType(); 17849 17850 // In Obj-C and Microsoft mode, require the enumeration value to be 17851 // representable in the underlying type of the enumeration. In C++11, 17852 // we perform a non-narrowing conversion as part of converted constant 17853 // expression checking. 17854 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17855 if (Context.getTargetInfo() 17856 .getTriple() 17857 .isWindowsMSVCEnvironment()) { 17858 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17859 } else { 17860 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17861 } 17862 } 17863 17864 // Cast to the underlying type. 17865 Val = ImpCastExprToType(Val, EltTy, 17866 EltTy->isBooleanType() ? CK_IntegralToBoolean 17867 : CK_IntegralCast) 17868 .get(); 17869 } else if (getLangOpts().CPlusPlus) { 17870 // C++11 [dcl.enum]p5: 17871 // If the underlying type is not fixed, the type of each enumerator 17872 // is the type of its initializing value: 17873 // - If an initializer is specified for an enumerator, the 17874 // initializing value has the same type as the expression. 17875 EltTy = Val->getType(); 17876 } else { 17877 // C99 6.7.2.2p2: 17878 // The expression that defines the value of an enumeration constant 17879 // shall be an integer constant expression that has a value 17880 // representable as an int. 17881 17882 // Complain if the value is not representable in an int. 17883 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17884 Diag(IdLoc, diag::ext_enum_value_not_int) 17885 << toString(EnumVal, 10) << Val->getSourceRange() 17886 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17887 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17888 // Force the type of the expression to 'int'. 17889 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17890 } 17891 EltTy = Val->getType(); 17892 } 17893 } 17894 } 17895 } 17896 17897 if (!Val) { 17898 if (Enum->isDependentType()) 17899 EltTy = Context.DependentTy; 17900 else if (!LastEnumConst) { 17901 // C++0x [dcl.enum]p5: 17902 // If the underlying type is not fixed, the type of each enumerator 17903 // is the type of its initializing value: 17904 // - If no initializer is specified for the first enumerator, the 17905 // initializing value has an unspecified integral type. 17906 // 17907 // GCC uses 'int' for its unspecified integral type, as does 17908 // C99 6.7.2.2p3. 17909 if (Enum->isFixed()) { 17910 EltTy = Enum->getIntegerType(); 17911 } 17912 else { 17913 EltTy = Context.IntTy; 17914 } 17915 } else { 17916 // Assign the last value + 1. 17917 EnumVal = LastEnumConst->getInitVal(); 17918 ++EnumVal; 17919 EltTy = LastEnumConst->getType(); 17920 17921 // Check for overflow on increment. 17922 if (EnumVal < LastEnumConst->getInitVal()) { 17923 // C++0x [dcl.enum]p5: 17924 // If the underlying type is not fixed, the type of each enumerator 17925 // is the type of its initializing value: 17926 // 17927 // - Otherwise the type of the initializing value is the same as 17928 // the type of the initializing value of the preceding enumerator 17929 // unless the incremented value is not representable in that type, 17930 // in which case the type is an unspecified integral type 17931 // sufficient to contain the incremented value. If no such type 17932 // exists, the program is ill-formed. 17933 QualType T = getNextLargerIntegralType(Context, EltTy); 17934 if (T.isNull() || Enum->isFixed()) { 17935 // There is no integral type larger enough to represent this 17936 // value. Complain, then allow the value to wrap around. 17937 EnumVal = LastEnumConst->getInitVal(); 17938 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17939 ++EnumVal; 17940 if (Enum->isFixed()) 17941 // When the underlying type is fixed, this is ill-formed. 17942 Diag(IdLoc, diag::err_enumerator_wrapped) 17943 << toString(EnumVal, 10) 17944 << EltTy; 17945 else 17946 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17947 << toString(EnumVal, 10); 17948 } else { 17949 EltTy = T; 17950 } 17951 17952 // Retrieve the last enumerator's value, extent that type to the 17953 // type that is supposed to be large enough to represent the incremented 17954 // value, then increment. 17955 EnumVal = LastEnumConst->getInitVal(); 17956 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17957 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17958 ++EnumVal; 17959 17960 // If we're not in C++, diagnose the overflow of enumerator values, 17961 // which in C99 means that the enumerator value is not representable in 17962 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17963 // permits enumerator values that are representable in some larger 17964 // integral type. 17965 if (!getLangOpts().CPlusPlus && !T.isNull()) 17966 Diag(IdLoc, diag::warn_enum_value_overflow); 17967 } else if (!getLangOpts().CPlusPlus && 17968 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17969 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17970 Diag(IdLoc, diag::ext_enum_value_not_int) 17971 << toString(EnumVal, 10) << 1; 17972 } 17973 } 17974 } 17975 17976 if (!EltTy->isDependentType()) { 17977 // Make the enumerator value match the signedness and size of the 17978 // enumerator's type. 17979 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17980 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17981 } 17982 17983 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17984 Val, EnumVal); 17985 } 17986 17987 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17988 SourceLocation IILoc) { 17989 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17990 !getLangOpts().CPlusPlus) 17991 return SkipBodyInfo(); 17992 17993 // We have an anonymous enum definition. Look up the first enumerator to 17994 // determine if we should merge the definition with an existing one and 17995 // skip the body. 17996 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17997 forRedeclarationInCurContext()); 17998 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17999 if (!PrevECD) 18000 return SkipBodyInfo(); 18001 18002 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18003 NamedDecl *Hidden; 18004 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18005 SkipBodyInfo Skip; 18006 Skip.Previous = Hidden; 18007 return Skip; 18008 } 18009 18010 return SkipBodyInfo(); 18011 } 18012 18013 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18014 SourceLocation IdLoc, IdentifierInfo *Id, 18015 const ParsedAttributesView &Attrs, 18016 SourceLocation EqualLoc, Expr *Val) { 18017 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18018 EnumConstantDecl *LastEnumConst = 18019 cast_or_null<EnumConstantDecl>(lastEnumConst); 18020 18021 // The scope passed in may not be a decl scope. Zip up the scope tree until 18022 // we find one that is. 18023 S = getNonFieldDeclScope(S); 18024 18025 // Verify that there isn't already something declared with this name in this 18026 // scope. 18027 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18028 LookupName(R, S); 18029 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18030 18031 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18032 // Maybe we will complain about the shadowed template parameter. 18033 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18034 // Just pretend that we didn't see the previous declaration. 18035 PrevDecl = nullptr; 18036 } 18037 18038 // C++ [class.mem]p15: 18039 // If T is the name of a class, then each of the following shall have a name 18040 // different from T: 18041 // - every enumerator of every member of class T that is an unscoped 18042 // enumerated type 18043 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18044 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18045 DeclarationNameInfo(Id, IdLoc)); 18046 18047 EnumConstantDecl *New = 18048 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18049 if (!New) 18050 return nullptr; 18051 18052 if (PrevDecl) { 18053 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18054 // Check for other kinds of shadowing not already handled. 18055 CheckShadow(New, PrevDecl, R); 18056 } 18057 18058 // When in C++, we may get a TagDecl with the same name; in this case the 18059 // enum constant will 'hide' the tag. 18060 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18061 "Received TagDecl when not in C++!"); 18062 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18063 if (isa<EnumConstantDecl>(PrevDecl)) 18064 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18065 else 18066 Diag(IdLoc, diag::err_redefinition) << Id; 18067 notePreviousDefinition(PrevDecl, IdLoc); 18068 return nullptr; 18069 } 18070 } 18071 18072 // Process attributes. 18073 ProcessDeclAttributeList(S, New, Attrs); 18074 AddPragmaAttributes(S, New); 18075 18076 // Register this decl in the current scope stack. 18077 New->setAccess(TheEnumDecl->getAccess()); 18078 PushOnScopeChains(New, S); 18079 18080 ActOnDocumentableDecl(New); 18081 18082 return New; 18083 } 18084 18085 // Returns true when the enum initial expression does not trigger the 18086 // duplicate enum warning. A few common cases are exempted as follows: 18087 // Element2 = Element1 18088 // Element2 = Element1 + 1 18089 // Element2 = Element1 - 1 18090 // Where Element2 and Element1 are from the same enum. 18091 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18092 Expr *InitExpr = ECD->getInitExpr(); 18093 if (!InitExpr) 18094 return true; 18095 InitExpr = InitExpr->IgnoreImpCasts(); 18096 18097 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18098 if (!BO->isAdditiveOp()) 18099 return true; 18100 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18101 if (!IL) 18102 return true; 18103 if (IL->getValue() != 1) 18104 return true; 18105 18106 InitExpr = BO->getLHS(); 18107 } 18108 18109 // This checks if the elements are from the same enum. 18110 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18111 if (!DRE) 18112 return true; 18113 18114 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18115 if (!EnumConstant) 18116 return true; 18117 18118 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18119 Enum) 18120 return true; 18121 18122 return false; 18123 } 18124 18125 // Emits a warning when an element is implicitly set a value that 18126 // a previous element has already been set to. 18127 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18128 EnumDecl *Enum, QualType EnumType) { 18129 // Avoid anonymous enums 18130 if (!Enum->getIdentifier()) 18131 return; 18132 18133 // Only check for small enums. 18134 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18135 return; 18136 18137 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18138 return; 18139 18140 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18141 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18142 18143 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18144 18145 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18146 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18147 18148 // Use int64_t as a key to avoid needing special handling for map keys. 18149 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18150 llvm::APSInt Val = D->getInitVal(); 18151 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18152 }; 18153 18154 DuplicatesVector DupVector; 18155 ValueToVectorMap EnumMap; 18156 18157 // Populate the EnumMap with all values represented by enum constants without 18158 // an initializer. 18159 for (auto *Element : Elements) { 18160 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18161 18162 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18163 // this constant. Skip this enum since it may be ill-formed. 18164 if (!ECD) { 18165 return; 18166 } 18167 18168 // Constants with initalizers are handled in the next loop. 18169 if (ECD->getInitExpr()) 18170 continue; 18171 18172 // Duplicate values are handled in the next loop. 18173 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18174 } 18175 18176 if (EnumMap.size() == 0) 18177 return; 18178 18179 // Create vectors for any values that has duplicates. 18180 for (auto *Element : Elements) { 18181 // The last loop returned if any constant was null. 18182 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18183 if (!ValidDuplicateEnum(ECD, Enum)) 18184 continue; 18185 18186 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18187 if (Iter == EnumMap.end()) 18188 continue; 18189 18190 DeclOrVector& Entry = Iter->second; 18191 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18192 // Ensure constants are different. 18193 if (D == ECD) 18194 continue; 18195 18196 // Create new vector and push values onto it. 18197 auto Vec = std::make_unique<ECDVector>(); 18198 Vec->push_back(D); 18199 Vec->push_back(ECD); 18200 18201 // Update entry to point to the duplicates vector. 18202 Entry = Vec.get(); 18203 18204 // Store the vector somewhere we can consult later for quick emission of 18205 // diagnostics. 18206 DupVector.emplace_back(std::move(Vec)); 18207 continue; 18208 } 18209 18210 ECDVector *Vec = Entry.get<ECDVector*>(); 18211 // Make sure constants are not added more than once. 18212 if (*Vec->begin() == ECD) 18213 continue; 18214 18215 Vec->push_back(ECD); 18216 } 18217 18218 // Emit diagnostics. 18219 for (const auto &Vec : DupVector) { 18220 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18221 18222 // Emit warning for one enum constant. 18223 auto *FirstECD = Vec->front(); 18224 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18225 << FirstECD << toString(FirstECD->getInitVal(), 10) 18226 << FirstECD->getSourceRange(); 18227 18228 // Emit one note for each of the remaining enum constants with 18229 // the same value. 18230 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18231 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18232 << ECD << toString(ECD->getInitVal(), 10) 18233 << ECD->getSourceRange(); 18234 } 18235 } 18236 18237 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18238 bool AllowMask) const { 18239 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18240 assert(ED->isCompleteDefinition() && "expected enum definition"); 18241 18242 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18243 llvm::APInt &FlagBits = R.first->second; 18244 18245 if (R.second) { 18246 for (auto *E : ED->enumerators()) { 18247 const auto &EVal = E->getInitVal(); 18248 // Only single-bit enumerators introduce new flag values. 18249 if (EVal.isPowerOf2()) 18250 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18251 } 18252 } 18253 18254 // A value is in a flag enum if either its bits are a subset of the enum's 18255 // flag bits (the first condition) or we are allowing masks and the same is 18256 // true of its complement (the second condition). When masks are allowed, we 18257 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18258 // 18259 // While it's true that any value could be used as a mask, the assumption is 18260 // that a mask will have all of the insignificant bits set. Anything else is 18261 // likely a logic error. 18262 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18263 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18264 } 18265 18266 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18267 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18268 const ParsedAttributesView &Attrs) { 18269 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18270 QualType EnumType = Context.getTypeDeclType(Enum); 18271 18272 ProcessDeclAttributeList(S, Enum, Attrs); 18273 18274 if (Enum->isDependentType()) { 18275 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18276 EnumConstantDecl *ECD = 18277 cast_or_null<EnumConstantDecl>(Elements[i]); 18278 if (!ECD) continue; 18279 18280 ECD->setType(EnumType); 18281 } 18282 18283 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18284 return; 18285 } 18286 18287 // TODO: If the result value doesn't fit in an int, it must be a long or long 18288 // long value. ISO C does not support this, but GCC does as an extension, 18289 // emit a warning. 18290 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18291 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18292 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18293 18294 // Verify that all the values are okay, compute the size of the values, and 18295 // reverse the list. 18296 unsigned NumNegativeBits = 0; 18297 unsigned NumPositiveBits = 0; 18298 18299 // Keep track of whether all elements have type int. 18300 bool AllElementsInt = true; 18301 18302 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18303 EnumConstantDecl *ECD = 18304 cast_or_null<EnumConstantDecl>(Elements[i]); 18305 if (!ECD) continue; // Already issued a diagnostic. 18306 18307 const llvm::APSInt &InitVal = ECD->getInitVal(); 18308 18309 // Keep track of the size of positive and negative values. 18310 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18311 NumPositiveBits = std::max(NumPositiveBits, 18312 (unsigned)InitVal.getActiveBits()); 18313 else 18314 NumNegativeBits = std::max(NumNegativeBits, 18315 (unsigned)InitVal.getMinSignedBits()); 18316 18317 // Keep track of whether every enum element has type int (very common). 18318 if (AllElementsInt) 18319 AllElementsInt = ECD->getType() == Context.IntTy; 18320 } 18321 18322 // Figure out the type that should be used for this enum. 18323 QualType BestType; 18324 unsigned BestWidth; 18325 18326 // C++0x N3000 [conv.prom]p3: 18327 // An rvalue of an unscoped enumeration type whose underlying 18328 // type is not fixed can be converted to an rvalue of the first 18329 // of the following types that can represent all the values of 18330 // the enumeration: int, unsigned int, long int, unsigned long 18331 // int, long long int, or unsigned long long int. 18332 // C99 6.4.4.3p2: 18333 // An identifier declared as an enumeration constant has type int. 18334 // The C99 rule is modified by a gcc extension 18335 QualType BestPromotionType; 18336 18337 bool Packed = Enum->hasAttr<PackedAttr>(); 18338 // -fshort-enums is the equivalent to specifying the packed attribute on all 18339 // enum definitions. 18340 if (LangOpts.ShortEnums) 18341 Packed = true; 18342 18343 // If the enum already has a type because it is fixed or dictated by the 18344 // target, promote that type instead of analyzing the enumerators. 18345 if (Enum->isComplete()) { 18346 BestType = Enum->getIntegerType(); 18347 if (BestType->isPromotableIntegerType()) 18348 BestPromotionType = Context.getPromotedIntegerType(BestType); 18349 else 18350 BestPromotionType = BestType; 18351 18352 BestWidth = Context.getIntWidth(BestType); 18353 } 18354 else if (NumNegativeBits) { 18355 // If there is a negative value, figure out the smallest integer type (of 18356 // int/long/longlong) that fits. 18357 // If it's packed, check also if it fits a char or a short. 18358 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18359 BestType = Context.SignedCharTy; 18360 BestWidth = CharWidth; 18361 } else if (Packed && NumNegativeBits <= ShortWidth && 18362 NumPositiveBits < ShortWidth) { 18363 BestType = Context.ShortTy; 18364 BestWidth = ShortWidth; 18365 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18366 BestType = Context.IntTy; 18367 BestWidth = IntWidth; 18368 } else { 18369 BestWidth = Context.getTargetInfo().getLongWidth(); 18370 18371 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18372 BestType = Context.LongTy; 18373 } else { 18374 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18375 18376 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18377 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18378 BestType = Context.LongLongTy; 18379 } 18380 } 18381 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18382 } else { 18383 // If there is no negative value, figure out the smallest type that fits 18384 // all of the enumerator values. 18385 // If it's packed, check also if it fits a char or a short. 18386 if (Packed && NumPositiveBits <= CharWidth) { 18387 BestType = Context.UnsignedCharTy; 18388 BestPromotionType = Context.IntTy; 18389 BestWidth = CharWidth; 18390 } else if (Packed && NumPositiveBits <= ShortWidth) { 18391 BestType = Context.UnsignedShortTy; 18392 BestPromotionType = Context.IntTy; 18393 BestWidth = ShortWidth; 18394 } else if (NumPositiveBits <= IntWidth) { 18395 BestType = Context.UnsignedIntTy; 18396 BestWidth = IntWidth; 18397 BestPromotionType 18398 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18399 ? Context.UnsignedIntTy : Context.IntTy; 18400 } else if (NumPositiveBits <= 18401 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18402 BestType = Context.UnsignedLongTy; 18403 BestPromotionType 18404 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18405 ? Context.UnsignedLongTy : Context.LongTy; 18406 } else { 18407 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18408 assert(NumPositiveBits <= BestWidth && 18409 "How could an initializer get larger than ULL?"); 18410 BestType = Context.UnsignedLongLongTy; 18411 BestPromotionType 18412 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18413 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18414 } 18415 } 18416 18417 // Loop over all of the enumerator constants, changing their types to match 18418 // the type of the enum if needed. 18419 for (auto *D : Elements) { 18420 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18421 if (!ECD) continue; // Already issued a diagnostic. 18422 18423 // Standard C says the enumerators have int type, but we allow, as an 18424 // extension, the enumerators to be larger than int size. If each 18425 // enumerator value fits in an int, type it as an int, otherwise type it the 18426 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18427 // that X has type 'int', not 'unsigned'. 18428 18429 // Determine whether the value fits into an int. 18430 llvm::APSInt InitVal = ECD->getInitVal(); 18431 18432 // If it fits into an integer type, force it. Otherwise force it to match 18433 // the enum decl type. 18434 QualType NewTy; 18435 unsigned NewWidth; 18436 bool NewSign; 18437 if (!getLangOpts().CPlusPlus && 18438 !Enum->isFixed() && 18439 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18440 NewTy = Context.IntTy; 18441 NewWidth = IntWidth; 18442 NewSign = true; 18443 } else if (ECD->getType() == BestType) { 18444 // Already the right type! 18445 if (getLangOpts().CPlusPlus) 18446 // C++ [dcl.enum]p4: Following the closing brace of an 18447 // enum-specifier, each enumerator has the type of its 18448 // enumeration. 18449 ECD->setType(EnumType); 18450 continue; 18451 } else { 18452 NewTy = BestType; 18453 NewWidth = BestWidth; 18454 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18455 } 18456 18457 // Adjust the APSInt value. 18458 InitVal = InitVal.extOrTrunc(NewWidth); 18459 InitVal.setIsSigned(NewSign); 18460 ECD->setInitVal(InitVal); 18461 18462 // Adjust the Expr initializer and type. 18463 if (ECD->getInitExpr() && 18464 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18465 ECD->setInitExpr(ImplicitCastExpr::Create( 18466 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18467 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18468 if (getLangOpts().CPlusPlus) 18469 // C++ [dcl.enum]p4: Following the closing brace of an 18470 // enum-specifier, each enumerator has the type of its 18471 // enumeration. 18472 ECD->setType(EnumType); 18473 else 18474 ECD->setType(NewTy); 18475 } 18476 18477 Enum->completeDefinition(BestType, BestPromotionType, 18478 NumPositiveBits, NumNegativeBits); 18479 18480 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18481 18482 if (Enum->isClosedFlag()) { 18483 for (Decl *D : Elements) { 18484 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18485 if (!ECD) continue; // Already issued a diagnostic. 18486 18487 llvm::APSInt InitVal = ECD->getInitVal(); 18488 if (InitVal != 0 && !InitVal.isPowerOf2() && 18489 !IsValueInFlagEnum(Enum, InitVal, true)) 18490 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18491 << ECD << Enum; 18492 } 18493 } 18494 18495 // Now that the enum type is defined, ensure it's not been underaligned. 18496 if (Enum->hasAttrs()) 18497 CheckAlignasUnderalignment(Enum); 18498 } 18499 18500 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18501 SourceLocation StartLoc, 18502 SourceLocation EndLoc) { 18503 StringLiteral *AsmString = cast<StringLiteral>(expr); 18504 18505 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18506 AsmString, StartLoc, 18507 EndLoc); 18508 CurContext->addDecl(New); 18509 return New; 18510 } 18511 18512 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18513 IdentifierInfo* AliasName, 18514 SourceLocation PragmaLoc, 18515 SourceLocation NameLoc, 18516 SourceLocation AliasNameLoc) { 18517 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18518 LookupOrdinaryName); 18519 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18520 AttributeCommonInfo::AS_Pragma); 18521 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18522 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18523 18524 // If a declaration that: 18525 // 1) declares a function or a variable 18526 // 2) has external linkage 18527 // already exists, add a label attribute to it. 18528 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18529 if (isDeclExternC(PrevDecl)) 18530 PrevDecl->addAttr(Attr); 18531 else 18532 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18533 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18534 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18535 } else 18536 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18537 } 18538 18539 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18540 SourceLocation PragmaLoc, 18541 SourceLocation NameLoc) { 18542 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18543 18544 if (PrevDecl) { 18545 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18546 } else { 18547 (void)WeakUndeclaredIdentifiers.insert( 18548 std::pair<IdentifierInfo*,WeakInfo> 18549 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18550 } 18551 } 18552 18553 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18554 IdentifierInfo* AliasName, 18555 SourceLocation PragmaLoc, 18556 SourceLocation NameLoc, 18557 SourceLocation AliasNameLoc) { 18558 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18559 LookupOrdinaryName); 18560 WeakInfo W = WeakInfo(Name, NameLoc); 18561 18562 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18563 if (!PrevDecl->hasAttr<AliasAttr>()) 18564 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18565 DeclApplyPragmaWeak(TUScope, ND, W); 18566 } else { 18567 (void)WeakUndeclaredIdentifiers.insert( 18568 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18569 } 18570 } 18571 18572 Decl *Sema::getObjCDeclContext() const { 18573 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18574 } 18575 18576 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18577 bool Final) { 18578 assert(FD && "Expected non-null FunctionDecl"); 18579 18580 // SYCL functions can be template, so we check if they have appropriate 18581 // attribute prior to checking if it is a template. 18582 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18583 return FunctionEmissionStatus::Emitted; 18584 18585 // Templates are emitted when they're instantiated. 18586 if (FD->isDependentContext()) 18587 return FunctionEmissionStatus::TemplateDiscarded; 18588 18589 // Check whether this function is an externally visible definition. 18590 auto IsEmittedForExternalSymbol = [this, FD]() { 18591 // We have to check the GVA linkage of the function's *definition* -- if we 18592 // only have a declaration, we don't know whether or not the function will 18593 // be emitted, because (say) the definition could include "inline". 18594 FunctionDecl *Def = FD->getDefinition(); 18595 18596 return Def && !isDiscardableGVALinkage( 18597 getASTContext().GetGVALinkageForFunction(Def)); 18598 }; 18599 18600 if (LangOpts.OpenMPIsDevice) { 18601 // In OpenMP device mode we will not emit host only functions, or functions 18602 // we don't need due to their linkage. 18603 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18604 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18605 // DevTy may be changed later by 18606 // #pragma omp declare target to(*) device_type(*). 18607 // Therefore DevTy having no value does not imply host. The emission status 18608 // will be checked again at the end of compilation unit with Final = true. 18609 if (DevTy.hasValue()) 18610 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18611 return FunctionEmissionStatus::OMPDiscarded; 18612 // If we have an explicit value for the device type, or we are in a target 18613 // declare context, we need to emit all extern and used symbols. 18614 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18615 if (IsEmittedForExternalSymbol()) 18616 return FunctionEmissionStatus::Emitted; 18617 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18618 // we'll omit it. 18619 if (Final) 18620 return FunctionEmissionStatus::OMPDiscarded; 18621 } else if (LangOpts.OpenMP > 45) { 18622 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18623 // function. In 5.0, no_host was introduced which might cause a function to 18624 // be ommitted. 18625 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18626 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18627 if (DevTy.hasValue()) 18628 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18629 return FunctionEmissionStatus::OMPDiscarded; 18630 } 18631 18632 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18633 return FunctionEmissionStatus::Emitted; 18634 18635 if (LangOpts.CUDA) { 18636 // When compiling for device, host functions are never emitted. Similarly, 18637 // when compiling for host, device and global functions are never emitted. 18638 // (Technically, we do emit a host-side stub for global functions, but this 18639 // doesn't count for our purposes here.) 18640 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18641 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18642 return FunctionEmissionStatus::CUDADiscarded; 18643 if (!LangOpts.CUDAIsDevice && 18644 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18645 return FunctionEmissionStatus::CUDADiscarded; 18646 18647 if (IsEmittedForExternalSymbol()) 18648 return FunctionEmissionStatus::Emitted; 18649 } 18650 18651 // Otherwise, the function is known-emitted if it's in our set of 18652 // known-emitted functions. 18653 return FunctionEmissionStatus::Unknown; 18654 } 18655 18656 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18657 // Host-side references to a __global__ function refer to the stub, so the 18658 // function itself is never emitted and therefore should not be marked. 18659 // If we have host fn calls kernel fn calls host+device, the HD function 18660 // does not get instantiated on the host. We model this by omitting at the 18661 // call to the kernel from the callgraph. This ensures that, when compiling 18662 // for host, only HD functions actually called from the host get marked as 18663 // known-emitted. 18664 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18665 IdentifyCUDATarget(Callee) == CFT_Global; 18666 } 18667